使用Java代码给PDF文件加水印

iTextPdf

使用 itextpdfPDF 文件加水印, https://github.com/itext/itextpdf

Maven

1
2
3
4
5
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13</version>
</dependency>

Gradle

1
compile group: 'com.itextpdf', name: 'itextpdf', version: '5.5.13'

Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;

import java.io.FileOutputStream;
import java.io.IOException;

/**
* @author hdvsyu
*/
public class PdfStampService {

String stampPdf(String fileName, String newFileName) {
try {
PdfReader pdfReader = new PdfReader(fileName);
try {
PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileOutputStream(newFileName));
int totalPage = pdfReader.getNumberOfPages();
for (int i = 1; i <= totalPage; i++) {
PdfContentByte pdfContentByte = pdfStamper.getOverContent(i);
pdfContentByte.beginText();
pdfContentByte.setColorFill(BaseColor.BLACK);
pdfContentByte.setFontAndSize(BaseFont.createFont(), 9);
pdfContentByte.setTextMatrix(66, 20);
pdfContentByte.showText("some text");
pdfContentByte.endText();
}
pdfStamper.close();
} catch (DocumentException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}

return newFileName;
}
}

pdfContentByte.setTextMatrix(x, y); 坐标是以左下角为原点的坐标系中的坐标