JAVA 使用itextpdf给pdf加水印

package test;

import java.io.FileOutputStream;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Element;
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 pdfUtils {
	 /**
     * @param inputFile 你的PDF文件地址
     * @param outputFile 添加水印后生成PDF存放的地址
     * @param waterMarkName 你的水印
     * @return
     */
      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("STSong-Light",
                    "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);// 使用系统字体
            int total = reader.getNumberOfPages() + 1;

            PdfContentByte under;
            Rectangle pageRect = null;
            for (int i = 1; i < total; i++) {
                pageRect = stamper.getReader().
                        getPageSizeWithRotation(i);
                // 计算水印X,Y坐标
//                float x = pageRect.getWidth()/10;
//                float y = pageRect.getHeight()/10-10;
                // 获得PDF最顶层
                under = stamper.getOverContent(i);
                under.saveState();
                // set Transparency
                PdfGState gs = new PdfGState();
                // 设置透明度为0.2
                gs.setFillOpacity(0.8f);
                under.setGState(gs);
                under.restoreState();
                under.beginText();
                under.setFontAndSize(base, 25);
                under.setTextMatrix(30, 30);
                under.setColorFill(BaseColor.RED);
            	for (int y = 0; y < 10; y++) {
					for (int x = 0; x < 8; x++) {
						// 水印文字成45度角倾斜
		                under.showTextAligned(Element.ALIGN_LEFT
		                        , waterMarkName, 100 + 300 * x, 300 * y, 45);					}
				}
                
                // 添加水印文字
                under.endText();
                under.setLineWidth(1f);
                under.stroke();
            }
            stamper.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
      
      public static void main(String[] args) { 
      	System.out.println(pdfUtils.waterMark("D:\\222\\表单&正文.pdf", "D:\\222\\正文.pdf", "中文水印"));
      }
      
}

 

你可能感兴趣的:(JAVA 使用itextpdf给pdf加水印)