Automating Word document formatting is a frequent requirement in .NET development, and setting document backgrounds (color or image) is a common task for enhancing visual presentation. Free Spire.Doc for .NET is a free component for Word document manipulation that operates without Microsoft Office. This article demonstrates how to use this component to set background colors or images in Word documents using C#.
Environment Setup
Install Free Spire.Doc for .NET via NuGet Package Manager:
- Open Visual Studio and create a .NET project (Console Application, ASP.NET Core, etc.).
- Right-click the project → "Manage NuGet Packages" → search for "Free Spire.Doc" → install the latest version.
- Alternatively, use the NuGet Package Manager Console:
Install-Package FreeSpire.Doc
Setting a Background Color
Access the Document.Background property. First specify the background type as BackgroundType.Color, then assign a color value.
Complete Code Example:
using Spire.Doc;
using System.Drawing;
using Spire.Doc.Documents;
namespace SetBackgroundColor
{
class Program
{
static void Main(string[] args)
{
Document doc = new Document();
doc.LoadFromFile("Sample.docx");
doc.Background.Type = BackgroundType.Color;
doc.Background.Color = Color.AliceBlue;
doc.SaveToFile("SolidBackground.docx", FileFormat.Docx);
}
}
}
Setting a Background Image
Change Background.Type to BackgroundType.Picture and assign an image to Background.Picture.
Complete Code Example:
using Spire.Doc;
using System.Drawing;
using Spire.Doc.Documents;
namespace SetBackgroundImage
{
class Program
{
static void Main(string[] args)
{
try
{
Document doc = new Document();
doc.LoadFromFile("Sample.docx");
doc.Background.Type = BackgroundType.Picture;
doc.Background.Picture = Image.FromFile(@"C:\Images\background.png");
doc.SaveToFile("ImageBackground.docx", FileFormat.Docx);
Console.WriteLine("Background image applied successfully.");
}
catch (Exception ex)
{
Console.WriteLine($"Operation failed: {ex.Message}");
}
}
}
}
Important Notes
- Supported Image Formats: JPG, PNG, BMP, and other common formats. Use images with dimensions proportional to a standard A4 page (210×297 mm) to minimize distortion.
- Display Mode: Background images tile by default. No stretch mode is directly available. To simulate stretching, resize the image programmatically using
System.Drawingbefore assigning it. - File Paths: Use absolute paths (e.g.,
C:\Documents\bg.jpg) to avoid file-not-found errors.
These methods allow developers to customize document backgrounds in C# applications. Although the free version has certain limitations on document size, it remains a functional and easy-to-use solution for basic document processing needs.