一、Maven引入PDF支持

<dependency>
   <groupId>org.apache.pdfbox</groupId>
   <artifactId>pdfbox</artifactId>
   <version>2.0.24</version>
</dependency>

二、核心加水印代码
private static void watermark(File file,OutputStream ops) throws Exception {
//创建新pdf文件
//File tmpPDF = new File("D:\tmp\testwatermark.pdf");
//打开pdf文件
PDDocument doc = PDDocument.load(file);
doc.setAllSecurityToBeRemoved(true);
//遍历pdf所有页
for (PDPage page : doc.getPages()) {
PDPageContentStream cs = new PDPageContentStream(doc, page, PDPageContentStream.AppendMode.APPEND, true, true);
String ts = "仅供内部使用-仅供内部使用";
//引入字体文件 解决中文汉字乱码问题
PDFont font = PDType0Font.load(doc, new FileInputStream("D:\tmp\simkai.ttf"), true);
float fontSize = 18;
PDResources resources = page.getResources();
PDExtendedGraphicsState r0 = new PDExtendedGraphicsState();
// 水印透明度
r0.setNonStrokingAlphaConstant(0.1f);
r0.setAlphaSourceFlag(true);
cs.setGraphicsStateParameters(r0);
//水印颜色
// cs.setNonStrokingColor(200, 0, 0,0.2f);
cs.setNonStrokingColor(Color.BLACK);
cs.beginText();
cs.setFont(font, fontSize);
//根据水印文字大小长度计算横向坐标需要渲染几次水印
float h = ts.length() fontSize;
System.out.println(h);
for (int i = 0; i <= 10; i++) {
// 获取旋转实例
cs.setTextMatrix(Matrix.getRotateInstance(-150, i
100, 0));
cs.showText(ts);
for (int j = 0; j < 20; j++) {
cs.setTextMatrix(Matrix.getRotateInstance(-150, i 100, j h));
cs.showText(ts);
}
}
cs.endText();
cs.restoreGraphicsState();
cs.close();
}
//保存到文件
//doc.save(tmpPDF);
//保存到输出流
doc.save(ops);
}

三、代码使用
public static void main(String[] args) throws Exception {
File f= new File("D:\tmp\test.pdf");
File tmpPDF = new File("D:\tmp\testwatermark.pdf");
OutputStream ops= new FileOutputStream(tmpPDF);
watermark(f,ops);
}

最后修改:2021 年 12 月 07 日
如果觉得我的文章对你有用,请随意赞赏