Add a watermark to a PDF in C#
Write a large, rotated, semi transparent word across every page.
Short answer
Section titled “Short answer”Draw on each page with CreateGraphics, rotate the canvas about the page center with
RotateAtTransform, and draw the text with a color that has an alpha below 1. Positive angles turn
clockwise, so -45 runs the text up from bottom left to top right.
#:package PdfNetStack@1.2.0using PdfNetStack;using PdfNetStack.Drawing;using PdfNetStack.Fonts;
PdfDocument doc = PdfDocument.Open("contract.pdf");PdfFont font = PdfStandardFont.HelveticaBold;double size = 110;double width = font.MeasureString("DRAFT", size);foreach (PdfPage page in doc.Pages){ using PdfGraphics g = page.CreateGraphics(); g.RotateAtTransform(-45, page.Width / 2, page.Height / 2); // positive angles turn clockwise g.DrawString("DRAFT", font, size, PdfColor.FromHex("#DC2626").WithAlpha(0.25), (page.Width - width) / 2, page.Height / 2 + size * 0.35);}doc.Save("contract-draft.pdf");
Variations
Section titled “Variations”page.CreateGraphics(PdfGraphicsLayer.Background)draws underneath the existing content, so the text of the page stays on top of the watermark.- For an image or a logo, use
DrawImageorDrawSvgthe same way. To stamp another PDF page, such as a letterhead, usePdfForm.FromPageandDrawForm, see Images.
Related
Section titled “Related”- Drawing
- Images
- API: PdfGraphics, PdfColor