第三方软件

1、pdfbox

PDFBox 0.7.3。PDFBox是一个开源的对pdf文件进行操作的库。 PDFBox-0.7.3.jar加入classpath。同时FontBox1.0.jar加入classpath,否则报错:

Exception in thread "main" java.lang.NoClassDefFoundError: org/fontbox/afm/FontMetric

Caused by: java.lang.ClassNotFoundException: org.fontbox.afm.FontMetric

代码1

 1 import java.io.FileInputStream;
 2 import java.io.FileNotFoundException;
 3 import java.io.IOException;
 4
 5 import org.pdfbox.pdfparser.PDFParser;
 6 import org.pdfbox.pdmodel.PDDocument;
 7 import org.pdfbox.util.PDFTextStripper;
 8
 9 public class PdfReader {
10     /**
11      * simply reader all the text from a pdf file.
12      * You have to deal with the format of the output text by yourself.
13      * 2008-2-25
14      * @param pdfFilePath file path
15      * @return all text in the pdf file
16      */
17     public static String getTextFromPDF(String pdfFilePath)
18     {
19         String result = null;
20         FileInputStream is = null;
21         PDDocument document = null;
22         try {
23             is = new FileInputStream(pdfFilePath);
24             PDFParser parser = new PDFParser(is);
25             parser.parse();
26             document = parser.getPDDocument();
27             PDFTextStripper stripper = new PDFTextStripper();
28             result = stripper.getText(document);
29         } catch (FileNotFoundException e) {
30             // TODO Auto-generated catch block
31             e.printStackTrace();
32         } catch (IOException e) {
33             // TODO Auto-generated catch block
34             e.printStackTrace();
35         } finally {
36             if (is != null) {
37                 try {
38                     is.close();
39                 } catch (IOException e) {
40                     // TODO Auto-generated catch block
41                     e.printStackTrace();
42                 }
43             }
44             if (document != null) {
45                 try {
46                     document.close();
47                 } catch (IOException e) {
48                     // TODO Auto-generated catch block
49                     e.printStackTrace();
50                 }
51             }
52         }
53         return result;
54     }
55     public  static void main(String[] args)
56     {
57         String str=PdfReader.getTextFromPDF("C:\\Read.pdf");
58         System.out.println(str);
59
60     }
61 }  

参考: http://daning.iteye.com/blog/165284

代码2

 1 import java.io.File;
 2 import java.io.FileOutputStream;
 3 import java.io.OutputStreamWriter;
 4 import java.io.Writer;
 5 import java.net.MalformedURLException;
 6 import java.net.URL;
 7 import org.pdfbox.pdmodel.PDDocument;
 8 import org.pdfbox.util.PDFTextStripper;
 9 public class PDFReader {
10  public void readFdf(String file) throws Exception {
11   // 是否排序
12   boolean sort = false;
13   // pdf文件名
14   String pdfFile = file;
15   // 输入文本文件名称
16   String textFile = null;
17   // 编码方式
18   String encoding = "UTF-8";
19   // 开始提取页数
20   int startPage = 1;
21   // 结束提取页数
22   int endPage = Integer.MAX_VALUE;
23   // 文件输入流,生成文本文件
24   Writer output = null;
25   // 内存中存储的PDF Document
26   PDDocument document = null;
27   try {
28    try {
29     // 首先当作一个URL来装载文件,如果得到异常再从本地文件系统//去装载文件
30     URL url = new URL(pdfFile);
31    //注意参数已不是以前版本中的URL.而是File。
32     document = PDDocument.load(pdfFile);
33     // 获取PDF的文件名
34     String fileName = url.getFile();
35     // 以原来PDF的名称来命名新产生的txt文件
36     if (fileName.length() > 4) {
37      File outputFile = new File(fileName.substring(0, fileName
38        .length() - 4)
39        + ".txt");
40      textFile = outputFile.getName();
41     }
42    } catch (MalformedURLException e) {
43     // 如果作为URL装载得到异常则从文件系统装载
44    //注意参数已不是以前版本中的URL.而是File。
45     document = PDDocument.load(pdfFile);
46     if (pdfFile.length() > 4) {
47      textFile = pdfFile.substring(0, pdfFile.length() - 4)
48        + ".txt";
49     }
50    }
51    // 文件输入流,写入文件倒textFile
52    output = new OutputStreamWriter(new FileOutputStream(textFile),
53      encoding);
54    // PDFTextStripper来提取文本
55    PDFTextStripper stripper = null;
56    stripper = new PDFTextStripper();
57    // 设置是否排序
58    stripper.setSortByPosition(sort);
59    // 设置起始页
60    stripper.setStartPage(startPage);
61    // 设置结束页
62    stripper.setEndPage(endPage);
63    // 调用PDFTextStripper的writeText提取并输出文本
64    stripper.writeText(document, output);
65   } finally {
66    if (output != null) {
67     // 关闭输出流
68     output.close();
69    }
70    if (document != null) {
71     // 关闭PDF Document
72     document.close();
73    }
74   }
75  }
76  /**
77   * @param args
78   */
79  public static void main(String[] args) {
80   // TODO Auto-generated method stub
81      PDFReader pdfReader = new PDFReader();
82   try {
83    // 取得E盘下的SpringGuide.pdf的内容
84    pdfReader.readFdf("C:\\Read.pdf");
85   } catch (Exception e) {
86    e.printStackTrace();
87   }
88  }
89 } 

参考:http://blog.csdn.net/weijie_search/article/details/2662189

2、抽取支持中文的pdf文件-xpdf
xpdf是一个开源项目,我们可以调用他的本地方法来实现抽取中文pdf文件。
下载xpdf函数包:
http://www.java-cn.com/technology/tech_downs/1880_004.zip
同时需要下载支持中文的补丁包:
http://www.java-cn.com/technology/tech_downs/1880_005.zip
按照readme放好中文的patch,就可以开始写调用本地方法的java程序了
下面是一个如何调用的例子:

 1 import java.io.*;
 2 /**
 3 * <p>Title: pdf extraction</p>
 4 * <p>Description: email:chris@matrix.org.cn</p>
 5 * <p>Copyright: Matrix Copyright (c) 2003</p>
 6 * <p>Company: Matrix.org.cn</p>
 7 * @author chris
 8 * @version 1.0,who use this example pls remain the declare
 9 */
10
11
12 public class PdfWin {
13 public PdfWin() {
14 }
15 public static void main(String args[]) throws Exception
16 {
17 String PATH_TO_XPDF="C:Program Filesxpdfpdftotext.exe";
18 String filename="c:a.pdf";
19 String[] cmd = new String[] { PATH_TO_XPDF, "-enc", "UTF-8", "-q", filename, "-"};
20 Process p = Runtime.getRuntime().exec(cmd);
21 BufferedInputStream bis = new BufferedInputStream(p.getInputStream());
22 InputStreamReader reader = new InputStreamReader(bis, "UTF-8");
23 StringWriter out = new StringWriter();
24 char [] buf = new char[10000];
25 int len;
26 while((len = reader.read(buf))>= 0) {
27 //out.write(buf, 0, len);
28 System.out.println("the length is"+len);
29 }
30 reader.close();
31 String ts=new String(buf);
32 System.out.println("the str is"+ts);
33 }
34 }  

参考:http://blog.csdn.net/lyd518/article/details/2318224

3、iText

iText作为在Java中处理PDF文档的工具被广泛使用,各种开源项目中都比较常见。现在就使用iText提供的API将PDF文档中的文本信息导出为纯文本,虽然现在很多工具中都已经支持这样的操作,这是第一步也算是读取PDF文件最常见的需求。

首先下载iText包,地址为http://sourceforge.net/projects/itext/,最新版本为5.1.2,完整包名为iText-5.1.2.zip,解压后将得到一组jar包,我们要使用的是里面的itextpdf-5.1.2.jar。在本地配置好Java编译和运行环境后,编写如下示例代码:

 1 import java.io.IOException;
 2
 3 import com.itextpdf.text.pdf.PdfReader;
 4 import com.itextpdf.text.pdf.parser.PdfReaderContentParser;
 5 import com.itextpdf.text.pdf.parser.SimpleTextExtractionStrategy;
 6 import com.itextpdf.text.pdf.parser.TextExtractionStrategy;
 7
 8 public class PDFReader {
 9
10  /**
11   * @param args
12   * @throws IOException
13   */
14  public static void main(String[] args) throws IOException {
15   System.out.print(getPdfFileText("E:\\test\\plugindoc.pdf"));
16  }
17
18  public static String getPdfFileText(String fileName) throws IOException {
19   PdfReader reader = new PdfReader(fileName);
20   PdfReaderContentParser parser = new PdfReaderContentParser(reader);
21   StringBuffer buff = new StringBuffer();
22   TextExtractionStrategy strategy;
23   for (int i = 1; i <= reader.getNumberOfPages(); i++) {
24    strategy = parser.processContent(i,
25      new SimpleTextExtractionStrategy());
26    buff.append(strategy.getResultantText());
27   }
28   return buff.toString();
29  }
30
31 } 

参考:http://blog.csdn.net/mscf/article/details/6957061

1,2都不能读出目标pdf,其它pdf可以

3.1能够读出目标pdf,但是按页读取的,没法按行读取

代码2 按行读取

仿照iTextsharp

  1 package com.iText.read.pdf;
  2
  3
  4 import java.io.IOException;
  5 import java.util.Arrays;
  6
  7 import com.itextpdf.text.pdf.PdfReader;
  8
  9 public class PdfIO {
 10
 11       ///<summary>
 12     ///读取单个或多个pdf
 13     ///</summary>
 14     ///<returns>文件内容字符串</returns>
 15     @SuppressWarnings("null")
 16     public static String readPdf(String fileName) throws IOException
 17     {
 18
 19             PdfReader p = new PdfReader(fileName);
 20             //从每一页读出的字符串
 21             String str = null;
 22             //"[......]"内部字符串
 23             String subStr =null;
 24             //函数返回的字符串
 25             StringBuffer rtBuf=new  StringBuffer();
 26
 27             String rtStr=null;
 28
 29             //"[","]","(",")"在字符串中的位置
 30             int bg = 0, ed = 0, subbg = 0, subed = 0;
 31
 32
 33
 34             //":"前面的字符串
 35             String fc =null;
 36
 37             //":"前面的字符串
 38             String bc =null;
 39
 40
 41
 42             //取得文档总页数
 43             int pg = p.getNumberOfPages();
 44
 45
 46             // ExcelIO ei = new ExcelIO();
 47             for (int i = 1; i <= 1; i++)
 48             {
 49
 50
 51                 bg = 0;
 52                 ed = 0;
 53
 54                //Arrays.fill(b, 0);
 55
 56               //从每一页读出的8位字节数组
 57                 byte[] b = new byte[0];
 58                 //取得第i页的内容
 59                 b = p.getPageContent(i);
 60
 61                 //下一行是把每一页的取得的字节数据写入一个txt的文件,仅供研究时用
 62                 //System.IO.File.WriteAllBytes(Application.StartupPath + "//P" + i.ToString() + ".txt", b);
 63
 64                 StringBuilder sb = new StringBuilder();
 65
 66                 //取得每一页的字节数组,将每一个字节转换为字符,并将数组转换为字符串
 67                 for (int j = 0; j < b.length; j++) sb.append((char)(b[j]));
 68                 str = sb.toString();
 69
 70                 //return str;
 71
 72                if (str.indexOf("[") >= 0)
 73                 {
 74
 75                     //循环寻找"["和"]",直到找不到"["为止
 76                     while (bg > -1)
 77                     {
 78                         //取得下一个"["和"]"的位置
 79                         bg = str.indexOf("[", ed);
 80                         ed = str.indexOf("]", bg + 1);
 81
 82                         //如果没有下一个"["就跳出循环
 83                         if (bg == -1) break;
 84
 85                         //取得一个"[]"里的内容,将开始寻找"("和")"的位置初始为0
 86                         subStr = str.substring(bg + 1, ed - bg - 1);
 87                         subbg = 0;
 88                         subed = 0;
 89
 90                         //循环寻找下一个"("和")",直到没有下一个"("就跳出循环
 91                         while (subbg > -1)
 92                         {
 93                             //取得下一对"()"的位置
 94                             subbg = subStr.indexOf("(", subed);
 95                             subed = subStr.indexOf(")", subbg + 1);
 96
 97                             //如找不到下一对就跳出
 98                             if (subbg == -1) break;
 99                             //在返回字符串后面加上新找到的字符串
100                             rtStr = subStr.substring(subbg + 1, subed - subbg - 1);
101
102
103
104                         }
105                         rtStr+= rtStr + "|";
106                     }
107                     return rtStr;
108                 }
109                 else
110                 {
111                     //每页的行数
112                     int lineNumber = 0;
113                     while (bg > -1)
114                     {
115                         //取得下一个"("和")"的位置
116                         bg = str.indexOf("(", ed);
117                         ed = str.indexOf(")", bg + 1);
118                         //如果没有下一个"["就跳出循环
119                         if (bg == -1) break;
120                         //每行加个'|'为以后分隔准备,为什么不用"/n/r",因为不需要换行功能
121                         //rtStr += str.substring(bg + 1, ed-1) + "|";
122
123                         String rtStrTemp = str.substring(bg + 1, ed-1);
124
125                         rtBuf.append(rtStrTemp);
126                         rtBuf.append("|");
127
128                     }
129                     rtStr=rtBuf.toString();
130
131
132                 }
133
134
135             }
136             if (p != null)
137             {
138                 p.close();
139             }
140
141             return rtStr;
142
143
144     }
145
146 }

转载于:https://www.cnblogs.com/wangwiz/p/9172690.html

java读取pdf总结相关推荐

  1. java读取pdf文本转换html

    java读取pdf文本转换html 完整代码地址 也就两个文件 java读取pdf中的纯文字,这里使用的是pdfbox工具包 maven引入如下配置 <dependency><gro ...

  2. Java读取pdf模板,并动态生成pdf文件,如动态生成准考证

    Java读取pdf模板,并动态生成pdf文件,如动态生成准考证 ​ 前几天遇到了一个生成准考证的需求,并提供用户下载,然后百度了一圈还是觉得使用itextpdf这个框架好用点.但是还需要找到一个能创建 ...

  3. 用Java读取pdf中的数据

    用Java简单的读取pdf文件中的数据: 第一步:下载PDFBox-0.7.2.jar.提供一个下载地址:[url]http://pdfhome.hope.com.cn/Resource.aspx?C ...

  4. Java 读取PDF中表格的工具

    目录 1.方法1:Spire.PDF 1.1 Maven仓库下载导入 1.2 读取PDF中的表格 1.2.1 代码 1.2.2 表格内容 1.2.3 读取结果 2.方法2:Tabula 2.1 Mav ...

  5. java 读取pdf各级标题_Java那些事之pdf读取

    今天说说java中的pdf读取,实话说,这是一个很恼人的任务.现在网络上的pdf各种各样,分析出来的文本也是千差万别,目前最流行的jar包pdfbox也只能做到把文字分析出来,并无法很好的控制分析的顺 ...

  6. Java 读取PDF中的文本和图片

    本文将介绍通过Java程序来读取PDF文档中的文本和图片的方法.分别调用方法extractText()和extractImages()来读取. 使用工具:Free Spire.PDF for Java ...

  7. java 读取pdf、word、Excel文件

    用到的jar: itextpdf-5.5.8.jar   (PDF) poi.jar public class FileUtils {/*** 判断文件是否存在* * @Title: isExcite ...

  8. java pdf分页显示,java读取pdf(可分页读取)

    需要pdfbox和log4j的包 举个例子: import org.pdfbox.pdfparser.*; import org.pdfbox.util.PDFTextStripper; import ...

  9. java 读取pdf签名域_Java给PDF签名

    1.引入依赖 com.e-iceblue e-iceblue http://repo.e-iceblue.cn/repository/maven-public/ e-iceblue spire.pdf ...

最新文章

  1. CVPR 2021 | 从理论和实验角度深入剖析对比损失中的温度超参数
  2. Tomcat web.xml配置参数详解
  3. 数字统计2(依然是数组下标法)
  4. 自动化运维工具 Ansible
  5. 银河麒麟V10入选2020中国十大科技新闻
  6. XCode5.1.1怎样实现代码块自己主动排版
  7. linux suse11 nfs,suse11 nfsserver服务安装
  8. paip.php 与js 的相似性以及为什么它们这么烂还很流行。。
  9. aardio + .NET 快速开发独立 EXE 程序,可防 ILSpy 反编译
  10. 将多个excel文件合并为:一个excel文件的多个sheet页【方法技巧】
  11. python求学生成绩平均值_python 计算student_grade.txt 中 语文成绩的平均值, 找出数学成绩最高的学生是谁...
  12. 小学语文必背的古诗词分类汇总,建议给孩子收藏!
  13. python.exe无法找到入口 无法定位程序输入点
  14. Win10设置:输入法快捷键【仅保留中英切换】,其他花里胡哨快捷键全部删除
  15. 计算机怎么保存窗口画面,电脑视频怎么旋转保存 怎样将视频画面进行旋转并保存|视频画面旋转工具...
  16. linux 使用regulator
  17. 2021年度训练联盟热身训练赛第三场——C,G,I
  18. 小树corexy改voron装前必看
  19. 考研调剂信息爬取,以“小木虫”为例
  20. 1.4 无穷小与无穷大

热门文章

  1. OpenCV中的神经网络
  2. Dockerflie概述
  3. 深度学习矩阵乘法的终极奥义einsum,结合多个计算框架上的使用
  4. 强制OOALV运行数据修改事件
  5. 30分钟搭建你的静态网站
  6. C# 加密-密钥容器
  7. 阿里云、蚂蚁区块链医疗解决方案首次应用于未来医院电子处方
  8. abaqus在不同job间传递结果(import)之整理与问题(转载)
  9. Revit MEP 平面视图中(立管)怎么设置二维表达?
  10. Java使用Spire.Pdf实现PDF添加图片水印