How to add a watermark to PDF
model.PdfPage has two watermark methods, AddWatermarkText and
AddWatermarkImage. Both wrap the page’s existing content in q/Q and append
a form XObject after it, so the stamp lands on top and the original content is
never rewritten.
options := model.WatermarkTextOptions{
Alpha: 0.3,
FontSize: 40,
FontPath: "Roboto-Regular.ttf",
FontColor: color.RGBA{R: 255, G: 0, B: 0, A: 255},
Angle: 30,
}
if err := page.AddWatermarkText("CONFIDENTIAL", options); err != nil {
return err
}Neither method writes anything. Call pdfReader.ToWriter(nil) afterwards and
WriteToFile on the writer, or feed the pages to a creator with AddPage.
The text watermark is not text. UniPDF rasterizes it with FreeType and embeds
the result as an image, then calls AddWatermarkImage internally, so the
watermark is a bitmap: not selectable, not searchable, resolution-dependent.
FontPath has to be a .ttf on disk, not a PdfFont you already loaded.
The two option structs disagree about defaults, which catches people.
WatermarkTextOptions fills in a zero value: Alpha becomes 0.5, FontSize
becomes 20, a nil FontColor becomes black. WatermarkImageOptions does not,
so model.WatermarkImageOptions{} writes an opacity of 0 and produces an
invisible watermark with no error and no warning. Always set Alpha for image
watermarks.
Both calls center the stamp on the page. For real text, tiling, or placement
anywhere else, draw it with the creator instead.
See the watermark guides for the option tables and for removing a watermark that is already in a file.