package com.zving.demo; import java.awt.Color; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import com.lowagie.text.Element; import com.lowagie.text.pdf.BaseFont; import com.lowagie.text.pdf.PdfContentByte; import com.lowagie.text.pdf.PdfGState;
import com.lowagie.text.Rectangle; import com.lowagie.text.pdf.PdfReader; import com.lowagie.text.pdf.PdfStamper; public class PdfWaterPrint { public static void main(String[] args) { try { // 目标pdf文件 BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File("E:/BBB.pdf"))); // 源pdf文件 setWatermark(bos, "E:/AAA.pdf",16); } catch (Exception e) { e.printStackTrace(); } } public static void setWatermark(BufferedOutputStream bos, String input, int permission){ try { PdfReader reader = new PdfReader(input); PdfStamper stamper = new PdfStamper(reader, bos); int total = reader.getNumberOfPages() + 1; PdfContentByte content; BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",BaseFont.EMBEDDED); PdfGState gs = new PdfGState();
Rectangle pageRect = null;for (int i = 1; i < total; i++) { // 设置透明度
gs.setFillOpacity(0.6f);
gs.setStrokeOpacity(0.6f);
pageRect = stamper.getReader().getPageSizeWithRotation(i);
// 计算水印X,Y坐标
float x = pageRect.getWidth() / 2;
float y = pageRect.getHeight() / 2;
//获得PDF最顶层
content = stamper.getOverContent(i);
content.saveState();
content.setGState(gs);
content.beginText();
content.setColorFill(new java.awt.Color(130, 130, 130));
content.setFontAndSize(base, pageRect.getWidth() / 10);
// 水印文字成45度角倾斜
content.showTextAligned(Element.ALIGN_CENTER , "新闻记者证核发办公室", x, y, 45);
content.endText(); } stamper.close(); } catch (Exception e) { e.printStackTrace(); } } }
所需要得jar包