欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

导出带水印的pdf

程序员文章站 2024-01-04 13:25:22
...
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<WatermarkAbstract> 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<WatermarkAbstract> 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<Watermark> watermarks = new ArrayList<Watermark>();
		Set<Integer> textpages = new HashSet<Integer>();
		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<BufferedImage> pdfBoxToImage(String pdfFile,int[] pageNumber)   {
    	 List<BufferedImage> imgs= new ArrayList<BufferedImage>();
         PDDocument doc = null;  
         try {  
             doc = PDDocument.load(pdfFile);  
             List<PDPage> pages = (List<PDPage>)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<BufferedImage> jpedalToImage(String pdfFile,int[] pageNumber)   {
    	 List<BufferedImage> imgs= new ArrayList<BufferedImage>(); 
         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()<pages[0]){
 				return false;
 			}
			document = new Document();  
			copyer = new PdfCopy(document, new FileOutputStream(importedPdfFile));             
	        document.open();
	        for(int page:pages){
	        	if(reader.getNumberOfPages()<page){
	 				return false;
	 			}
		        PdfImportedPage pager = copyer.getImportedPage(reader, page);  
		        copyer.addPage(pager);  
	        }
 		} catch (Exception e) { 
 			e.printStackTrace();
 			return false;
 		} finally {
 		   	if(document!=null){
 		   		document.close();
 		   	}
 		   	if(copyer!=null){
 		   		copyer.close();
 		   	}
 		}
 		return true;
     }
     
     public static boolean pdfImportedPage(String inputfile,String importedPdfFile,int[] pages){
    	 PdfReader reader = null;  
 		try { 
 			reader = new PdfReader(inputfile); 
 			return pdfImportedPage(reader,importedPdfFile,pages);
 		} catch (Exception e) { 
			return false;
		} finally {
		   	if(reader!=null){
		   		reader.close();
		   	}
		} 
     }
     
     /**
      * 将BufferedImage生成为PDF文件
      * @param bImages List<BufferedImage>
      * @param pdfFile PDF文件名
      * @return
      */
     public static boolean bufferedImageToImagePdf(List<BufferedImage> 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);
    }
     
     
     
}

 

上一篇:

下一篇: