public static void main(String[] args) {
//创建PdfDocument类的对象
PdfDocument pdf = new PdfDocument();
//加载测试文档
pdf.loadFromFile("test.pdf");
//获取文档第1页
PdfPageBase page = pdf.getPages().get(0);
//调用insertWatermark()方法插入文本水印
insertWatermark(page, "TOP SECRET");
//保存文档到指定文件夹
pdf.saveToFile("out/textWaterMark.pdf");
}
static void insertWatermark(PdfPageBase page, String watermark) {
Dimension2D dimension2D = new Dimension();
dimension2D.setSize(page.getCanvas().getClientSize().getWidth() / 2, page.getCanvas().getClientSize().getHeight() / 2);
PdfTilingBrush brush = new PdfTilingBrush(dimension2D);
brush.getGraphics().setTransparency(0.4F);
brush.getGraphics().save();
brush.getGraphics().translateTransform((float) brush.getSize().getWidth() / 2, (float) brush.getSize().getHeight() / 2);
brush.getGraphics().rotateTransform(-45);
brush.getGraphics().drawString(watermark, new PdfFont(PdfFontFamily.Helvetica, 30), PdfBrushes.getViolet(), 0, 0, new PdfStringFormat(PdfTextAlignment.Center));
brush.getGraphics().restore();
brush.getGraphics().setTransparency(1);
Rectangle2D loRect = new Rectangle2D.Float();
loRect.setFrame(new Point2D.Float(0, 0), page.getCanvas().getClientSize());
page.getCanvas().drawRectangle(brush, loRect);
}