maven导入itextpdf依赖
<!-- pdf添加水印 -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.9</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
public class WaterPrintUtil {
/**
* @param srcFile pdf文件位置
* @param response 返回的响应流
* @param logoText 水印内容
* @param fileName 返回文件的名字
* @throws DocumentException
* @throws IOException
*/
public static void addWaterMark(String srcFile, HttpServletResponse response, String logoText, String fileName)
throws DocumentException, IOException {
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
response.setContentType("application/pdf;charset=UTF-8");
// 待加水印的文件
PdfReader reader = new PdfReader(srcFile);
// 加完水印的文件
PdfStamper pdfStamper = new PdfStamper(reader, response.getOutputStream());
int pageNumber = reader.getNumberOfPages() + 1;
PdfContentByte content;
// 检查字体文件存不存在
// if (!new File(fontUrl).exists()) {
// throw new RuntimeException(fontUrl + " 字体文件不存在");
// }
// 创建字体
// BaseFont font = BaseFont.createFont(fontUrl, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
// 使用默认字体
BaseFont font = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
// 设置水印透明度
PdfGState gs = new PdfGState();
// 设置填充字体不透明度为0.3f
gs.setFillOpacity(0.3f);
// 循环对每页插入水印
for (int i = 1; i < pageNumber; i++) {
// 水印在之前文本下
content = pdfStamper.getUnderContent(i);
// 开始
content.beginText();
// 设置水印颜色(红色)
content.setColorFill(BaseColor.RED);
// 设置水印字体参数及大小 (字体参数,字体编码格式,是否将字体信息嵌入到pdf中(一般不需要嵌入),字体大小)
content.setFontAndSize(font, 30);
// 设置透明度
content.setGState(gs);
// 设置水印对齐方式 水印内容 X坐标 Y坐标 旋转角度
content.showTextAligned(Element.ALIGN_RIGHT, logoText, 300, 0, 40);
// 结束
content.endText();
}
pdfStamper.close();
}
}