PDF添加水印

最近项目当中有用到下载PDF需添加水印的功能,就试了一把。代码如下:

import java.awt.FontMetrics;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.swing.JLabel;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfGState;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfStamper;

/**
 * PDF添加水印
 * @author win 10
 *
 */
public class PDFAddWaterMark {
	private static int interval = -5;
	public static void main(String[] args) throws DocumentException, IOException {
		String sourcePath = "D:/无水印.pdf";
        String targetPath = "D:/添加水印后.pdf";
        InputStream in = new FileInputStream(sourcePath);
        OutputStream out = new FileOutputStream(targetPath);
        waterMark(in,out,"测试添加水印");
	}
	public static void waterMark(InputStream source,OutputStream target,String waterMarkName) throws DocumentException, IOException{
		 PdfReader reader = null;
         PdfStamper stamper = null;
		try {
			 reader = new PdfReader(source);
			 stamper = new PdfStamper(reader, target);
	         BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
	         Rectangle pageRect = null;
	         PdfGState gs = new PdfGState();
	         //设置水印透明度
	         gs.setFillOpacity(0.2f);
	         gs.setStrokeOpacity(0.2f);
	         int total = reader.getNumberOfPages() + 1;
	         JLabel label = new JLabel();
	         FontMetrics metrics;
	         int textH = 0;
	         int textW = 0;
	         label.setText(waterMarkName);
	         metrics = label.getFontMetrics(label.getFont());
	         textH = metrics.getHeight();
	         textW = metrics.stringWidth(label.getText());
	         PdfContentByte under;
	         for (int i = 1; i < total; i++) {
	              pageRect = reader.getPageSizeWithRotation(i);
	              under = stamper.getOverContent(i);
	              under.saveState();
	              under.setGState(gs);
	              under.beginText();
	              under.setFontAndSize(base, 40);
	              //设置水印平铺所有页,注释此循环部分则每页添加一个水印
	              for (int height = interval + textH; height < pageRect.getHeight();height = height + textH * 6) {
	                  for (int width = interval + textW; width < pageRect.getWidth() + textW; width = width + textW * 4) {
	                	  //设置水印的位置以及角度
	                      under.showTextAligned(Element.ALIGN_LEFT, waterMarkName, width - textW, height - textH, 30);
	                   }
	                }
	                // 添加水印文字
	                under.endText();
	            }
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			 stamper.close();
	         reader.close();
		}
	}
}

亲测可用!

你可能感兴趣的:(PDF添加水印)