Java解析PDF文件(PDFBOX、itext解析PDF)导出PDF中的子图片,去除PDF中的水印

原文地址:http://blog.csdn.net/sinat_29957455/article/details/68951228?locationNum=6&fps=1


前段时间,为了解析PDF,花了不少时间去学习PDFbox和itext,这两个都是处理PDF的开源库,有java和C#的。作为一个刚开始学习这两个开源库的,感觉百度上的资源还是太少了。我做的是一个关于PDF的处理,在百度上找了半天都没找到答案,最后去itext的官网和Stack Overflow上找到了答案。最后比较了一下,pdfbox和itext相对而言,itext的功能要强不少,本人对比过itext和pdfbox处理pdf 文件时候的速度itext要快一些,而且itext官网给出的例子和一些问题(这些问题都是从Stack Overflow上面的问题),所以我最后选择了itext,itext5例子这个链接是itext5官方的例子,非常需要注意的一个地方就是,不同版本的itext对于解决同一个问题的代码可以不同,个人觉得itext7相对于itext5的改变挺大的。下面我的一些例子都是itext5.5.11版本的,这个链接可以下载itext5.5.11的jar包itext5.5.11 jar下载itext dll这个链接可以下载itext5.5.11的dll包。其实java和c#在使用itext的时候都是一样的。下面我会,给出几个关于PDF操作的一些例子。都是一些处理PDF的例子,对于如何去制作一个PDF文件可以去itext官网找资料。在itext中处理PDF文件都是以字典对象进行封装的,这个和PDF的结构是一样的,可以去参考PDF reference

一、导出PDF中的子图片

[java]  view plain  copy
  1. public static void extractImage(String filename){  
  2.           
  3.         PdfReader reader = null;  
  4.         try {  
  5.             //读取pdf文件  
  6.             reader = new PdfReader(filename);  
  7.             //获得pdf文件的页数  
  8.             int sumPage = reader.getNumberOfPages();      
  9.             //读取pdf文件中的每一页  
  10.             for(int i = 1;i <= sumPage;i++){  
  11.                 //得到pdf每一页的字典对象  
  12.                 PdfDictionary dictionary = reader.getPageN(i);  
  13.                 //通过RESOURCES得到对应的字典对象  
  14.                 PdfDictionary res = (PdfDictionary) PdfReader.getPdfObject(dictionary.get(PdfName.RESOURCES));  
  15.                 //得到XOBJECT图片对象  
  16.                 PdfDictionary xobj = (PdfDictionary) PdfReader.getPdfObject(res.get(PdfName.XOBJECT));  
  17.                 if(xobj != null){  
  18.                     for(Iterator it = xobj.getKeys().iterator();it.hasNext();){  
  19.                         PdfObject obj = xobj.get((PdfName)it.next());             
  20.                         if(obj.isIndirect()){  
  21.                             PdfDictionary tg = (PdfDictionary) PdfReader.getPdfObject(obj);                   
  22.                             PdfName type = (PdfName) PdfReader.getPdfObject(tg.get(PdfName.SUBTYPE));  
  23.                             if(PdfName.IMAGE.equals(type)){       
  24.                                 PdfObject object =  reader.getPdfObject(obj);  
  25.                                 if(object.isStream()){                        
  26.                                     PRStream prstream = (PRStream)object;  
  27.                                     byte[] b;  
  28.                                     try{  
  29.                                         b = reader.getStreamBytes(prstream);  
  30.                                     }catch(UnsupportedPdfException e){  
  31.                                         b = reader.getStreamBytesRaw(prstream);  
  32.                                     }  
  33.                                     FileOutputStream output = new FileOutputStream(String.format("d:/pdf/output%d.jpg",i));  
  34.                                     output.write(b);  
  35.                                     output.flush();  
  36.                                     output.close();                               
  37.                                 }  
  38.                             }  
  39.                         }  
  40.                     }  
  41.                 }  
  42.             }  
  43.               
  44.         } catch (IOException e) {  
  45.             // TODO Auto-generated catch block  
  46.             e.printStackTrace();  
  47.         }  
[java]  view plain  copy
  1. }  

这个例子是我在百度上搜到的,但是并不完整,这个是导出PDF中的图片,我将他补充完整了。这个程序有问题,可以对于某些PDF文件导出的图片无法打开。

二、去除PDF文件的水印字体

[java]  view plain  copy
  1. /** 
  2.  * <a href="http://stackoverflow.com/questions/35526822/removing-watermark-from-pdf-itextsharp"> 
  3.  * Removing Watermark from PDF iTextSharp 
  4.  * </a> 
  5.  * <p> 
  6.  * This class presents a simple content stream editing framework. As is it creates an equivalent 
  7.  * copy of the original page content stream. To actually edit, simply overwrite the method 
  8.  * {@link #write(PdfContentStreamProcessor, PdfLiteral, List)} to not (as in this class) write 
  9.  * the given operations as they are but change them in some fancy way. 
  10.  * </p> 
  11.  *  
  12.  * @author mkl 
  13.  */  
  14. public class PdfContentStreamEditor extends PdfContentStreamProcessor  
  15. {  
  16.       
  17.     public static void main(String[] args) {  
  18.         try {  
  19.             PdfReader reader = new PdfReader("input.pdf");  
  20.             OutputStream result = new FileOutputStream(new File("out.pdf"));  
  21.             PdfStamper pdfStamper = new PdfStamper(reader, result);  
  22.             PdfContentStreamEditor identityEditor = new PdfContentStreamEditor();  
  23.             for(int i = 1;i <= reader.getNumberOfPages();i++){  
  24.                 identityEditor.editPage(pdfStamper, i);  
  25.             }  
  26.             pdfStamper.close();  
  27.         } catch (IOException e) {  
  28.             // TODO Auto-generated catch block  
  29.             e.printStackTrace();  
  30.         } catch (DocumentException e) {  
  31.             // TODO Auto-generated catch block  
  32.             e.printStackTrace();  
  33.         }  
  34.     }  
  35.       
  36.     /** 
  37.      * This method edits the immediate contents of a page, i.e. its content stream. 
  38.      * It explicitly does not descent into form xobjects, patterns, or annotations. 
  39.      */  
  40.     public void editPage(PdfStamper pdfStamper, int pageNum) throws IOException  
  41.     {  
  42.         PdfReader pdfReader = pdfStamper.getReader();  
  43.         PdfDictionary page = pdfReader.getPageN(pageNum);  
  44.         byte[] pageContentInput = ContentByteUtils.getContentBytesForPage(pdfReader, pageNum);  
  45.         page.remove(PdfName.CONTENTS);  
  46.         editContent(pageContentInput, page.getAsDict(PdfName.RESOURCES), pdfStamper.getUnderContent(pageNum));  
  47.     }  
  48.       
  49.     /** 
  50.      * This method processes the content bytes and outputs to the given canvas. 
  51.      * It explicitly does not descent into form xobjects, patterns, or annotations. 
  52.      */  
  53.     public void editContent(byte[] contentBytes, PdfDictionary resources, PdfContentByte canvas)  
  54.     {  
  55.         this.canvas = canvas;  
  56.         processContent(contentBytes, resources);  
  57.         this.canvas = null;  
  58.     }  
  59.       
  60.     /** 
  61.      * <p> 
  62.      * This method writes content stream operations to the target canvas. The default 
  63.      * implementation writes them as they come, so it essentially generates identical 
  64.      * copies of the original instructions the {@link ContentOperatorWrapper} instances 
  65.      * forward to it. 
  66.      * </p> 
  67.      * <p> 
  68.      * Override this method to achieve some fancy editing effect. 
  69.      * </p>  
  70.      */  
  71.     protected void write(PdfContentStreamProcessor processor, PdfLiteral operator, List<PdfObject> operands) throws IOException  
  72.     {  
  73.         int index = 0;  
  74.   
  75.         for (PdfObject object : operands)  
  76.         {  
  77.             object.toPdf(canvas.getPdfWriter(), canvas.getInternalBuffer());  
  78.             canvas.getInternalBuffer().append(operands.size() > ++index ? (byte' ' : (byte'\n');  
  79.         }  
  80.     }  
  81.   
  82.     //  
  83.     // constructor giving the parent a dummy listener to talk to   
  84.     //  
  85.     public PdfContentStreamEditor()  
  86.     {  
  87.         super(new DummyRenderListener());  
  88.     }  
  89.   
  90.     //  
  91.     // Overrides of PdfContentStreamProcessor methods  
  92.     //  
  93.     @Override  
  94.     public ContentOperator registerContentOperator(String operatorString, ContentOperator operator)  
  95.     {  
  96.         ContentOperatorWrapper wrapper = new ContentOperatorWrapper();  
  97.         wrapper.setOriginalOperator(operator);  
  98.         ContentOperator formerOperator = super.registerContentOperator(operatorString, wrapper);  
  99.         return formerOperator instanceof ContentOperatorWrapper ? ((ContentOperatorWrapper)formerOperator).getOriginalOperator() : formerOperator;  
  100.     }  
  101.   
  102.     @Override  
  103.     public void processContent(byte[] contentBytes, PdfDictionary resources)  
  104.     {  
  105.         this.resources = resources;   
  106.         super.processContent(contentBytes, resources);  
  107.         this.resources = null;  
  108.     }  
  109.   
  110.     //  
  111.     // members holding the output canvas and the resources  
  112.     //  
  113.     protected PdfContentByte canvas = null;  
  114.     protected PdfDictionary resources = null;  
  115.       
  116.     //  
  117.     // A content operator class to wrap all content operators to forward the invocation to the editor  
  118.     //  
  119.     class ContentOperatorWrapper implements ContentOperator  
  120.     {  
  121.         public ContentOperator getOriginalOperator()  
  122.         {  
  123.             return originalOperator;  
  124.         }  
  125.   
  126.         public void setOriginalOperator(ContentOperator originalOperator)  
  127.         {  
  128.             this.originalOperator = originalOperator;  
  129.         }  
  130.   
  131.         @Override  
  132.         public void invoke(PdfContentStreamProcessor processor, PdfLiteral operator, ArrayList<PdfObject> operands) throws Exception  
  133.         {  
  134.             if (originalOperator != null && !"Do".equals(operator.toString()))  
  135.             {  
  136.                 originalOperator.invoke(processor, operator, operands);  
  137.             }  
  138.             write(processor, operator, operands);  
  139.         }  
  140.           
  141.         private ContentOperator originalOperator = null;  
  142.     }  
  143.   
  144.     //  
  145.     // A dummy render listener to give to the underlying content stream processor to feed events to  
  146.     //  
  147.     static class DummyRenderListener implements RenderListener  
  148.     {  
  149.         @Override  
  150.         public void beginTextBlock() { }  
  151.   
  152.         @Override  
  153.         public void renderText(TextRenderInfo renderInfo) { }  
  154.   
  155.         @Override  
  156.         public void endTextBlock() { }  
  157.   
  158.         @Override  
  159.         public void renderImage(ImageRenderInfo renderInfo) { }  
  160.     }  
  161. }  
上面这个类是官方给出的一个工具类

[java]  view plain  copy
  1. public static void main(String[] args) {  
  2.         try {  
  3.             PdfReader pdfReader = new PdfReader("d:/1.pdf");  
  4.             FileOutputStream os = new FileOutputStream("d:/reader.pdf");  
  5.             PdfStamper stamper = new PdfStamper(pdfReader,os);  
  6.             PdfContentStreamEditor editor = new PdfContentStreamEditor(){                 
  7.                 @Override  
  8.                 protected void write(PdfContentStreamProcessor processor, PdfLiteral operator, List<PdfObject> operands)  
  9.                         throws IOException {  
  10.                     String operatorString = operator.toString();  
  11.                     //Tj 操作通过当前的字体和其他文字相关的图形状态参数来取走一串操作和绘制相应的字形  
  12.                     //Tr操作设置的文本渲染模式  
  13.                     //一个文本对象开始于BT,结束于ET  
  14.                     final List<String> TEXT_SHOWING_OPERATORS = Arrays.asList("Tj","'","\\","TJ");  
  15.                     System.out.println(operatorString);  
  16.                     if(TEXT_SHOWING_OPERATORS.contains(operatorString)){  
  17.                         PdfDictionary dic = gs().getFont().getFontDictionary();                       
  18.                         if(gs().getFont().getPostscriptFontName().endsWith("BoldMT")){//BoldMT字体的名称  
  19.                             return;  
  20.                         }  
  21.                     }  
  22.                     super.write(processor, operator, operands);  
  23.                 }  
  24.             };  
  25.             for(int i = 1;i <= pdfReader.getNumberOfPages();i++){  
  26.                 editor.editPage(stamper, i);  
  27.             }  
  28.             stamper.close();  
  29.         } catch (IOException e) {  
  30.             // TODO Auto-generated catch block  
  31.             e.printStackTrace();  
  32.         } catch (DocumentException e) {  
  33.             // TODO Auto-generated catch block  
  34.             e.printStackTrace();  
  35.         }  
  36.     }  

用itext处理PDF文件的时候RenderListener非常有用,他是itext里面的一个接口,你可以建立一个类去实现它,然后重新它的方法,可以在里面写处理PDF文件具体功能。这个接口,提供了处理文字和图片的方法需要你重写。我是在Stack Overflow上面找到的,真的就像那个说的一样,就是万能的。




猜你喜欢

转载自blog.csdn.net/zxgmdzz/article/details/78426951