public static void main(String[] args) throws Exception { PdfReader reader = new PdfReader(new FileInputStream(new File("E:/e1c84094314443dbba6c3f77ea907030.pdf")));//存在的文件 PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(new File("E:/pdfWithWaterMark.pdf")));//输出文件 int total = reader.getNumberOfPages() + 1;//pdf总页数 PdfContentByte content; BaseFont base = BaseFont.createFont("C:/WINDOWS/Fonts/SIMSUN.TTC,1",BaseFont.IDENTITY_H, BaseFont.EMBEDDED); PdfGState gs = new PdfGState();
int a=0,b=0,c=35; //a距左,b距下,c倾斜度 for (int i = 1; i < total; i++) { content = stamper.getOverContent(i);// 在内容上方加水印 // content = stamper.getUnderContent(i);//在内容下方加水印 gs.setFillOpacity(0.4f); content.setGState(gs);// 透明度 content.beginText(); content.setColorFill(Color.LIGHT_GRAY); content.setFontAndSize(base, 30); content.setTextMatrix(70, 200); content.showTextAligned(Element.ALIGN_CENTER, "测试水印", a, b, c); content.setColorFill(Color.BLACK); content.setFontAndSize(base, 8); content.endText(); } stamper.close(); }
不过这个方法一页只能放一个水印 不过可以通过循环
content.showTextAligned(Element.ALIGN_CENTER, "测试水印", a, b, c);
该行一页添加多个水印 还在寻找其他更好的方法
itext包:
<dependency> <groupId>com.itextpdf</groupId> <artifactId>itextpdf</artifactId> <version>5.4.5</version> </dependency>