在实际运用中,我们往往不想将原pdf文件给用户,而是想给有水印的pdf文件给用户,这样既保护了自己文章的写作权还可以加以宣传。那么,在PDF文件上添加水印,使用Java该如何实现呢?
实现过程
1、添加itextpdf依赖
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.9</version>
</dependency>
2、实现
inputFile:要加水印的源文件的路径(例如:D:\test.pdf)
outputFile:加水印后文件的输出路径
waterMarkName:要加的水印名
public void waterMark(String inputFile,String outputFile, String waterMarkName) {
try {
PdfReader reader = new PdfReader(inputFile);
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(outputFile));
BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
PdfGState gs = new PdfGState();
//改透明度
gs.setFillOpacity(0.5f);
gs.setStrokeOpacity(0.4f);
int total = reader.getNumberOfPages() + 1;
JLabel label = new JLabel();
label.setText(waterMarkName);
PdfContentByte under;
// 添加一个水印
for (int i = 1; i < total; i++) {
// 在内容上方加水印
under = stamper.getOverContent(i);
//在内容下方加水印
//under = stamper.getUnderContent(i);
gs.setFillOpacity(0.5f);
under.setGState(gs);
under.beginText();
//改变颜色
under.setColorFill(BaseColor.LIGHT_GRAY);
//改水印文字大小
under.setFontAndSize(base, 150);
under.setTextMatrix(70, 200);
//后3个参数,x坐标,y坐标,角度
under.showTextAligned(Element.ALIGN_CENTER, waterMarkName, 300, 350, 55);
under.endText();
}
stamper.close();
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}