DEV Community

Jack9012
Jack9012

Posted on

How to Add Watermarks to Excel in C#: Two Practical Approaches

In scenarios such as report distribution, contract archiving, and confidential data sharing, adding a watermark to an Excel document is a simple and practical means of copyright identification. A watermark can be composed of either an image or text. Watermarks with wording such as "Confidential," "Internal Use Only," and "Do Not Distribute" are widely used across business contexts worldwide.

Add Watermarks to Excel in C#

This article will demonstrate how to use a free .NET Excel library to add watermarks to Excel documents in C#, compare two implementation approaches—header image watermarks and background image watermarks—and supplement this with a piece of helper code for generating text watermark images, so that it can be used directly even when no ready-made watermark image is available.

Installation

The library can be brought into the project via NuGet.

  • NuGet Package Manager Console
  Install-Package FreeSpire.XLS
Enter fullscreen mode Exit fullscreen mode
  • .NET CLI
  dotnet add package FreeSpire.XLS
Enter fullscreen mode Exit fullscreen mode

After installation is complete, import the namespace Spire.Xls in the code to use it.

Comparison of the Two Watermark Solutions

An Excel watermark is not a true "watermark" object. It is essentially simulated through a header image or a worksheet background image, so the two solutions differ significantly in terms of printing, view, positioning, and other aspects.

Comparison Item Header Image Watermark Background Image Watermark
Print output Printed along with the document Does not appear in the print result
View visibility Visible only in "Page Layout" or "Page Break Preview" mode, not in Normal view Visible in all view modes
Position control Header area margins need to be adjusted manually to center the image Automatically fills the entire worksheet data area
Visual consistency Affected by pagination; adjacent pages may be misaligned The entire worksheet displays only the same image

Header Image Watermark

  • Advantages : The watermark appears in the document's final print output, making it suitable for scenarios that must be printed and archived.
  • Disadvantages : It is not visible in Excel's "Normal" view and can only be seen in "Page Layout" or "Page Break Preview"; to position the image exactly in the center of the page, the top and left margins of the image must be adjusted carefully.

Background Image Watermark

  • Advantages : The watermark image covers the entire worksheet, producing a consistent effect.
  • Disadvantages : The watermark does not appear in the print output.

Solution 1: Add an Image Watermark Through the Header

The following example iterates through all worksheets in the document and sets the same watermark image in the center position of the header.

using Spire.Xls;
using System.Drawing;

namespace AddWatermarkToExcelUsingHeader
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a Workbook object
            Workbook workbook = new Workbook();

            // Load the Excel document
            workbook.LoadFromFile(@"C:\Users\Administrator\Desktop\Input.xlsx");

            // Load the watermark image
            Image image = Image.FromFile(@"C:\Users\Administrator\Desktop\confidential.png");

            // Iterate through all worksheets in the document
            for (int i = 0; i < workbook.Worksheets.Count; i++)
            {
                // Get the specified worksheet
                Worksheet worksheet = workbook.Worksheets[i];

                // Insert an image placeholder in the center of the header
                worksheet.PageSetup.CenterHeader = "&G";

                // Set the image in the center of the header
                worksheet.PageSetup.CenterHeaderImage = image;
            }

            // Save the resulting file
            workbook.SaveToFile("AddWatermark.xlsx", ExcelVersion.Version2016);

            // Release resources
            workbook.Dispose();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Note: &G is Excel's own header image placeholder. All text (such as the word "Confidential") should be baked directly into the image, rather than written into the CenterHeader string.

Solution 2: Set the Image as a Worksheet Background

The following example uses an image as a worksheet background watermark, which is suitable for screen-only viewing scenarios that require strong visibility.

using Spire.Xls;
using System.Drawing;

namespace AddWatermarkToExcelUsingBackground
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a Workbook object
            Workbook workbook = new Workbook();

            // Load the Excel document
            workbook.LoadFromFile(@"C:\Users\Administrator\Desktop\Input.xlsx");

            // Load the watermark image
            Bitmap bitmapImage = new Bitmap(Image.FromFile(@"C:\Users\Administrator\Desktop\sample.png"));

            // Iterate through all worksheets in the document
            for (int i = 0; i < workbook.Worksheets.Count; i++)
            {
                // Get the specified worksheet
                Worksheet worksheet = workbook.Worksheets[i];

                // Set the image as the background of the worksheet
                worksheet.PageSetup.BackgroundImage = bitmapImage;
            }

            // Save the resulting file
            workbook.SaveToFile("AddWatermark.xlsx", ExcelVersion.Version2016);

            // Release resources
            workbook.Dispose();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Generation of Text Watermarks

In real-world business scenarios, watermarks are often dynamic text such as "Confidential" or "Internal Use Only," and there is no need for a designer to provide a PNG every time. You can use System.Drawing to draw a text watermark image with a transparent background in memory, and then reuse it with Solution 1 or Solution 2.

using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;

public static class WatermarkHelper
{
    /// <summary>
    /// Generates a text watermark image (transparent background, tilted -30°)
    /// </summary>
    /// <param name="text">Watermark text, such as "Confidential"</param>
    /// <param name="width">Canvas width</param>
    /// <param name="height">Canvas height</param>
    /// <returns>A Bitmap object with a transparent background</returns>
    public static Bitmap Create(string text, int width, int height)
    {
        Bitmap bmp = new Bitmap(width, height, PixelFormat.Format32bppArgb);

        using (Graphics g = Graphics.FromImage(bmp))
        {
            g.Clear(Color.Transparent);
            g.SmoothingMode = SmoothingMode.AntiAlias;
            g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit;

            using (Font font = new Font("Arial", 60, FontStyle.Bold))
            using (SolidBrush brush = new SolidBrush(Color.FromArgb(60, Color.Red)))
            {
                // Calculate the text size and center it
                SizeF size = g.MeasureString(text, font);

                // Translate to the center of the canvas, then rotate, so that the drawn text is centered
                g.TranslateTransform(width / 2f, height / 2f);
                g.RotateTransform(-30);

                g.DrawString(text, font, brush, -size.Width / 2f, -size.Height / 2f);
            }
        }

        return bmp;
    }
}
Enter fullscreen mode Exit fullscreen mode

When calling it, simply pass the generated Bitmap directly to either of the two solutions above:

// Generate a text watermark image
Bitmap watermarkImage = WatermarkHelper.Create("Confidential", 800, 600);

// Use it as a worksheet background watermark
workbook.Worksheets[0].PageSetup.BackgroundImage = watermarkImage;
Enter fullscreen mode Exit fullscreen mode

Font Consistency Recommendations

System.Drawing renders text using fonts installed on the system by default. In different environments (such as Linux servers or containerized deployments), font loss may occur, causing text to render incorrectly. In production environments, it is recommended to:

  1. Package font files into the application;
  2. Load private fonts through PrivateFontCollection and then pass them to the Font constructor;
  3. Or render all potentially used watermark text into PNGs in advance and distribute them as static resources with the project.

Solution Selection Reference

Scenario Recommended Solution
Reports need to be printed and archived, and documents need to be retained long-term Solution 1: Header image watermark
Screen-only viewing, internal presentations, emphasis on intuitive visibility Solution 2: Background image watermark

Summary

The free .NET Excel library itself does not directly provide a "watermark" object. Instead, it implements watermarks through two mechanisms: header images or worksheet background images. By passing any Image/Bitmap to CenterHeaderImage or BackgroundImage, watermark addition is complete; combined with a short piece of text drawing code, watermarks such as "Confidential" and "Internal Use Only" can be generated flexibly without relying on external assets.

In actual projects, it is recommended to encapsulate "image generation + watermark injection" into independent utility methods, exposing only a small number of parameters such as file path, watermark text, and visibility to the outside. This minimizes the cost of reuse when dealing with multiple business lines and multiple templates.

Top comments (0)