maven依赖:
<dependency><groupId>com.itextpdf</groupId><artifactId>itextpdf</artifactId><version>5.4.3</version> </dependency>
网络地址添加水印代码:
java"> public static boolean waterMarkNet(String inputFile, String outputFile, String waterMarkName) {try{URL url = new URL(inputFile);PdfReader reader = new PdfReader(url);PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(outputFile));BaseFont base = BaseFont.createFont();int total = reader.getNumberOfPages() + 1;PdfContentByte under;Rectangle pageRect = null;PdfGState gs = new PdfGState();gs.setFillOpacity(0.2f);gs.setStrokeOpacity(0.1f);for (int i = 1; i < total; i++){pageRect = stamper.getReader().getPageSizeWithRotation(i);under = stamper.getOverContent(i);under.saveState();under.setGState(gs);under.beginText();under.setFontAndSize(base, 50);under.setTextMatrix(30, 30);under.showTextAligned(Element.ALIGN_CENTER, waterMarkName, 300, 100, 20);under.showTextAligned(Element.ALIGN_CENTER, waterMarkName, 300, 300, 20);under.showTextAligned(Element.ALIGN_CENTER, waterMarkName, 300, 500, 20);under.showTextAligned(Element.ALIGN_CENTER, waterMarkName, 300, 700, 20);under.endText();under.setLineWidth(10f);under.stroke();}stamper.close();return true;} catch (Exception e){e.printStackTrace();return false;
本地地址添加水印代码
java">public static boolean waterMark(String inputFile, String outputFile, String waterMarkName) {try{PdfReader reader = new PdfReader(inputFile);PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(outputFile));BaseFont base = BaseFont.createFont();int total = reader.getNumberOfPages() + 1;PdfContentByte under;Rectangle pageRect = null;PdfGState gs = new PdfGState();gs.setFillOpacity(0.2f);gs.setStrokeOpacity(0.1f);for (int i = 1; i < total; i++){pageRect = stamper.getReader().getPageSizeWithRotation(i);under = stamper.getOverContent(i);under.saveState();under.setGState(gs);under.beginText();under.setFontAndSize(base, 50);under.setTextMatrix(30, 30);under.showTextAligned(Element.ALIGN_CENTER, waterMarkName, 300, 100, 20);under.showTextAligned(Element.ALIGN_CENTER, waterMarkName, 300, 300, 20);under.showTextAligned(Element.ALIGN_CENTER, waterMarkName, 300, 500, 20);under.showTextAligned(Element.ALIGN_CENTER, waterMarkName, 300, 700, 20);under.endText();under.setLineWidth(10f);under.stroke();}stamper.close();return true;} catch (Exception e){e.printStackTrace();return false;}}
测试代码
java"> public static void main(String[] args) {System.out.println(TestwaterMark.waterMark("https://XXXXXX/%E6%AD%A3%E6%96%87.pdf", "D:\\XXX\\XXX.pdf", "zymz"+DateUtils.dateTimeNow()));}