package com.test;
import org.apache.pdfbox.pdmodel.*;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDType0Font;
import org.apache.pdfbox.pdmodel.graphics.state.PDExtendedGraphicsState;
import org.apache.pdfbox.util.Matrix;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class TestWaterMark3 {
public static void main(String[] args) {
File tempFile = new File("C://Users//Admin//Desktop//凭证 - 副本.pdf");
String waterMark = "我是测试水印";
float fontSize = 13;
int[] color = {0, 200, 0};
int rowSpace = 150;
int colSpace = 150;
try {
waterMarkUtil(tempFile, waterMark, fontSize, color, rowSpace, colSpace);
} catch (IOException e) {
System.out.println("水印渲染异常:" + e);
}
}
/**
* 给文件添加水印
*
* @param tempFile 需要添加水印的文件
* @param waterMark 水印文字
* @param fontSize 字体大小
* @param color 字体颜色:{r, g, b}
* @param rowSpace 行间距,大中小分别对应150/100/50
* @param colSpace 列间距,大中小分别对应150/100/50
* @throws IOException 异常
*/
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, new FileInputStream("C://Users//Admin//Desktop//锐字工房云字库大黑GBK.ttf"), true);
PDExtendedGraphicsState r = new PDExtendedGraphicsState();
// 设置透明度
r.setNonStrokingAlphaConstant(0.2f);
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);
}
}
利用PDFBOX给PDF文件添加水印
最新推荐文章于 2024-09-05 15:25:36 发布