Let's take a look at the effect first:
First copy the dependencies
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.5</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13</version>
</dependency>
Next go directly to the code
1. This is download
public void addWaterMark(String pdfFilePath) {
// String pdfFilePath="D:\\data\\file\\164\\国家磁约束核聚变能发展研究专项 2019 年度项目申报指南.pdf";
try {
// 原PDF文件
PdfReader reader = new PdfReader(pdfFilePath);
// 输出的PDF文件内容
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(outputFilePath));
// 字体 来源于 itext-asian JAR包
BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", true);
PdfGState gs = new PdfGState();
// 设置透明度
gs.setFillOpacity(0.2f);
gs.setStrokeOpacity(0.2f);
int totalPage = reader.getNumberOfPages() + 1;
for (int i = 1; i < totalPage; i++) {
// 内容上层
PdfContentByte content = stamper.getOverContent(i);
// 内容下层
// PdfContentByte content = stamper.getUnderContent(i);
content.beginText();
// 字体添加透明度
content.setGState(gs);
// 添加字体大小等
content.setFontAndSize(baseFont, 50);
// 添加范围
content.setTextMatrix(70, 200);
// 具体位置 内容 旋转多少度 共360度
content.showTextAligned(Element.ALIGN_CENTER, "姓名和单位", 300, 350, 40);
content.endText();
}
// 关闭
stamper.close();
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
2. This is a preview
public void addWaterMark(HttpServletResponse response,String pdfFilePath) {
// String pdfFilePath="D:\\data\\file\\164\\国家磁约束核聚变能发展研究专项 2019 年度项目申报指南.pdf";
try {
// 原PDF文件
PdfReader reader = new PdfReader(pdfFilePath);
// 输出的PDF文件内容
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "inline; filename=myFile.pdf");
OutputStream out = response.getOutputStream();
PdfStamper stamper = new PdfStamper(reader,out);
// PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(outputFilePath));
// 字体 来源于 itext-asian JAR包
BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", true);
PdfGState gs = new PdfGState();
// 设置透明度
gs.setFillOpacity(0.2f);
gs.setStrokeOpacity(0.2f);
int totalPage = reader.getNumberOfPages() + 1;
for (int i = 1; i < totalPage; i++) {
// 内容上层
PdfContentByte content = stamper.getOverContent(i);
// 内容下层
// PdfContentByte content = stamper.getUnderContent(i);
content.beginText();
// 字体添加透明度
content.setGState(gs);
// 添加字体大小等
content.setFontAndSize(baseFont, 50);
// 添加范围
content.setTextMatrix(70, 200);
// 具体位置 内容 旋转多少度 共360度
content.showTextAligned(Element.ALIGN_CENTER, "姓名和单位", 300, 350, 40);
// content.showTextAligned(Element.ALIGN_TOP, "机密文件2", 100, 100, 5);
// content.showTextAligned(Element.ALIGN_BOTTOM, "机密文件3", 400, 400, 75);
content.endText();
}
// 关闭
stamper.close();
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}