水印位置、倾斜度、透明度、字体大小、颜色、条数可自行调整;
话不多说直接上代码!!!
File tempFile = new File("F:\\6665.pdf");
String waterMark = "测试水印";
float fontSize = 20;
int[] color = {200, 0, 0};
int rowSpace = 200;
int colSpace = 200;
try {
waterMarkUtil(tempFile, waterMark, fontSize, color, rowSpace, colSpace);
} catch (IOException e) {
System.out.println("水印渲染异常:" + e);
}
具体实现如下:
tempFile: 需要添加水印的文件
waterMark: 需要添加的水印文字
rowSpace、colSpace:倾斜度
color: 颜色,我这里使用的红色
fontSize: 文字大小
需要用到字体:使用默认字体不生效,最好是引入字体
private static void waterMarkUtil(File tempFile, String waterMark, float fontSize, int[] color, int rowSpace, int colSpace) throws IOException {
// 加载PDF文件
PDDocument document = PDDocument.load(tempFile);
document.setAllSecurityToBeRemoved(true);
// 遍历PDF文件,在每一页加上水印
for (PDPage page : document.getPages()) {
PDPageContentStream stream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true, true);
// 加载水印字体
PDFont font = PDType0Font.load(document, Files.newInputStream(Paths.get("C:\\Users\\Desktop\\仿宋_GB2312.ttf")), true);
PDExtendedGraphicsState r = new PDExtendedGraphicsState();
// 设置透明度
r.setNonStrokingAlphaConstant(0.1f);
r.setAlphaSourceFlag(true);
stream.setGraphicsStateParameters(r);
// 设置水印字体颜色
if (color.length == 3) {
stream.setNonStrokingColor(color[0], color[1], color[2]);
}
stream.beginText();
stream.setFont(font, fontSize);
stream.newLineAtOffset(0, -15);
// 获取PDF页面大小
float pageHeight = page.getMediaBox().getHeight();
float pageWidth = page.getMediaBox().getWidth();
// 根据纸张大小添加水印,30度倾斜
for (int h = 10; h < pageHeight; h = h + rowSpace) {
for (int w = -10; w < pageWidth; w = w + colSpace) {
stream.setTextMatrix(Matrix.getRotateInstance(0.3, w, h));
stream.showText(waterMark);
}
}
// 结束渲染,关闭流
stream.endText();
stream.restoreGraphicsState();
stream.close();
}
document.save(tempFile);
}
结果如下: