I am trying to add a watermark to a PDF specifically with PDFBox. I\'ve been able to get the image to appear on each page, but it loses the background transparency because i
This is how I was able to add a text watermark with the date using PdfBox 2.0.x in C#. It centres the watermark at the top of the page.
public static void AddWatermark(string fileName)
{
StringBuilder sb = new StringBuilder();
sb.Append("watermark_text ");
sb.Append(DateTime.Now.ToString());
string waterMarkText = sb.ToString();
PDDocument origDoc = PDDocument.load(new java.io.File(fileName));
PDPageTree allPages = origDoc.getPages();
PDFont font = PDType1Font.HELVETICA_BOLD;
for (int i = 0, len = allPages.getCount(); i < len; ++i)
{
PDPage pg = (PDPage)allPages.get(i);
AddWatermarkText(origDoc, pg, font, waterMarkText);
}
origDoc.save(fileName);
origDoc.close();
}
static void AddWatermarkText(PDDocument doc, PDPage page, PDFont font, string text)
{
using (PDPageContentStream cs = new PDPageContentStream(doc, page, PDPageContentStream.AppendMode.APPEND, true, true))
{
float fontHeight = 30;
float width = page.getMediaBox().getWidth();
float height = page.getMediaBox().getHeight();
float stringWidth = font.getStringWidth(text) / 1000 * fontHeight;
float x = (width / 2) - (stringWidth / 2);
float y = height - 25;
cs.setFont(font, fontHeight);
PDExtendedGraphicsState gs = new PDExtendedGraphicsState();
gs.setNonStrokingAlphaConstant(new java.lang.Float(0.2f));
gs.setStrokingAlphaConstant(new java.lang.Float(0.2f));
gs.setBlendMode(BlendMode.MULTIPLY);
gs.setLineWidth(new java.lang.Float(3f));
cs.setGraphicsStateParameters(gs);
cs.setNonStrokingColor(Color.red);
cs.setStrokingColor(Color.red);
cs.beginText();
cs.newLineAtOffset(x, y);
cs.showText(text);
cs.endText();
}
}
pdfbox c# watermark pdf