zoukankan      html  css  js  c++  java
  • 使用pdfbox解析中英文pdf文件

     

    package com.dreamers.read;


    import java.io.Writer;
    import java.net.MalformedURLException;
    import java.net.URL;

    import org.pdfbox.pdmodel.PDDocument;
    import org.pdfbox.util.PDFTextStripper;

    public class PdfboxText {
     public static final String DEFAULT_ENCODING = "UTF-8";
     
     // "ISO-8859-1";
     // "ISO-8859-6";
     // "US-ASCII";
     // "UTF-8";
     // "UTF-16";
     // "UTF-16BE";
     // "UTF-16LE";
     public String geText(String file) throws Exception {
      // 是否排序
      boolean sort = false;
      //ArrayList<String> list = new ArrayList<String>();
      // pdf文件名
      String pdfFile = file;
      // 输入文本文件名称
     
      // 编码方式
      
      // 开始提取页
      int startPage = 1;
      // 结束提取页数
      int endPage = Integer.MAX_VALUE;
      // 文件输入流,生成文本文件
      Writer output = null;
      // 内存中存储的PDF Document
      PDDocument document = null;
      try {
       try {
        // 首先当作一个URL来装载文件,如果得到异常再从本地文件系统//去装载文件
        URL url = new URL(pdfFile);
        document = PDDocument.load(url);
        // 获取PDF的文件名
        
        
        
       } catch (MalformedURLException e) {
        // 如果作为URL装载得到异常则从文件系统装载
        document = PDDocument.load(pdfFile);
       
       }
       // 文件输入流,写入文件倒textFile
      
       // PDFTextStripper来提取文本
       PDFTextStripper stripper = null;
       stripper = new PDFTextStripper();
       // 设置是否排序
       stripper.setSortByPosition(sort);
       // 设置起始页
       stripper.setStartPage(startPage);
       // 设置结束页
       stripper.setEndPage(endPage);
      // list.add(stripper.getText(document));
       String text = stripper.getText(document);
       // 调用PDFTextStripper的writeText提取并输出文本
       return text;
      } finally {
       if (output != null) {
        // 关闭输出流
        output.close();
       }
       if (document != null) {
        // 关闭PDF Document
        document.close();
       }
      }
     }

     public static void main(String[] args) {
      PdfboxText test = new PdfboxText();
      try {
       
       //ArrayList<String> list = new ArrayList<String>();
      
       System.out.println(test.geText("E:\\java\\PdfText\\Dom4j解析XML.pdf"));
      } catch (Exception e) {
       e.printStackTrace();
      }
     }

    }
    刚开始用的版本低不能解析中文文件,新版本支持中文,减少了不少功夫。

  • 相关阅读:
    大数据揭秘华尔街如何从金融危机中赚钱
    大数据揭秘华尔街如何从金融危机中赚钱
    CDA考试 ▏2017 CDA L1备考资源习题详解-统计基础部分
    CDA考试 ▏2017 CDA L1备考资源习题详解-统计基础部分
    同步大数据发展与大数据法制,方能形成一个良性循环
    同步大数据发展与大数据法制,方能形成一个良性循环
    Solr在Linux中的安装
    NOSQL中的redis缓存数据库
    Context initialization failed
    Caused by: java.sql.SQLException: Field 'category_id' doesn't have a default value
  • 原文地址:https://www.cnblogs.com/lcqBlogs/p/2392396.html
Copyright © 2011-2022 走看看