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

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; 
            
          
    }

}


 

 

 

 

 

 

 

  • 6
    点赞
  • 39
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值