看了一些文章,大多都是一个一个的斜排水印,一般加水印都是想要加全屏的
首先映入依赖:
<!-- PDF文件依赖包 -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13.1</version>
</dependency>
<!-- PDF文件字体 防止中文乱码 -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
代码:
/**
* pdf生成水印(全屏)
* @param srcPdfPath 插入前的文件路径
* @param tarPdfPath 插入后的文件路径
* @param waterMarkContent 水印文案
* @throws Exception
*/
public static void addWaterMarkFullScreen(String srcPdfPath, String tarPdfPath, String waterMarkContent) throws Exception {
PdfReader reader = new PdfReader(srcPdfPath);
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(tarPdfPath));
PdfGState gs = new PdfGState();
// 设置字体
BaseFont font = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
// 设置透明度
gs.setFillOpacity(0.2f);
int total = reader.getNumberOfPages() + 1;
PdfContentByte content;
for (int i = 1; i < total; i++) {
content = stamper.getOverContent(i);
content.beginText();
content.setGState(gs);
// 水印颜色
content.setColorFill(BaseColor.BLUE);
// 水印字体样式和大小
content.setFontAndSize(font, 20);
// 获取页面尺寸
Rectangle pageSize = reader.getPageSize(i);
float pageWidth = pageSize.getWidth();
float pageHeight = pageSize.getHeight();
// 计算水印位置,覆盖整个页面
float x = 0;
float y = 0;
float rotation = 30; // 水印旋转角度
// 循环插入水印
while (x < pageWidth && y < pageHeight) {
content.showTextAligned(Element.ALIGN_CENTER, waterMarkContent, x, y, rotation);
// 水平平移
x += 200;
// 垂直平移
if (x >= pageWidth) {
x = 0;
y += 200;
}
}
content.endText();
}
stamper.close();
System.out.println("PDF水印添加完成!");
}
public static void main(String[] args) throws Exception {
addWaterMarkFullScreen(
"F:\\ybbe\\文档\\output.pdf",
"F:\\ybbe\\文档\\output2.pdf",
"作者qq:209740....@qq.com");
}