0.前提条件:需要导入itextpdf-5.5.13.jar
1.写一个为PDF添加水印的工具类,代码如下:
package com.tancong.mark; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import com.itextpdf.text.BaseColor; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Rectangle; import com.itextpdf.text.pdf.BaseFont; import com.itextpdf.text.pdf.PdfContentByte; import com.itextpdf.text.pdf.PdfGState; import com.itextpdf.text.pdf.PdfReader; import com.itextpdf.text.pdf.PdfStamper; public class PDFWatermarkUtil { public static boolean addTextMark(String origination, String desination, String waterText, int x, int y, int fontSize) { FileInputStream fileInputStream = null; FileOutputStream fileOutputStream = null; try { fileInputStream = new FileInputStream(new File(origination)); fileOutputStream = new FileOutputStream(new File(desination)); return addTextMark(fileInputStream, fileOutputStream, waterText, x, y, fontSize); } catch (Exception e) { e.printStackTrace(); } finally { if (fileOutputStream != null) { try { fileOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } if (fileInputStream != null) { try { fileInputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } return false; } private static boolean addTextMark(InputStream originFile, FileOutputStream targetFile, String waterText, int x, int y, int fontSize) { PdfReader reader = null; PdfStamper stamper = null; try { reader = new PdfReader(originFile); stamper = new PdfStamper(reader, targetFile); if (waterText == null) waterText = "没有定义水印"; BaseFont font; if (waterText.getBytes().length == waterText.length()) { font = BaseFont.createFont(); } else { font = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", true); } int total = reader.getNumberOfPages(); PdfGState pg = new PdfGState(); for (int i = 1; i <= total; i++) { Rectangle rect = reader.getPageSizeWithRotation(i); double width = rect.getWidth(); double height = rect.getHeight(); System.out.println(width + " " + height); if (width > height) { width -= height; height = width + height; width = height - width; } PdfContentByte content = stamper.getOverContent(i); content.beginText(); content.setColorFill(BaseColor.LIGHT_GRAY); content.setFontAndSize(font, fontSize); int xPosition = x; int yPosition = y; if (x > Math.floor(width)) xPosition = (int) Math.floor(width) - 520; if (Math.floor(width) < 1200.0D) xPosition += 10; if (y > Math.floor(height)) y = (int) Math.floor(height) / 2; if (Math.floor(height) < 900.0D) yPosition -= 60; xPosition += 50; yPosition -= 100; System.out.println(xPosition + " " + yPosition); pg.setFillOpacity(0.4F); content.setGState(pg); content.showTextAligned(0, waterText, xPosition, yPosition, 30.0F); content.endText(); } return true; } catch (Exception e) { e.printStackTrace(); } finally { try { stamper.close(); } catch (DocumentException | IOException e) { e.printStackTrace(); } reader.close(); } return false; } }