[转]JAVA代码PDFBOX对pdf文件的操作

 

转载地址:http://blog.csdn.net/reserved_person/article/details/52785153 

PDFBox是Java实现的PDF文档协作类库,提供PDF文档的创建、处理以及文档内容提取功能,也包含了一些命令行实用工具。其主要特性包括: 
1、提取PDF文件的Unicode文本 
2、将PDF切分成多个PDF文件或合并多个PDF文件 
3、从PDF表格中提取数据或填写PDF表格 
4、验证PDF文件是否符合PDF/A-1b标准 
5、使用标准的Java API打印PDF文件 
6、将PDF文件保存为图像文件,如PNG、JPEG 
7、创建一个PDF文件,包含嵌入的字体和图像 
8、PDF文件进行数字签名,即对PDF 文档进行加密与解密

 

[java] view plain copy
 
 print?在CODE上查看代码片派生到我的代码片
  1. import java.io.FileInputStream;  
  2. import java.io.FileNotFoundException;  
  3. import java.io.FileOutputStream;  
  4. import java.io.IOException;  
  5. import java.io.OutputStreamWriter;  
  6. import java.io.Writer;  
  7. import java.text.SimpleDateFormat;  
  8. import java.util.Calendar;  
  9. import java.util.List;  
  10. import java.util.Map;  
  11. import java.util.logging.Level;  
  12. import java.util.logging.Logger;  
  13. import org.apache.pdfbox.pdfparser.PDFParser;  
  14. import org.apache.pdfbox.pdmodel.PDDocument;  
  15. import org.apache.pdfbox.pdmodel.PDDocumentCatalog;  
  16. import org.apache.pdfbox.pdmodel.PDDocumentInformation;  
  17. import org.apache.pdfbox.pdmodel.PDPage;  
  18. import org.apache.pdfbox.pdmodel.PDResources;  
  19. import org.apache.pdfbox.pdmodel.graphics.xobject.PDXObjectImage;  
  20. import org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDDocumentOutline;  
  21. import org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineItem;  
  22. import org.apache.pdfbox.util.PDFTextStripper;  
  23. importstatic readPDFContent.PDFParse.dateFormat;  
  24.   
  25. /** 
  26.  * 
  27.  * @author Angela 
  28.  */publicclassPDFReader {/**  
  29.      * 获取格式化后的时间信息  
  30.      * @param calendar   时间信息  
  31.      * @return     */publicstatic String dateFormat( Calendar calendar ){    
  32.         if( null == calendar )    
  33.             returnnull;    
  34.         String date = null;      
  35.         String pattern = "yyyy-MM-dd HH:mm:ss";    
  36.         SimpleDateFormat format = new SimpleDateFormat( pattern );    
  37.         date = format.format( calendar.getTime() );    
  38.         return date == null ? "" : date;    
  39.     }    
  40.   
  41.         /**打印纲要**/publicstaticvoidgetPDFOutline(String file){  
  42.         try {    
  43.             //打开pdf文件流  
  44.             FileInputStream fis = new   FileInputStream(file);  
  45.             //加载 pdf 文档,获取PDDocument文档对象  
  46.             PDDocument document=PDDocument.load(fis);  
  47.             //获取PDDocumentCatalog文档目录对象  
  48.             PDDocumentCatalog catalog=document.getDocumentCatalog();  
  49.             //获取PDDocumentOutline文档纲要对象  
  50.             PDDocumentOutline outline=catalog.getDocumentOutline();  
  51.             //获取第一个纲要条目(标题1)  
  52.             PDOutlineItem item=outline.getFirstChild();  
  53.             if(outline!=null){  
  54.                 //遍历每一个标题1while(item!=null){  
  55.                     //打印标题1的文本  
  56.                     System.out.println("Item:"+item.getTitle());  
  57.                     //获取标题1下的第一个子标题(标题2)  
  58.                     PDOutlineItem child=item.getFirstChild();   
  59.                     //遍历每一个标题2while(child!=null){  
  60.                         //打印标题2的文本  
  61.                         System.out.println("    Child:"+child.getTitle());  
  62.                         //指向下一个标题2  
  63.                         child=child.getNextSibling();  
  64.                     }  
  65.                     //指向下一个标题1  
  66.                     item=item.getNextSibling();  
  67.                 }  
  68.             }  
  69.             //关闭输入流  
  70.             document.close();  
  71.             fis.close();  
  72.         } catch (FileNotFoundException ex) {  
  73.             Logger.getLogger(PDFBOXReader.class.getName()).log(Level.SEVERE, null, ex);  
  74.         } catch (IOException ex) {  
  75.             Logger.getLogger(PDFBOXReader.class.getName()).log(Level.SEVERE, null, ex);  
  76.         }   
  77.     }  
  78.   
  79.     /**打印一级目录**/publicstaticvoidgetPDFCatalog(String file){  
  80.         try {    
  81.             //打开pdf文件流  
  82.             FileInputStream fis = new   FileInputStream(file);  
  83.             //加载 pdf 文档,获取PDDocument文档对象  
  84.             PDDocument document=PDDocument.load(fis);  
  85.             //获取PDDocumentCatalog文档目录对象  
  86.             PDDocumentCatalog catalog=document.getDocumentCatalog();  
  87.             //获取PDDocumentOutline文档纲要对象  
  88.             PDDocumentOutline outline=catalog.getDocumentOutline();  
  89.             //获取第一个纲要条目(标题1)if(outline!=null){  
  90.                 PDOutlineItem item=outline.getFirstChild();  
  91.                 //遍历每一个标题1while(item!=null){  
  92.                     //打印标题1的文本  
  93.                     System.out.println("Item:"+item.getTitle());                 
  94.                     //指向下一个标题1  
  95.                     item=item.getNextSibling();  
  96.                 }  
  97.             }  
  98.             //关闭输入流  
  99.             document.close();  
  100.             fis.close();  
  101.         } catch (FileNotFoundException ex) {  
  102.             Logger.getLogger(PDFBOXReader.class.getName()).log(Level.SEVERE, null, ex);  
  103.         } catch (IOException ex) {  
  104.             Logger.getLogger(PDFBOXReader.class.getName()).log(Level.SEVERE, null, ex);  
  105.         }   
  106.     }  
  107.   
  108.     /**获取PDF文档元数据**/publicstaticvoidgetPDFInformation(String file){  
  109.         try {    
  110.             //打开pdf文件流  
  111.             FileInputStream fis = new   FileInputStream(file);  
  112.             //加载 pdf 文档,获取PDDocument文档对象  
  113.             PDDocument document=PDDocument.load(fis);  
  114.             /** 文档属性信息 **/            PDDocumentInformation info = document.getDocumentInformation();   
  115.   
  116.             System.out.println("页数:"+document.getNumberOfPages());  
  117.   
  118.             System.out.println( "标题:" + info.getTitle() );    
  119.             System.out.println( "主题:" + info.getSubject() );    
  120.             System.out.println( "作者:" + info.getAuthor() );    
  121.             System.out.println( "关键字:" + info.getKeywords() );               
  122.   
  123.             System.out.println( "应用程序:" + info.getCreator() );    
  124.             System.out.println( "pdf 制作程序:" + info.getProducer() );    
  125.   
  126.             System.out.println( "Trapped:" + info.getTrapped() );    
  127.   
  128.             System.out.println( "创建时间:" + dateFormat( info.getCreationDate() ));    
  129.             System.out.println( "修改时间:" + dateFormat( info.getModificationDate()));    
  130.   
  131.             //关闭输入流  
  132.             document.close();  
  133.             fis.close();  
  134.         } catch (FileNotFoundException ex) {  
  135.             Logger.getLogger(PDFReader.class.getName()).log(Level.SEVERE, null, ex);  
  136.         } catch (IOException ex) {  
  137.             Logger.getLogger(PDFReader.class.getName()).log(Level.SEVERE, null, ex);  
  138.         }   
  139.     }  
  140.   
  141.     /**提取pdf文本**/publicstaticvoidextractTXT(String file){  
  142.         try{  
  143.             //打开pdf文件流  
  144.             FileInputStream fis = new   FileInputStream(file);  
  145.             //实例化一个PDF解析器  
  146.             PDFParser parser = new PDFParser(fis);  
  147.             //解析pdf文档  
  148.             parser.parse();  
  149.             //获取PDDocument文档对象  
  150.             PDDocument document=parser.getPDDocument();  
  151.             //获取一个PDFTextStripper文本剥离对象             
  152.             PDFTextStripper stripper = new PDFTextStripper();  
  153.             //获取文本内容  
  154.             String content = stripper.getText(document);   
  155.             //打印内容  
  156.             System.out.println( "内容:" + content );     
  157.             document.close();  
  158.             fis.close();  
  159.         } catch (FileNotFoundException ex) {  
  160.             Logger.getLogger(PDFReader.class.getName()).log(Level.SEVERE, null, ex);  
  161.         } catch (IOException ex) {  
  162.             Logger.getLogger(PDFReader.class.getName()).log(Level.SEVERE, null, ex);  
  163.         }  
  164.     }  
  165.   
  166.     /** 
  167.      * 提取部分页面文本 
  168.      * @param file pdf文档路径 
  169.      * @param startPage 开始页数 
  170.      * @param endPage 结束页数 
  171.      */publicstaticvoidextractTXT(String file,int startPage,int endPage){  
  172.         try{  
  173.             //打开pdf文件流  
  174.             FileInputStream fis = new   FileInputStream(file);  
  175.             //实例化一个PDF解析器  
  176.             PDFParser parser = new PDFParser(fis);  
  177.             //解析pdf文档  
  178.             parser.parse();  
  179.             //获取PDDocument文档对象  
  180.             PDDocument document=parser.getPDDocument();  
  181.             //获取一个PDFTextStripper文本剥离对象             
  182.             PDFTextStripper stripper = new PDFTextStripper();  
  183.             // 设置起始页  
  184.             stripper.setStartPage(startPage);  
  185.             // 设置结束页  
  186.             stripper.setEndPage(endPage);  
  187.             //获取文本内容  
  188.             String content = stripper.getText(document);   
  189.             //打印内容  
  190.             System.out.println( "内容:" + content );     
  191.             document.close();  
  192.             fis.close();  
  193.         } catch (FileNotFoundException ex) {  
  194.             Logger.getLogger(PDFReader.class.getName()).log(Level.SEVERE, null, ex);  
  195.         } catch (IOException ex) {  
  196.             Logger.getLogger(PDFReader.class.getName()).log(Level.SEVERE, null, ex);  
  197.         }  
  198.     }  
  199.   
  200.     /** 
  201.      * 提取图片并保存 
  202.      * @param file PDF文档路径 
  203.      * @param imgSavePath 图片保存路径 
  204.      */publicstaticvoidextractImage(String file,String imgSavePath){  
  205.         try{  
  206.             //打开pdf文件流  
  207.             FileInputStream fis = new   FileInputStream(file);  
  208.             //加载 pdf 文档,获取PDDocument文档对象  
  209.             PDDocument document=PDDocument.load(fis);             
  210.             /** 文档页面信息 **///获取PDDocumentCatalog文档目录对象  
  211.             PDDocumentCatalog catalog = document.getDocumentCatalog();  
  212.             //获取文档页面PDPage列表  
  213.             List pages = catalog.getAllPages();    
  214.             int count = 1;    
  215.             int pageNum=pages.size();   //文档页数//遍历每一页for( int i = 0; i < pageNum; i++ ){    
  216.                 //取得第i页  
  217.                 PDPage page = ( PDPage ) pages.get( i );   
  218.                 if( null != page ){    
  219.                     PDResources resource = page.findResources();                        
  220.                     //获取页面图片信息   
  221.                     Map<String,PDXObjectImage> imgs = resource.getImages();                      
  222.                     for(Map.Entry<String,PDXObjectImage> me: imgs.entrySet()){  
  223.                         //System.out.println(me.getKey());  
  224.                         PDXObjectImage img = me.getValue();    
  225.                         //保存图片,会自动添加图片后缀类型  
  226.                         img.write2file( imgSavePath + count );    
  227.                         count++;    
  228.                     }    
  229.                 }    
  230.             }    
  231.             document.close();  
  232.             fis.close();  
  233.         } catch (FileNotFoundException ex) {  
  234.             Logger.getLogger(PDFReader.class.getName()).log(Level.SEVERE, null, ex);  
  235.         } catch (IOException ex) {  
  236.             Logger.getLogger(PDFReader.class.getName()).log(Level.SEVERE, null, ex);  
  237.         }  
  238.     }  
  239.   
  240.     /** 
  241.      * 提取文本并保存 
  242.      * @param file PDF文档路径 
  243.      * @param savePath 文本保存路径 
  244.      */publicstaticvoidextractTXT(String file,String savePath){  
  245.         try{  
  246.             //打开pdf文件流  
  247.             FileInputStream fis = new   FileInputStream(file);  
  248.             //实例化一个PDF解析器  
  249.             PDFParser parser = new PDFParser(fis);  
  250.             //解析pdf文档  
  251.             parser.parse();  
  252.             //获取PDDocument文档对象  
  253.             PDDocument document=parser.getPDDocument();  
  254.             //获取一个PDFTextStripper文本剥离对象             
  255.             PDFTextStripper stripper = new PDFTextStripper();  
  256.             //创建一个输出流  
  257.             Writer writer=new OutputStreamWriter(new FileOutputStream(savePath));  
  258.             //保存文本内容  
  259.             stripper.writeText(document, writer);               
  260.             //关闭输出流  
  261.             writer.close();  
  262.             //关闭输入流  
  263.             document.close();  
  264.             fis.close();  
  265.         } catch (FileNotFoundException ex) {  
  266.             Logger.getLogger(PDFReader.class.getName()).log(Level.SEVERE, null, ex);  
  267.         } catch (IOException ex) {  
  268.             Logger.getLogger(PDFReader.class.getName()).log(Level.SEVERE, null, ex);  
  269.         }  
  270.     }  
  271.   
  272.     /** 
  273.      * 提取部分页面文本并保存 
  274.      * @param file PDF文档路径 
  275.      * @param startPage 开始页数 
  276.      * @param endPage 结束页数 
  277.      * @param savePath 文本保存路径 
  278.      */publicstaticvoidextractTXT(String file,int startPage,  
  279.             int endPage,String savePath){  
  280.         try{  
  281.             //打开pdf文件流  
  282.             FileInputStream fis = new   FileInputStream(file);  
  283.             //实例化一个PDF解析器  
  284.             PDFParser parser = new PDFParser(fis);  
  285.             //解析pdf文档  
  286.             parser.parse();  
  287.             //获取PDDocument文档对象  
  288.             PDDocument document=parser.getPDDocument();  
  289.             //获取一个PDFTextStripper文本剥离对象             
  290.             PDFTextStripper stripper = new PDFTextStripper();  
  291.             //创建一个输出流  
  292.             Writer writer=new OutputStreamWriter(new FileOutputStream(savePath));  
  293.             // 设置起始页  
  294.             stripper.setStartPage(startPage);  
  295.             // 设置结束页  
  296.             stripper.setEndPage(endPage);  
  297.             //保存文本内容  
  298.             stripper.writeText(document, writer);               
  299.             //关闭输出流  
  300.             writer.close();  
  301.             //关闭输入流  
  302.             document.close();  
  303.             fis.close();  
  304.         } catch (FileNotFoundException ex) {  
  305.             Logger.getLogger(PDFReader.class.getName()).log(Level.SEVERE, null, ex);  
  306.         } catch (IOException ex) {  
  307.             Logger.getLogger(PDFReader.class.getName()).log(Level.SEVERE, null, ex);  
  308.         }  
  309.     }  
  310.   
  311.     publicstaticvoidmain(String args[]){  
  312.         String file="F:\\pdf\\2013\\000608_阳光股份_2013年年度报告(更新后)_1.pdf";  
  313.         String savePath="E:\\result1.txt";  
  314.         long startTime=System.currentTimeMillis();  
  315.         extractTXT(file,savePath);  
  316.         long endTime=System.currentTimeMillis();  
  317.         System.out.println("读写所用时间为:"+(endTime-startTime)+"ms");  
  318.     }  
  319.   
  320. }  

posted on 2017-02-27 11:22  Crysaty  阅读(1132)  评论(0编辑  收藏  举报

导航