给pdf文件添加水印
- 引入依赖
<dependency><groupId>com.itextpdf</groupId><artifactId>itextpdf</artifactId><version>5.5.13.3</version></dependency>
- 添加水印
package com.it2.pdfdemo02.util;import com.itextpdf.text.Element;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.*;import java.io.FileOutputStream;/*** @Description: PDF增加水印工具类*/
public class PDFUtil {/*** 给PDF添加水印* @param inputFilePath 源文件* @param outputFilePath 生成的文件* @param waterMarkContent 添加水印的内容*/public static void pdfAddWaterMark(String inputFilePath, String outputFilePath, String waterMarkContent) {try {// 水印的高和宽int waterMarkHeight = 30;int watermarkWeight = 60;// 水印间隔距离int waterMarkInterval = 200;// 读取PDF文件流PdfReader pdfReader = new PdfReader(inputFilePath);// 创建PDF文件的模板,可以对模板的内容修改,重新生成新PDF文件PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileOutputStream(outputFilePath));// 设置水印字体BaseFont baseFont = BaseFont.createFont("Font/SIMYOU.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); //幼圆常规// 设置PDF内容的Graphic State 图形状态PdfGState pdfGraPhicState = new PdfGState();// 填充透明度pdfGraPhicState.setFillOpacity(0.2f);// 轮廓不透明度pdfGraPhicState.setStrokeOpacity(0.4f);// PDF页数int pdfPageNum = pdfReader.getNumberOfPages() + 1;// PDF文件内容字节PdfContentByte pdfContent;// PDF页面矩形区域Rectangle pageRectangle;for (int i = 1; i < pdfPageNum; i++) {// 获取当前页面矩形区域pageRectangle = pdfReader.getPageSizeWithRotation(i);// 获取当前页内容,getOverContent表示之后会在页面内容的上方加水印pdfContent = pdfStamper.getOverContent(i);// 获取当前页内容,getOverContent表示之后会在页面内容的下方加水印
// pdfContent = pdfStamper.getUnderContent(i);pdfContent.saveState();// 设置水印透明度pdfContent.setGState(pdfGraPhicState);// 开启写入文本pdfContent.beginText();// 设置字体pdfContent.setFontAndSize(baseFont, 20);// 在高度和宽度维度每隔waterMarkInterval距离添加一个水印for (int height = waterMarkHeight; height < pageRectangle.getHeight(); height = height + waterMarkInterval) {for (int width = watermarkWeight; width < pageRectangle.getWidth() + watermarkWeight;width = width + waterMarkInterval) {// 添加水印文字并旋转30度角pdfContent.showTextAligned(Element.ALIGN_LEFT, waterMarkContent, width - watermarkWeight,height - waterMarkHeight, 30);}}// 停止写入文本pdfContent.endText();}pdfStamper.close();pdfReader.close();} catch (Exception e) {e.printStackTrace();}}
}
- 添加字体文件到resoures\Font\simsun.ttc
用到的字体文件(幼圆常规,C盘Windows/Fonts目录下
- 测试用例
@Testvoid addWater() {PDFUtil.pdfAddWaterMark("D:\\test3\\test1.pdf", "D:\\test3\\test1_watermark.pdf", "内部资料,禁止外传");}