使用java代码实现给PDF加水印的功能
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.11</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
/**
* @param inputFile 你的PDF文件地址
* @param outputFile 添加水印后生成PDF存放的地址
* @param waterMarkName 你的水印
* @return
*/
public static boolean 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.NOT_EMBEDDED);// 使用系统字体
int total = reader.getNumberOfPages() + 1;
PdfContentByte under;
Rectangle pageRect = null;
for (int i = 1; i < total; i++) {
pageRect = stamper.getReader().
getPageSizeWithRotation(i);
// 计算水印X,Y坐标
float x = pageRect.getWidth()/10;
float y = pageRect.getHeight()/10-10;
// 获得PDF最顶层
under = stamper.getOverContent(i);
under.saveState();
// set Transparency
PdfGState gs = new PdfGState();
// 设置透明度为0.2
gs.setFillOpacity(1.f);
under.setGState(gs);
under.restoreState();
under.beginText();
under.setFontAndSize(base, 60);
under.setColorFill(BaseColor.ORANGE);
// 水印文字成45度角倾斜
under.showTextAligned(Element.ALIGN_CENTER
, waterMarkName, x,
y, 55);
// 添加水印文字
under.endText();
under.setLineWidth(1f);
under.stroke();
}
stamper.close();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}