public static void main(String[] args) {
watermark(new File("D:/测试.pdf"),"测试专用文件");
}
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.12</version>
</dependency>
public static String watermark(File file,String ts) {
File tmpPDF = new File("D:/"+file.getName());
PDDocument doc = null;
try {
doc = PDDocument.load(file);
} catch (IOException e) {
e.printStackTrace();
}
doc.setAllSecurityToBeRemoved(true);
for (PDPage page : doc.getPages()) {
PDPageContentStream cs = null;
try {
cs = new PDPageContentStream(doc, page, PDPageContentStream.AppendMode.APPEND, true, true);
} catch (IOException e) {
e.printStackTrace();
}
PDFont font = null;
try {
font = PDType0Font.load(doc, new FileInputStream("C:/WINDOWS/Fonts/SIMYOU.TTF"), true);
} catch (IOException e) {
e.printStackTrace();
}
float fontSize = 28;
PDResources resources = page.getResources();
PDExtendedGraphicsState r0 = new PDExtendedGraphicsState();
r0.setNonStrokingAlphaConstant(0.05f);
r0.setAlphaSourceFlag(true);
try {
cs.setGraphicsStateParameters(r0);
cs.setNonStrokingColor(0, 0, 0);
cs.beginText();
cs.setFont(font, fontSize);
} catch (IOException e) {
e.printStackTrace();
}
float h = ts.length() * fontSize;
for (int i = 0; i <= 10; i++) {
try {
cs.setTextMatrix(Matrix.getRotateInstance(-150, i * 100, 0));
cs.showText(ts);
} catch (IOException e) {
e.printStackTrace();
}
for (int j = 0; j < 20; j++) {
try {
cs.setTextMatrix(Matrix.getRotateInstance(-150, i * 100, j * h));
cs.showText(ts);
} catch (IOException e) {
e.printStackTrace();
}
}
}
try {
cs.endText();
cs.restoreGraphicsState();
cs.close();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
doc.save(tmpPDF);
doc.close();
} catch (IOException e) {
e.printStackTrace();
}
return names;
}