方式1:
/**
* 添加背景图片水印,平铺rows行cols列。水印图片覆盖在最顶层,可以设置透明度,会覆盖pdf全部内容,包括图片。适用于要求水印覆盖全部内容的情况。
*
* @param srcPdfPath 原PDF路径
* @param targetPdfPath 新PDF路径
* @param imagePath 水印图片路径
* @param rows 水印行数
* @param cols 水印列数
* @param angle 水印图片旋转角度-180-180
* @param transparency 水印图片透明度0-1
* @param offx 水印图片横向偏移量
* @param offy 水印图片纵向偏移量
*/
public static void addImageWatermarkTiles(String srcPdfPath, String targetPdfPath, String imagePath, int rows,
int cols, float angle, float transparency, double offx, double offy) {
// 创建PdfDocument对象,并加载PDF测试文档
if (rows < 1) {
rows = 1;
}
if (cols < 1) {
cols = 1;
}
PdfDocument pdf = new PdfDocument();
try {
pdf.loadFromFile(srcPdfPath);
PdfImage image = PdfImage.fromFile(imagePath);
// 图片宽高
int imageWidth = image.getWidth();
int imageHeight = image.getHeight();
// 平铺刷宽高
double brushWidth, brushHeight;
// 遍历文档每一页,加载图片,并设置成平铺背景(水印)
for (int i = 0; i < pdf.getPages().getCount(); i++) {
PdfPageBase page = pdf.getPages().get(i);
// 一个图片的大小,刷子大小
Dimension2D dimension2D = new Dimension();
dimension2D.setSize(page.getCanvas().getSize().getWidth() / cols, page.getCanvas().getSize().getHeight() / rows);
// 平铺刷
PdfTilingBrush brush = new PdfTilingBrush(dimension2D);
brushWidth = brush.getSize().getWidth();
brushHeight = brush.getSize().getHeight();
// 设置透明度
brush.getGraphics().setTransparency(transparency);
// 偏移量?
brush.getGraphics().translateTransform(offx, offy);
// 旋转角度
brush.getGraphics().rotateTransform(angle);
// 绘图片到刷子正中
brush.getGraphics().drawImage(image, (brushWidth - imageWidth) / 2, (brushHeight - imageHeight) / 2, imageWidth, imageHeight);
// 整个页面区域
Rectangle2D rectangle2D = new Rectangle2D.Float();
rectangle2D.setFrame(new Point(0, 0), page.getCanvas().getClientSize());
// 将平铺刷画满整个页面
page.getCanvas().drawRectangle(brush, rectangle2D);
}
// 保存文档
pdf.saveToFile(targetPdfPath);
pdf.dispose();
} catch (Exception e) {
e.printStackTrace();
} finally {
pdf.close();
}
}
方式2:
/**
* 通过设置背景图片的方式添加图片水印,居中显示,不平铺,只添加一张图片。
需要平铺的需要先做一张大图片。这种方式会让pdf中的图片显示在上方,不被遮挡。
有的客户有这种要求。
*
* @param sourceFile
* @param targetFile
* @param watermarkImagePath
*/
public static void addBackgroundImage(String sourceFilePath, String targetFilePath, String watermarkImagePath) {
PdfImage image = PdfImage.fromFile(watermarkImagePath);
double imageWidth = image.getWidth();
double imageHeight = image.getHeight();
PdfDocument pdf = new PdfDocument();
pdf.loadFromFile(sourceFilePath);
int pageCount = pdf.getPages().getCount();
double x=0;
double y=0;
for (int i = 0; i < pageCount; i++) {
PdfPageBase page = pdf.getPages().get(i);
// 设置背景图片
page.setBackgroundImage(watermarkImagePath);
// 设置背景区域
Rectangle2D rect = new Rectangle2D.Float();
x = (page.getSize().getWidth() - imageWidth) / 2;
y = (page.getSize().getHeight() - imageHeight) / 2;
rect.setRect(x, y, imageWidth, imageHeight);
page.setBackgroundRegion(rect);
}
// 保存文档
pdf.saveToFile(targetFilePath);
}