1.首先在pom文件添加依赖
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13</version>
</dependency>
2.创建PdfUtil工具类,复制粘贴如下代码:
/**
*
* 【功能描述:添加文字水印】
* @param srcFile 待加水印文件地址
* @param response 响应
* @param logoText 加水印的文本内容
* @throws Exception
*/
public static void addWaterMark(String srcFile, HttpServletResponse response, String logoText, String fontUrl)
throws Exception {
// 待加水印的文件
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);
// 设置水印透明度
PdfGState gs = new PdfGState();
// 设置填充字体不透明度为0.4f
gs.setFillOpacity(0.4f);
// 循环对每页插入水印
for (int i = 1; i < pageNumber; i++) {
// 水印在之前文本下
content = pdfStamper.getUnderContent(i);
// 开始
content.beginText();
// 设置水印字体参数及大小 (字体参数,字体编码格式,是否将字体信息嵌入到pdf中(一般不需要嵌入),字体大小)
content.setFontAndSize(font, 60);
// 设置透明度
content.setGState(gs);
// 设置水印对齐方式 水印内容 X坐标 Y坐标 旋转角度
content.showTextAligned(Element.ALIGN_RIGHT, logoText, 500, 430, 45);
// 设置水印颜色(灰色)
content.setColorFill(BaseColor.GRAY);
//结束
content.endText();
}
pdfStamper.close();
}
3.从控制台->字体中找到简体隶书并将其放在fontUrl,或从网上下载ttf、otf字体文件,请注意字体版权问题