技术标签: java读取pdf
第三方软件
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 importjava.io.FileInputStream;2 importjava.io.FileNotFoundException;3 importjava.io.IOException;4
5 importorg.pdfbox.pdfparser.PDFParser;6 importorg.pdfbox.pdmodel.PDDocument;7 importorg.pdfbox.util.PDFTextStripper;8
9 public classPdfReader {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-2514 *@parampdfFilePath file path15 *@returnall text in the pdf file16 */
17 public staticString getTextFromPDF(String pdfFilePath)18 {19 String result = null;20 FileInputStream is = null;21 PDDocument document = null;22 try{23 is = newFileInputStream(pdfFilePath);24 PDFParser parser = newPDFParser(is);25 parser.parse();26 document =parser.getPDDocument();27 PDFTextStripper stripper = newPDFTextStripper();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 returnresult;54 }55 public static voidmain(String[] args)56 {57 String str=PdfReader.getTextFromPDF("C:\\Read.pdf");58 System.out.println(str);59
60 }61 }
代码2
1 importjava.io.File;2 importjava.io.FileOutputStream;3 importjava.io.OutputStreamWriter;4 importjava.io.Writer;5 importjava.net.MalformedURLException;6 importjava.net.URL;7 importorg.pdfbox.pdmodel.PDDocument;8 importorg.pdfbox.util.PDFTextStripper;9 public classPDFReader {10 public void readFdf(String file) throwsException {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 = newURL(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, fileName38 .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(newFileOutputStream(textFile),53 encoding);54 //PDFTextStripper来提取文本
55 PDFTextStripper stripper = null;56 stripper = newPDFTextStripper();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 *@paramargs78 */
79 public static voidmain(String[] args) {80 //TODO Auto-generated method stub
81 PDFReader pdfReader = newPDFReader();82 try{83 //取得E盘下的SpringGuide.pdf的内容
84 pdfReader.readFdf("C:\\Read.pdf");85 } catch(Exception e) {86 e.printStackTrace();87 }88 }89 }
2、抽取支持中文的pdf文件-xpdfxpdf是一个开源项目,我们可以调用他的本地方法来实现抽取中文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 *
Title: pdf extraction
4 *Description: email:[email protected]
5 *Copyright: Matrix Copyright (c) 2003
6 *Company: Matrix.org.cn
7 *@authorchris8 *@version1.0,who use this example pls remain the declare9 */10
11
12 public classPdfWin {13 publicPdfWin() {14 }15 public static void main(String args[]) throwsException16 {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 = newBufferedInputStream(p.getInputStream());22 InputStreamReader reader = new InputStreamReader(bis, "UTF-8");23 StringWriter out = newStringWriter();24 char [] buf = new char[10000];25 intlen;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=newString(buf);32 System.out.println("the str is"+ts);33 }34 }
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 importjava.io.IOException;2
3 importcom.itextpdf.text.pdf.PdfReader;4 importcom.itextpdf.text.pdf.parser.PdfReaderContentParser;5 importcom.itextpdf.text.pdf.parser.SimpleTextExtractionStrategy;6 importcom.itextpdf.text.pdf.parser.TextExtractionStrategy;7
8 public classPDFReader {9
10 /**
11 *@paramargs12 *@throwsIOException13 */
14 public static void main(String[] args) throwsIOException {15 System.out.print(getPdfFileText("E:\\test\\plugindoc.pdf"));16 }17
18 public static String getPdfFileText(String fileName) throwsIOException {19 PdfReader reader = newPdfReader(fileName);20 PdfReaderContentParser parser = newPdfReaderContentParser(reader);21 StringBuffer buff = newStringBuffer();22 TextExtractionStrategy strategy;23 for (int i = 1; i <= reader.getNumberOfPages(); i++) {24 strategy =parser.processContent(i,25 newSimpleTextExtractionStrategy());26 buff.append(strategy.getResultantText());27 }28 returnbuff.toString();29 }30
31 }
1,2都不能读出目标pdf,其它pdf可以
3.1能够读出目标pdf,但是按页读取的,没法按行读取
代码2 按行读取
仿照iTextsharp
1 packagecom.iText.read.pdf;2
3
4 importjava.io.IOException;5 importjava.util.Arrays;6
7 importcom.itextpdf.text.pdf.PdfReader;8
9 public classPdfIO {10
11 ///
12 ///读取单个或多个pdf
13 ///
14 ///文件内容字符串
15 @SuppressWarnings("null")16 public static String readPdf(String fileName) throwsIOException17 {18
19 PdfReader p = newPdfReader(fileName);20 //从每一页读出的字符串
21 String str = null;22 //"[......]"内部字符串
23 String subStr =null;24 //函数返回的字符串
25 StringBuffer rtBuf=newStringBuffer();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 = newStringBuilder();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 returnrtStr;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 returnrtStr;142
143
144 }145
146 }
一、自定义菜单的说明和按钮类型1、菜单说明1)自定义菜单最多包括3个一级菜单,每个一级菜单最多包含5个二级菜单。2)一级菜单最多4个汉字,二级菜单最多7个汉字,多出来的部分将会以“...”代替。3)创建自定义菜单后,菜单的刷新策略是,在用户进入公众号会话页或公众号profile页时,如果发现上一次拉取菜单的请求在5分钟以前,就会拉取一下菜单,如果菜单有更新,就会刷新客户端的菜单。
1. Action bar 内容 app icon view control action icon action overflow 2. Split Action Bar :一行action bar放不下时 在activity的manifest 文件中定义uiOptions="splitActionBarWhenNarrow" 可以吧top
安装 19c 的 rpm 版本非常简洁,和 18c 一致:以下是 19c 中的步骤。首先下载 preinstall 包:[[email protected] ~]# curl -o oracle-database-preinstall-19c-1.0-1.el7.x86_64.rpm https://yum.oracle.com/repo/OracleLinux/OL7/latest/x86_64/getPack...
一、经纬度转换为世界坐标1.Cesium.Cartesian3.fromDegrees(longitude, latitude, height, ellipsoid, result) 2.var ellipsoid=viewer.scene.globe.ellipsoid; var cartographic=Cesium.Cartographic.fromDegrees(lng,lat,alt);...
第一次玩,吐槽一句,bug太多浪费了大量时间上图,请各位大爷欣赏:不得不说还是很人性化的,最有通关还有哈利路亚之歌,啊哈哈~
1.登陆数据库 cmd命令窗口登陆数据库 序号 说明 登陆步骤 1 进入sql sqlplus 2 登陆Oracle 用户名/密码后面跟@oracle 3 ...
浅谈HTTP、TCP、UDP、IP协议概念HTTP 报文结构TCP UDPTCP/IP补充概念(记得深入学习传输协议时候还是在大学的网络工程课程,时间过了近3年了,现在重新拾起这块知识)start:HTTP 报文结构HTTP报文是面向文本的,报文中的每一个字段都是一些ASCII码串,各个字段的长度是不确定的。HTTP有两类报文:请求报文和响应报文。HTTP请求报文:一个HTTP...
一、reqeusts.get:def get(url, params=None, **kwargs)其中**kwargs:十二个控制访问参数,均为可选项1)params:字典或者字节序列,作为参数增加到url中2)data:字典、字节序列或者文件对象,作为Request的内容json:JSON格式的数据,作为Request的内容3)headers:字典,HTTP定制头4)c
ubuntu20.04+pytorch_GPU+cuda+pycharm+Anaconda
SEO优化扫我一、服务器无法连接远程桌面1、Ping不通IP,网站打不开,不可以远程连接。可能是服务器死机了,或者网络有问题,请尝试Web重启服务器或联系服务商确认。2、Ping正常,网站可以打开,远程桌面无法连接,请尝试Web重启服务器或者联系服务商确认。另外你是否修改了远程桌面端口,而没有在防火墙例外该端口.3、终端服务器超出了最大允许连接数,Windows 2003 系统默认可以同时登陆2个...
前言最近公司需要使用 Next 结合 React 、 Antd-Mobile 开发服务端渲染的H5,于是就看了些文档搭建一个简单地环境记录下来。Next文档一、搭建基础环境1. 使用 yarn 或者 npm 初始化一个文件夹yarn initORnpm init2. 安装要使用的包package.json 整体配置{ "name": "next-react-demo"...
1.问题描述:给定一个链表,删除链表中倒数第n个节点,返回链表的头节点。2.样例:Example 1: Input: list = 1->2->3->4->5->null, n = 2 Output: 1->2->3->5->nullExample 2: Input: list = 5->4->3->2->1->null, n = 2 Output: 5->4...