JAVA 는 itextpdf 를 사용 하여 pdf 에 워 터 마크 를 추가 합 니 다.

2767 단어
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", "    "));
      }
      
}

좋은 웹페이지 즐겨찾기