第三方软件

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

 import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException; import org.pdfbox.pdfparser.PDFParser;
import org.pdfbox.pdmodel.PDDocument;
import org.pdfbox.util.PDFTextStripper; public class PdfReader {
/**
* simply reader all the text from a pdf file.
* You have to deal with the format of the output text by yourself.
* 2008-2-25
* @param pdfFilePath file path
* @return all text in the pdf file
*/
public static String getTextFromPDF(String pdfFilePath)
{
String result = null;
FileInputStream is = null;
PDDocument document = null;
try {
is = new FileInputStream(pdfFilePath);
PDFParser parser = new PDFParser(is);
parser.parse();
document = parser.getPDDocument();
PDFTextStripper stripper = new PDFTextStripper();
result = stripper.getText(document);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (document != null) {
try {
document.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return result;
}
public static void main(String[] args)
{
String str=PdfReader.getTextFromPDF("C:\\Read.pdf");
System.out.println(str); }
}

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

代码2

 import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.MalformedURLException;
import java.net.URL;
import org.pdfbox.pdmodel.PDDocument;
import org.pdfbox.util.PDFTextStripper;
public class PDFReader {
public void readFdf(String file) throws Exception {
// 是否排序
boolean sort = false;
// pdf文件名
String pdfFile = file;
// 输入文本文件名称
String textFile = null;
// 编码方式
String encoding = "UTF-8";
// 开始提取页数
int startPage = 1;
// 结束提取页数
int endPage = Integer.MAX_VALUE;
// 文件输入流,生成文本文件
Writer output = null;
// 内存中存储的PDF Document
PDDocument document = null;
try {
try {
// 首先当作一个URL来装载文件,如果得到异常再从本地文件系统//去装载文件
URL url = new URL(pdfFile);
//注意参数已不是以前版本中的URL.而是File。
document = PDDocument.load(pdfFile);
// 获取PDF的文件名
String fileName = url.getFile();
// 以原来PDF的名称来命名新产生的txt文件
if (fileName.length() > 4) {
File outputFile = new File(fileName.substring(0, fileName
.length() - 4)
+ ".txt");
textFile = outputFile.getName();
}
} catch (MalformedURLException e) {
// 如果作为URL装载得到异常则从文件系统装载
//注意参数已不是以前版本中的URL.而是File。
document = PDDocument.load(pdfFile);
if (pdfFile.length() > 4) {
textFile = pdfFile.substring(0, pdfFile.length() - 4)
+ ".txt";
}
}
// 文件输入流,写入文件倒textFile
output = new OutputStreamWriter(new FileOutputStream(textFile),
encoding);
// PDFTextStripper来提取文本
PDFTextStripper stripper = null;
stripper = new PDFTextStripper();
// 设置是否排序
stripper.setSortByPosition(sort);
// 设置起始页
stripper.setStartPage(startPage);
// 设置结束页
stripper.setEndPage(endPage);
// 调用PDFTextStripper的writeText提取并输出文本
stripper.writeText(document, output);
} finally {
if (output != null) {
// 关闭输出流
output.close();
}
if (document != null) {
// 关闭PDF Document
document.close();
}
}
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
PDFReader pdfReader = new PDFReader();
try {
// 取得E盘下的SpringGuide.pdf的内容
pdfReader.readFdf("C:\\Read.pdf");
} catch (Exception e) {
e.printStackTrace();
}
}
}

参考: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程序了
下面是一个如何调用的例子:

 import java.io.*;
/**
* <p>Title: pdf extraction</p>
* <p>Description: email:chris@matrix.org.cn</p>
* <p>Copyright: Matrix Copyright (c) 2003</p>
* <p>Company: Matrix.org.cn</p>
* @author chris
* @version 1.0,who use this example pls remain the declare
*/ public class PdfWin {
public PdfWin() {
}
public static void main(String args[]) throws Exception
{
String PATH_TO_XPDF="C:Program Filesxpdfpdftotext.exe";
String filename="c:a.pdf";
String[] cmd = new String[] { PATH_TO_XPDF, "-enc", "UTF-8", "-q", filename, "-"};
Process p = Runtime.getRuntime().exec(cmd);
BufferedInputStream bis = new BufferedInputStream(p.getInputStream());
InputStreamReader reader = new InputStreamReader(bis, "UTF-8");
StringWriter out = new StringWriter();
char [] buf = new char[10000];
int len;
while((len = reader.read(buf))>= 0) {
//out.write(buf, 0, len);
System.out.println("the length is"+len);
}
reader.close();
String ts=new String(buf);
System.out.println("the str is"+ts);
}
}

参考: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编译和运行环境后,编写如下示例代码:

 import java.io.IOException;  

 import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.parser.PdfReaderContentParser;
import com.itextpdf.text.pdf.parser.SimpleTextExtractionStrategy;
import com.itextpdf.text.pdf.parser.TextExtractionStrategy; public class PDFReader { /**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
System.out.print(getPdfFileText("E:\\test\\plugindoc.pdf"));
} public static String getPdfFileText(String fileName) throws IOException {
PdfReader reader = new PdfReader(fileName);
PdfReaderContentParser parser = new PdfReaderContentParser(reader);
StringBuffer buff = new StringBuffer();
TextExtractionStrategy strategy;
for (int i = 1; i <= reader.getNumberOfPages(); i++) {
strategy = parser.processContent(i,
new SimpleTextExtractionStrategy());
buff.append(strategy.getResultantText());
}
return buff.toString();
} }

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

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

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

代码2 按行读取

仿照iTextsharp

 package com.iText.read.pdf;  

 import java.io.IOException;
import java.util.Arrays; import com.itextpdf.text.pdf.PdfReader; public class PdfIO { ///<summary>
///读取单个或多个pdf
///</summary>
///<returns>文件内容字符串</returns>
@SuppressWarnings("null")
public static String readPdf(String fileName) throws IOException
{ PdfReader p = new PdfReader(fileName);
//从每一页读出的字符串
String str = null;
//"[......]"内部字符串
String subStr =null;
//函数返回的字符串
StringBuffer rtBuf=new StringBuffer(); String rtStr=null; //"[","]","(",")"在字符串中的位置
int bg = 0, ed = 0, subbg = 0, subed = 0; //":"前面的字符串
String fc =null; //":"前面的字符串
String bc =null; //取得文档总页数
int pg = p.getNumberOfPages(); // ExcelIO ei = new ExcelIO();
for (int i = 1; i <= 1; i++)
{ bg = 0;
ed = 0; //Arrays.fill(b, 0); //从每一页读出的8位字节数组
byte[] b = new byte[0];
//取得第i页的内容
b = p.getPageContent(i); //下一行是把每一页的取得的字节数据写入一个txt的文件,仅供研究时用
//System.IO.File.WriteAllBytes(Application.StartupPath + "//P" + i.ToString() + ".txt", b); StringBuilder sb = new StringBuilder(); //取得每一页的字节数组,将每一个字节转换为字符,并将数组转换为字符串
for (int j = 0; j < b.length; j++) sb.append((char)(b[j]));
str = sb.toString(); //return str; if (str.indexOf("[") >= 0)
{ //循环寻找"["和"]",直到找不到"["为止
while (bg > -1)
{
//取得下一个"["和"]"的位置
bg = str.indexOf("[", ed);
ed = str.indexOf("]", bg + 1); //如果没有下一个"["就跳出循环
if (bg == -1) break; //取得一个"[]"里的内容,将开始寻找"("和")"的位置初始为0
subStr = str.substring(bg + 1, ed - bg - 1);
subbg = 0;
subed = 0; //循环寻找下一个"("和")",直到没有下一个"("就跳出循环
while (subbg > -1)
{
//取得下一对"()"的位置
subbg = subStr.indexOf("(", subed);
subed = subStr.indexOf(")", subbg + 1); //如找不到下一对就跳出
if (subbg == -1) break;
//在返回字符串后面加上新找到的字符串
rtStr = subStr.substring(subbg + 1, subed - subbg - 1); }
rtStr+= rtStr + "|";
}
return rtStr;
}
else
{
//每页的行数
int lineNumber = 0;
while (bg > -1)
{
//取得下一个"("和")"的位置
bg = str.indexOf("(", ed);
ed = str.indexOf(")", bg + 1);
//如果没有下一个"["就跳出循环
if (bg == -1) break;
//每行加个'|'为以后分隔准备,为什么不用"/n/r",因为不需要换行功能
//rtStr += str.substring(bg + 1, ed-1) + "|"; String rtStrTemp = str.substring(bg + 1, ed-1); rtBuf.append(rtStrTemp);
rtBuf.append("|"); }
rtStr=rtBuf.toString(); } }
if (p != null)
{
p.close();
} return rtStr; } }

java读取pdf总结的更多相关文章

  1. java读取pdf文本转换html

    补充:一下代码基于maven,现将依赖的jar包单独导出 地址:pdf jar 完整代码地址 也就两个文件 java读取pdf中的纯文字,这里使用的是pdfbox工具包 maven引入如下配置 < ...

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

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

  3. Java 读取PDF中的表格

    一.概述 本文以Java示例展示读取PDF中的表格的方法.这里导入Spire.PDF for Javah中的jar包,并使用其提供的相关及方法来实现获取表格中的文本内容.下表中整理了本次代码使用到的主 ...

  4. java读取pdf和MS Office文档

    有时候PDF中的文字无法复制,这可能是因为PDF文件加密了,不过使用PDFBox开源软件就可以把它读出来. 还有一个用于创建PDF文件的项目----iText. PDFBox下面有两个子项目:Font ...

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

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

  6. JAVA 读取pdf文件

    第一个路口action /* * wuhan syspro author zhangrui 2010/08/23 */ package jp.co.syspro.poo.action; import ...

  7. java读取pdf文档

    import java.io.*;import org.pdfbox.pdmodel.PDDocument;import org.pdfbox.pdfparser.PDFParser;import o ...

  8. java读取txt/pdf/xls/xlsx/doc/docx/ppt/pptx

    环境准备txt利用common-iopdf利用pdfbox剩下的用POI关于POI,读取xls没啥特别的,主要是读取doc和ppt,需要下载poi源代码,然后将poi-src-3.7-20101029 ...

  9. java操作office和pdf文件java读取word,excel和pdf文档内容

    在平常应用程序中,对office和pdf文档进行读取数据是比较常见的功能,尤其在很多web应用程序中.所以今天我们就简单来看一下Java对word.excel.pdf文件的读取.本篇博客只是讲解简单应 ...

随机推荐

  1. 【ecshop】调用购物车商品数量

    1 打开 includes/lib_insert.php 在最后位置添加如下代码: /** * 调用购物车商品数目 */ function insert_cart_mes_num() { $sql = ...

  2. 求全局最小割(SW算法)

    hdu3002 King of Destruction Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (J ...

  3. rest_framework之频率详解 03

    访问频率(节流) 1.某个用户一分钟之内访问的次数不能超过3次,超过3次则不能访问了,需要等待,过段时间才能再访问. 2.自定义访问频率.两个方法都必须写上. 登入页面的视图加上访问频率 3.返回值F ...

  4. maven修改本地仓库地址配置文件

    本地仓库是远程仓库的一个缓冲和子集,当你构建Maven项目的时候,首先会从本地仓库查找资源,如果没有,那么Maven会从远程仓库下载到你本地仓库.这样在你下次使用的时候就不需要从远程下载了.如果你所需 ...

  5. [Linux]ssh相关问题

    ssh链接不上的最可能原因是防火墙没关,一般提示“connection refused”. 可以使用这个命令查看:#service iptables status 暂时关闭iptables,重启后还会 ...

  6. Redis高级进阶

    目录 本章目标 Redis配置文件 Redis存储 Redis事务 Redis发布订阅 Redis安全 本章目标 Redis配置文件 Redis的存储 Redis的事务 Redis发布订阅 Redis ...

  7. 玩转JavaScript module pattern精髓

    JavaScript module pattern是一种常见的javascript编码模式.这种模式本身很好理解,但是有很多高级用法还没有得到大家的注意.本文,我们将回顾这种设计模式,并且介绍一些高级 ...

  8. poj3349 Snowflake Snow Snowflakes【HASH】

    Snowflake Snow Snowflakes Time Limit: 4000MS   Memory Limit: 65536K Total Submissions: 49991   Accep ...

  9. 使用docx4j编程式地创建复杂的Word(.docx)文档

    原文链接:Create complex Word (.docx) documents programatically with docx4j 原文作者:jos.dirksen 发表日期:2012年2月 ...

  10. using the library to generate a dynamic SELECT or DELETE statement mysqlbaits xml配置文件 与 sql构造器 对比

    https://github.com/mybatis/mybatis-dynamic-sql MyBatis Dynamic SQL     What Is This? This library is ...