Apply Watermark

This module uses the DevExpress PDF Document API to apply watermarks to PDF documents. You can process the sample file or supply your own document. To do the latter, select Upload a File from the file selection drop-down menu.

Specify the watermark text and enable text rotation. Click Add Watermark to update the document and download the result.

Sample document
Sample_Main.pdf



using DevExpress.Drawing;
using DevExpress.Pdf;

Stream ApplyWatermark(Stream documentStream, string text, bool rotate) {
    using var processor = new PdfDocumentProcessor();

    processor.LoadDocument(documentStream);

    using var brush = new DXSolidBrush(System.Drawing.Color.FromArgb(50, System.Drawing.Color.LightSkyBlue));

    var fontName = "Arial Black";
    var fontSize = 12;
    var font = new DXFont(fontName, fontSize);

    var stringFormat = PdfStringFormat.GenericTypographic;
    stringFormat.Alignment = PdfStringAlignment.Center;
    stringFormat.LineAlignment = PdfStringAlignment.Center;

    foreach(var page in processor.Document.Pages) {
        using var graphics = processor.CreateGraphicsPageSystem();

        var watermarkSize = page.CropBox.Width * 0.75;

        var stringSize = graphics.MeasureString(text, font);
        float scale = (float)(watermarkSize / (double)stringSize.Width);

        graphics.TranslateTransform((float)(page.CropBox.Width * 0.5), (float)(page.CropBox.Height * 0.5));
        if(rotate)
            graphics.RotateTransform(-45f);
        graphics.TranslateTransform(
            (float)(-stringSize.Width * scale * 0.5),
            (float)(-stringSize.Height * scale * 0.5));

        var actualFont = new DXFont(fontName, fontSize * scale);
        var rect = new System.Drawing.RectangleF(0, 0, stringSize.Width * scale, stringSize.Height * scale);
        graphics.DrawString(text, actualFont, brush, rect, stringFormat);

        graphics.AddToPageForeground(page);
    }

    var outputStream = new MemoryStream();
    processor.SaveDocument(outputStream);

    return outputStream;
}