DEV Community

Jeremy K.
Jeremy K.

Posted on

Adding Text Watermarks to PDF Documents with C#

In C# development, adding text watermarks to PDFs is a common requirement for copyright protection, document status labeling and content misuse prevention. Automating watermarking via code is far more efficient and manageable than manual operation with desktop PDF tools, especially for batch processing.

This guide demonstrates how to use the free library Free Spire.PDF for .NET to implement two typical text watermark types in C#: full-page tiled background watermarks and single localized watermarks. We also cover common customizations including transparency and rotation angle configuration.


1. Environment Preparation

1.1 Install Free Spire.PDF

You can install the library via Visual Studio’s NuGet Package Manager:

  1. Right-click your project → Manage NuGet Packages
  2. Search for FreeSpire.PDF and install the latest stable release.

Alternatively, run the command below in the Package Manager Console:

Install-Package FreeSpire.PDF
Enter fullscreen mode Exit fullscreen mode

Note: This is a free community edition. It has a usage limit: it only processes the first 10 pages of a PDF. Extra pages will be silently truncated without throwing exceptions. This library is ideal for small PDF files, development and testing scenarios.

1.2 Import Required Namespaces

Add the following references at the top of your code file:

using Spire.Pdf;
using Spire.Pdf.Graphics;
using System.Drawing;
Enter fullscreen mode Exit fullscreen mode

2. Create Tiled Background Watermarks

PdfTilingBrush is a built-in tiling brush from Free Spire.PDF. By defining tile width and height, you can generate repeating grid-style watermarks across the entire page. This approach works perfectly for background labels such as Internal Use Only or Draft.

Below is the complete implementation code:

using Spire.Pdf;
using Spire.Pdf.Graphics;
using System.Drawing;

namespace TextWatermarkDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            // Use using statement to auto-release PDF resources (C# best practice)
            using (PdfDocument pdf = new PdfDocument())
            {
                pdf.LoadFromFile("sample.pdf");

                // Set tile size to control watermark spacing
                float tileWidth = 260f;
                float tileHeight = 260f;

                // Initialize tiling brush
                PdfTilingBrush brush = new PdfTilingBrush(new SizeF(tileWidth, tileHeight));

                // Set watermark transparency (0.0 = fully transparent, 1.0 = fully opaque)
                brush.Graphics.SetTransparency(0.3f);
                brush.Graphics.Save();

                // Move drawing origin to tile center + rotate canvas
                brush.Graphics.TranslateTransform(brush.Size.Width / 2, brush.Size.Height / 2);
                brush.Graphics.RotateTransform(-45); // Rotate 45 degrees counterclockwise

                // Define font (Microsoft YaHei, size 24, embedded)
                PdfTrueTypeFont font = new PdfTrueTypeFont("Microsoft YaHei", 24f, PdfFontStyle.Regular, true);
                string watermarkText = "Internal Document";

                // Draw centered watermark text inside each tile
                brush.Graphics.DrawString(
                    watermarkText,
                    font,
                    PdfBrushes.Gray,
                    0,
                    0,
                    new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle));

                brush.Graphics.Restore();
                brush.Graphics.SetTransparency(1f);

                // Apply tiled watermark to every page
                foreach (PdfPageBase page in pdf.Pages)
                {
                    page.Canvas.DrawRectangle(
                        brush,
                        new RectangleF(0, 0, page.Canvas.ClientSize.Width, page.Canvas.ClientSize.Height)
                    );
                }

                // Export the final PDF
                pdf.SaveToFile("output.pdf");
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Code Explanation

  • Tile Size: tileWidth and tileHeight control the gap between repeated watermarks. The page will be fully filled with tiles of this dimension.
  • PdfTilingBrush: When used to draw a full-page rectangle, it automatically tiles the predefined graphic across the entire area.
  • Transparency: SetTransparency() adjusts watermark opacity with a range from 0.0 to 1.0.
  • Coordinate Transformation: TranslateTransform shifts the drawing point to the tile center; RotateTransform tilts the watermark for a better visual effect.
  • Font Setting: PdfTrueTypeFont supports custom system fonts and font embedding.
  • Page Rendering: Loop through all pages and draw the tiling brush over the full page canvas.

3. Add a Single Localized Text Watermark

If you only need a standalone watermark at a specific position (header, footer, corner, etc.), draw text directly on the page canvas with specified coordinates. This lightweight method is suitable for copyright statements, company names and page markers.

using Spire.Pdf;
using Spire.Pdf.Graphics;
using System.Drawing;

namespace TextWatermarkDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            using (PdfDocument pdf = new PdfDocument())
            {
                pdf.LoadFromFile("sample.pdf");

                foreach (PdfPageBase page in pdf.Pages)
                {
                    // Semi-transparent solid color brush
                    PdfBrush brush = new PdfSolidBrush(Color.FromArgb(60, Color.DarkBlue));
                    // Use built-in PDF standard font (no embedding, smaller file size)
                    PdfFont font = new PdfFont(PdfFontFamily.TimesRoman, 22f);
                    string waterText = "© 2026 Copyright";

                    // Calculate coordinates for bottom-right placement
                    float x = page.ActualSize.Width - 220;
                    float y = page.ActualSize.Height - 40;

                    // Draw watermark at target position
                    page.Canvas.DrawString(waterText, font, brush, x, y);
                }

                pdf.SaveToFile("simple_watermark.pdf");
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Key Parameter Explanation

  • Alpha Transparency: Color.FromArgb(Alpha, Color) — the alpha value ranges from 0 to 255; a smaller value means higher transparency.
  • Standard PDF Font: PdfFontFamily.TimesRoman is a native PDF font. It requires no font embedding and reduces file size, but only supports Latin characters.
  • Page Dimension: page.ActualSize retrieves the real width and height of the page for relative positioning.

Positioning Guide

Use the formulas below to place watermarks accurately (add custom margins as needed):

  • Bottom-right: x = Page Width - Text Width - Margin, y = Page Height - Margin
  • Bottom-left: x = Margin, y = Page Height - Margin
  • Page center: x = (Page Width - Text Width) / 2, y = (Page Height - Text Height) / 2

Tip: Use font.MeasureString() to get the exact text size for precise layout and avoid text overflow.


4. Best Practices & Usage Notes

4.1 Watermark Type Selection

Choose the solution based on your business scenario:

Scenario Recommended Solution
Full-page background labels (document classification, internal files, draft marks) Tiled background watermark
Copyright notices, company names, page numbers Single localized watermark
Repeating tilted watermarks that do not obscure main content Tiled watermark + low transparency

4.2 Optimize Tiled Watermarks

  • Tile Size: Set tileWidth and tileHeight between 200–400pt. Too small causes text overlap; too large results in sparse watermarks.
  • Font Size: 18–28pt is recommended. Keep the font size noticeably smaller than the tile size.
  • Rotation Angle: -30° or -45° are the most common choices for balanced visuals.

5. Conclusion

This article introduces two mainstream approaches to adding text watermarks to PDFs with C#: tiled background watermarks and single localized watermarks. Both solutions include runnable code samples and detailed parameter explanations. Remember the 10-page limit of the free Spire.PDF edition.

In real-world projects, select the appropriate method according to your requirements. Pay attention to coordinate rules, transparency adjustment and resource release. This guide will help you quickly integrate reliable PDF watermark functionality into your C# applications.

Top comments (0)