워 터 마크 가 있 는 pdf 내 보 내기

18890 단어 자바필기 하 다.
package com.util.pdf;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Security;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.imageio.ImageIO;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.jpedal.PdfDecoder;
import org.jpedal.exception.PdfException;

import com.itextpdf.text.BadElementException;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.pdf.CMYKColor;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfGState;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.PdfTemplate;
import com.itextpdf.text.pdf.PdfTransparencyGroup;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.Image;
import com.pde.app.util.PdeTools;

/**
 * 
 * @ClassName PdfUtil 
 * @Description PDF    
 * @version 1.0.0
 */
public class PdfUtil {
    
	/**
	 * 
	 * @Title addWatermark 
	 * @Description       PDF  
	 * @param filename  PDF  
	 * @param outfile         
	 * @param transparency      0--1
	 * @param Watermarks     
	 * @param ownerPassWord      
	 * @return boolean 
	 * @since  1.0.0
	 */
    public boolean addWatermark(String filename,String outfile,float transparency,List Watermarks,String ownerPassWord) {
    	boolean r = false;
    	PdfReader reader = null;
    	PdfStamper stamp = null;
    	FileOutputStream fileoutputS= null;
        try {
             if (null == ownerPassWord || "".equals(ownerPassWord)) { 
                 reader = new PdfReader(filename); 
             } else { 
                 reader = new PdfReader(filename, ownerPassWord.getBytes()); 
             } 
             fileoutputS =  new FileOutputStream(outfile);
             stamp = new PdfStamper(reader, fileoutputS);
             //    
         	 PdfGState gs = new PdfGState();
         	 gs.setFillOpacity(transparency);
             for(int i=1;i<=reader.getNumberOfPages();i++){
            	 PdfContentByte content = null;
                 PdfTemplate template = null;
                 for(WatermarkAbstract watermark :Watermarks){
                	 if(!watermark.isNeedByPage(i)){
                		 continue;
                	 }
                	 if(null==content){
                		 content = stamp.getOverContent(i);
                	 }
                	 float pageHeight =reader.getPageSize(i).getHeight();
                     float pageWidth= reader.getPageSize(i).getWidth();
                     if(null==template){
                    	 template = this.createTemplate(content, pageWidth, pageHeight);
                	 }
                     template = watermark.addWatermarkToTemplate(template);
                 }
                 if(null!=template && null!=content){
                	 content.setGState(gs);
                     content.addTemplate(template, 0, 0);
                 }
             }  
         }
         catch (Exception de) {
        	 de.printStackTrace();
             return false;
         }finally{
 			 try {
        		 if(stamp!=null)
        			 stamp.close();
			} catch (DocumentException e) {
			} catch (IOException e) {
			}	
        	if(reader!=null)
 				reader.close();	
        	try {
 				if(fileoutputS!=null){
 					fileoutputS.flush();
 					fileoutputS.close();
 				}
 			} catch (IOException e) {
 			}
         }
         File f = new File(outfile);
         if(f.isFile()){
        	 r = true;
         }
         return r;
     }
    
    /**
     * 
     * @Title createTemplate 
     * @Description   PdfTemplate 
     * @param content
     * @param pageWidth
     * @param pageHeight
     * @return
     * @throws BadElementException
     * @throws MalformedURLException
     * @throws IOException
     * @throws DocumentException PdfTemplate 
     * @since  1.0.0
     */
    public PdfTemplate createTemplate(PdfContentByte content,float pageWidth,float pageHeight) throws BadElementException, MalformedURLException, IOException, DocumentException{
    	PdfTemplate template =content.createTemplate(pageWidth, pageHeight);
        PdfTransparencyGroup transGroup = new PdfTransparencyGroup();
        transGroup.setIsolated(true);
        transGroup.setKnockout(false);
        template.setGroup(transGroup);
        return template;
    }
    /**
	 * 
	 * @Title addWatermark 
	 * @Description       PDF  
	 * @param filename  PDF  
	 * @param outfile         
	 * @param transparency      0--1
	 * @param Watermarks     
	 * @return boolean 
	 * @since  1.0.0
	 */
    public boolean addWatermark(String filename,String outfile,float transparency,List Watermarks){
    	return this.addWatermark(filename, outfile, transparency, Watermarks,null);
    }
     
     /** 
      * Itext     
      * 
      * @param originalFile 
      *            pdf     
      * @param encryptedFile 
      *                   pdf     
      * @param certFile 
      *                 
      * @param password 
      *                 
      * @param ownerPassWord 
      *                  
      */ 
     public void certificateEncryption(String originalFile, 
             String encryptedFile, String certFile, String password, 
             String ownerPassWord) { 
         PdfReader reader = null; 
         InputStream is = null; 
         PdfStamper stamper = null; 
         try { 

             //   providers ( %JAVA_HOME%/jre/lib/security/java.security      sun   providers ) 
             Security.addProvider(new BouncyCastleProvider()); 
             //                   ownerPassWord 
             if (null == ownerPassWord || "".equals(ownerPassWord)) { 
                 reader = new PdfReader(originalFile); 
             } else { 
                 reader = new PdfReader(originalFile, ownerPassWord.getBytes()); 
             } 
             stamper = new PdfStamper(reader, 
                     new FileOutputStream(encryptedFile)); 
             is = new FileInputStream(certFile); 
             // SubjectPublicKeyInfo(  X.509     )public key 
//             CertificateFactory cf = CertificateFactory.getInstance("X.509"); 
//             Certificate cert = cf.generateCertificate(is); 
//             
             X509Certificate cert = getCertFromKeyStoreFile(certFile, "intca",
            		 password);
             
             
             Certificate[] certs = new Certificate[1]; 
             certs[0] = cert; 

             int[] permissions = new int[1]; 
             
             
				permissions[0] = PdfWriter.ALLOW_MODIFY_CONTENTS | PdfWriter.ALLOW_COPY
						| PdfWriter.ALLOW_ASSEMBLY | PdfWriter.ALLOW_FILL_IN
						| PdfWriter.ALLOW_MODIFY_ANNOTATIONS
						| PdfWriter.ALLOW_SCREENREADERS;
				stamper.setEncryption(certs, permissions,
						PdfWriter.SPACE);
         } catch (Exception e) { 
             e.printStackTrace(); 
         } finally {
        	try {
         		 if(stamper!=null)
         			stamper.close();
 			} catch (DocumentException e) {
 			} catch (IOException e) {
 			}
            //     
        	if(reader!=null)
  				reader.close();
         	try {
  				if(is!=null)
  					is.close();
  			} catch (IOException e) {
  			}
         	
         } 
     }
     
     /**
 	 *     
 	 * @param fullFileName
 	 * @param alias
 	 * @param storepass
 	 * @return
 	 */
 	public X509Certificate getCertFromKeyStoreFile(String fullFileName,
 			String alias, String storepass) {
 		X509Certificate cert = null;
 		BufferedInputStream bIn = null;
 		try {
 			bIn = new BufferedInputStream(new FileInputStream(fullFileName));
 			KeyStore keyStore = KeyStore.getInstance("PKCS12", "BC");
 			keyStore.load(bIn, storepass.toCharArray());
 			Certificate[] certs = keyStore.getCertificateChain(alias);
 			cert = (X509Certificate) certs[0];

 		} catch (KeyStoreException e) {
 			e.printStackTrace();
 		} catch (NoSuchProviderException e) {
 			e.printStackTrace();
 		} catch (FileNotFoundException e) {
 			e.printStackTrace();
 		} catch (NoSuchAlgorithmException e) {
 			e.printStackTrace();
 		} catch (CertificateException e) {
 			e.printStackTrace();
 		} catch (IOException e) {
 			e.printStackTrace();
 		}finally{
 			if(null != bIn)
 				try {
 					bIn.close();
 				} catch (IOException e) {
 					e.printStackTrace();
 				}
 		}
 		return cert;
 	}
     
    /**
     * 
     * @Title setEncryption 
     * @Description PDF     
     * @param originalFile pdf     
     * @param encryptedFile        pdf     
     * @param original_ownerPassWord         
     * @param userPassWord      
     * @param ownerPassWord       
     * @param permissions      PdfWriter.ALLOW_ASSEMBLY | PdfWriter.ALLOW_COPY | PdfWriter.ALLOW_DEGRADED_PRINTING | PdfWriter.ALLOW_FILL_IN
     *  | PdfWriter.ALLOW_MODIFY_ANNOTATIONS | PdfWriter.ALLOW_MODIFY_CONTENTS | PdfWriter.ALLOW_PRINTING | PdfWriter.ALLOW_SCREENREADERS; 
     * return void 
     * @since  1.0.0
     */
     public void setEncryption(String originalFile,String encryptedFile,
    		 String original_ownerPassWord,String userPassWord,String ownerPassWord,int permissions) { 
         PdfReader reader = null; 
         PdfStamper stamper = null; 
         try { 
             if (null == original_ownerPassWord || "".equals(original_ownerPassWord)) { 
                 reader = new PdfReader(originalFile); 
             } else { 
                 reader = new PdfReader(originalFile, original_ownerPassWord.getBytes()); 
             } 
             stamper = new PdfStamper(reader, 
                     new FileOutputStream(encryptedFile)); 
             // pdf     
             //stamper.setEncryption(PdfWriter.ENCRYPTION_AES_128,null,null,PdfWriter.ALLOW_COPY ); 
             stamper.setEncryption(userPassWord.getBytes(), ownerPassWord.getBytes(), permissions, false);
         } catch (Exception e) { 
             e.printStackTrace(); 
         } finally {
        	try {
        		if(stamper!=null)
        			stamper.close();
 			} catch (DocumentException e) {
 			} catch (IOException e) {
 			}
        	if(reader!=null)
  				reader.close();
         } 
     }
     
     
	public void addTextWatermarkPdfsoft(String inputfile,String outputfile){
		List watermarks = new ArrayList();
		Set textpages = new HashSet();
		textpages.add(1);
		watermarks.add(new WatermarkText(2,0,10,45,0,null,"   gds" ,CMYKColor.BLUE,Element.ALIGN_LEFT,1,50));
		watermarks.add(new WatermarkImage(3,0,0,45,0,null,null,PdeTools.imageToByteArray(new File("f:/testinput/p9.png")),100));
		watermarks.add(new WatermarkRectangle(1,20,20,10,0,null,CMYKColor.BLUE,150,100,1));
		watermarks.add(new WatermarkRectangle(1,10,10,0,0,textpages,CMYKColor.BLUE,20,10,1));
		watermarks.add(new WatermarkText(1,14,12,0,0,textpages,"01",CMYKColor.RED,Element.ALIGN_LEFT,0,8));
		watermarks.add(new WatermarkRectangle(1,30,10,0,0,textpages,CMYKColor.BLUE,20,10,1));
		watermarks.add(new WatermarkText(1,31,12,0,0,textpages,"2012",CMYKColor.GRAY,Element.ALIGN_LEFT,0,8));
		watermarks.add(new WatermarkRectangle(1,50,10,0,0,textpages,CMYKColor.BLUE,20,10,1));
		watermarks.add(new WatermarkText(1,52,10,0,0,textpages,"  ",CMYKColor.RED,Element.ALIGN_LEFT,1,8));
		watermarks.add(new WatermarkRectangle(1,10,20,0,0,textpages,CMYKColor.BLUE,20,10,1));
		watermarks.add(new WatermarkText(1,11,22,0,0,textpages,"0001",CMYKColor.GRAY,Element.ALIGN_LEFT,0,8));
		watermarks.add(new WatermarkRectangle(1,30,20,0,0,textpages,CMYKColor.BLUE,20,10,1));
		watermarks.add(new WatermarkRectangle(1,50,20,0,0,textpages,CMYKColor.BLUE,20,10,1));
		
		watermarks.add(new WatermarkEllipse(1,10,10,0,0,textpages,CMYKColor.BLACK,200,200,1));
		watermarks.add(new WatermarkEllipse(2,10,10,0,0,textpages,CMYKColor.BLUE,200,200,1));
		watermarks.add(new WatermarkEllipse(3,10,10,0,0,textpages,CMYKColor.CYAN,200,200,1));
		watermarks.add(new WatermarkEllipse(4,10,10,0,0,textpages,CMYKColor.DARK_GRAY,200,200,1));
		watermarks.add(new WatermarkEllipse(5,10,10,0,0,textpages,CMYKColor.GRAY,200,200,1));
		watermarks.add(new WatermarkEllipse(6,10,10,0,0,textpages,CMYKColor.GREEN,200,200,1));
		watermarks.add(new WatermarkEllipse(7,10,10,0,0,textpages,CMYKColor.LIGHT_GRAY,200,200,1));
		watermarks.add(new WatermarkEllipse(8,10,10,0,0,textpages,CMYKColor.MAGENTA,200,200,1));
		watermarks.add(new WatermarkEllipse(9,10,10,0,0,textpages,CMYKColor.ORANGE,200,200,1));
		PdfWatermarkUtil  pdfWatermarkUtil = new PdfWatermarkUtil(0.5f,watermarks);
		//addWatermark(inputfile, outputfile,0.5f,watermarks,"");
		pdfWatermarkUtil.addWatermark(inputfile, outputfile);
     }
     public static void main(String[] strs){
    	 //new PdfUtil().addTextWatermarkPdfsoft("f:/1/307.pdf", "f:/1/testWatermark.pdf");
    	 // new PdfUtil().certificateEncryption("f:/1/1.pdf", "f:/1/1.cer.pdf", "e:/IntCA.pfx", "123456", null);
    	 //new PdfUtil().setEncryption("f:/1/1.pdf", "f:/1/Encryption.pdf", null, "user", "pde", 16); 
    	 //pdfBoxToImagePdf("c:/111.pdf","c:/222.pdf",new int[]{1});
    	 pdfImportedPage("c:/12345.pdf","c:/222.pdf",new int[]{1,22});
     }
     
     
     /**
      * PDF     BufferedImage By PDFBOX
      * @param pdfFile
      * @param pageNumber
      * @return
      */
     @SuppressWarnings("unchecked")
	public static List pdfBoxToImage(String pdfFile,int[] pageNumber)   {
    	 List imgs= new ArrayList();
         PDDocument doc = null;  
         try {  
             doc = PDDocument.load(pdfFile);  
             List pages = (List)doc.getDocumentCatalog().getAllPages();  
             for(int pagen:pageNumber){
            	 if(pagen > pages.size()) return null;
            	 PDPage page = (PDPage) pages.get(pagen-1); 
            	 BufferedImage image = page.convertToImage();  
            	 imgs.add(image);
             }
         } catch (IOException e) {  
             e.printStackTrace();  
         }  finally {
 		   	if(doc!=null){
 		   		try {
					doc.close();
				} catch (IOException e) {
				}
 		   	}
 		}
        return imgs;
     }
     
     /**
      * PDF     BufferedImage By jpedal
      * @param pdfFile
      * @param pageNumber
      * @return
      */
	public static List jpedalToImage(String pdfFile,int[] pageNumber)   {
    	 List imgs= new ArrayList(); 
         PdfDecoder decoder = new PdfDecoder(true);
         try{
        	 decoder.openPdfFile(pdfFile);
        	 for(int pagen:pageNumber){
            	 if(pagen > decoder.getPageCount()) return null;
            	 BufferedImage image = decoder.getPageAsImage(pagen);  
            	 imgs.add(image);
        	 }
         } catch (PdfException e) {
         } finally {
             decoder.closePdfFile();
         }
    	 return imgs;
    }

     
     /**
      * PdfReader      
      * @param reader PdfReader
      * @param importedPdfFile       
      * @param pages     
      * @return
      */
     public static boolean pdfImportedPage(PdfReader reader,String importedPdfFile,int[] pages){
 		PdfCopy copyer = null; 
 		Document document = null;  
 		try { 
 			if(reader.getNumberOfPages()
      * @param pdfFile PDF   
      * @return
      */
     public static boolean bufferedImageToImagePdf(List bImages,String pdfFile){
     	boolean result = false;
     	if(bImages==null || bImages.size()==0) return false;
  		Document document = null;
  		try {
  			document = new Document(new com.itextpdf.text.Rectangle(bImages.get(0).getWidth()+60,
  					bImages.get(0).getHeight()+60), 30, 30, 30, 30);
  			PdfWriter.getInstance(document, new FileOutputStream(pdfFile));
  			document.open();
  			for(BufferedImage bImage : bImages){
  				document.newPage();
  				ByteArrayOutputStream baos = new ByteArrayOutputStream();   
  				ImageIO.write(bImage, "jpg", baos);   
  	            byte[] bytes = baos.toByteArray(); 
  	            baos.flush();
  	            bImage.flush();
	  			Image image = Image.getInstance(bytes);
  				document.setPageSize(new com.itextpdf.text.Rectangle(image.getWidth()+60,
  						image.getHeight()+60));
	  			document.add(image);
  			}
  			result = true;
  		} catch (DocumentException de) {
  			result = false;
  		} catch (IOException ioe) {
  			result = false;
  		}finally{
  			if(document!=null)
  				document.close();
  		}
  		return result;
     }
     
     /**
      *  PDF        PDF by PDFBOX
      * @param ipdfFile   pdf
      * @param opdfFile   pdf
      * @param pageNumber   
      * @return
      */
     public static boolean pdfBoxToImagePdf(String ipdfFile,String opdfFile,int []pageNumber)   {
    	 return bufferedImageToImagePdf(pdfBoxToImage(ipdfFile,pageNumber),opdfFile);
     }
     
     /**  PDF        PDF by jpedal
     * @param ipdfFile   pdf
     * @param opdfFile   pdf
     * @param pageNumber   
     * @return
     */
    public static boolean jpedalToImagePdf(String ipdfFile,String opdfFile,int []pageNumber)   {
   	 return bufferedImageToImagePdf(jpedalToImage(ipdfFile,pageNumber),opdfFile);
    }
     
     
     
}

좋은 웹페이지 즐겨찾기