pdf 文本转换为 java 字符串

来源:互联网 发布:舞蹈软件下载 编辑:程序博客网 时间:2024/04/24 10:19

txt,rtf,rtfd->pdf,mac下面有个非常好用的工具,TextEditor,简洁实用!

pdf->txt,如下(依赖两个jar 包:pdfbox-1.6.0.jar、fontbox-1.6.0.jar):

[java] view plaincopy
  1. package org.bruce.toolkit.experiments;  
  2.   
  3. import java.io.ByteArrayOutputStream;  
  4. import java.io.File;  
  5. import java.io.OutputStreamWriter;  
  6.   
  7. import org.apache.pdfbox.pdmodel.PDDocument;  
  8. import org.apache.pdfbox.util.PDFTextStripper;  
  9.   
  10. /** 
  11.  * @author Bruce Yang 
  12.  * 将 pdf 文件中的字符解析为字符串中的字符~ 
  13.  */  
  14. public class Pdf2Text {  
  15.   
  16.     /** 
  17.      * @param args 
  18.      * @throws Exception 
  19.      */  
  20.     public static void main(String[] args) throws Exception {  
  21. //      System.out.println(parsePDF("/Users/user/Desktop/QT教程.pdf"));  
  22.         System.out.println(parsePDF("/Users/user/Novels/pdf/《盗墓笔记》第一季:.第二部.怒海潜沙.pdf"));  
  23.     }  
  24.   
  25.     /** 
  26.      * @param filePath 
  27.      * @return 
  28.      * @throws Exception 
  29.      */  
  30.     public static String parsePDF(String filePath) throws Exception {  
  31.         File file = new File(filePath);  
  32.         String context = "";  
  33.         ByteArrayOutputStream out = new ByteArrayOutputStream();  
  34.         OutputStreamWriter writer = new OutputStreamWriter(out);  
  35.         PDDocument pdfdocument = null;  
  36.   
  37.         pdfdocument = PDDocument.load(file);  
  38.         PDFTextStripper stripper = new PDFTextStripper();  
  39.         stripper.writeText(pdfdocument, writer);  
  40.         byte[] contents = out.toByteArray();  
  41.         System.out.println(contents.length);  
  42.         context = new String(contents);  
  43.   
  44.         writer.close();  
  45.         if (pdfdocument != null) {  
  46.             pdfdocument.close();  
  47.         }  
  48.         return context;  
  49.     }  
  50. }  
原创粉丝点击