【问题标题】:How to extract text from a PDF file with Apache PDFBox如何使用 Apache PDFBox 从 PDF 文件中提取文本
【发布时间】:2014-07-11 21:33:36
【问题描述】:

我想使用 Apache PDFBox 从给定的 PDF 文件中提取文本。

我写了这段代码:

PDFTextStripper pdfStripper = null;
PDDocument pdDoc = null;
COSDocument cosDoc = null;
File file = new File(filepath);

PDFParser parser = new PDFParser(new FileInputStream(file));
parser.parse();
cosDoc = parser.getDocument();
pdfStripper = new PDFTextStripper();
pdDoc = new PDDocument(cosDoc);
pdfStripper.setStartPage(1);
pdfStripper.setEndPage(5);
String parsedText = pdfStripper.getText(pdDoc);
System.out.println(parsedText);

但是,我收到以下错误:

Exception in thread "main" java.lang.NullPointerException
at org.apache.fontbox.afm.AFMParser.main(AFMParser.java:304)

我在类路径中添加了 pdfbox-1.8.5.jar 和 fontbox-1.8.5.jar。

编辑

我在程序的开头添加了System.out.println("program starts");

我运行了它,然后我得到了与上面提到的相同的错误,并且program starts 没有出现在控制台中。

因此,我认为我的类路径或其他东西有问题。

谢谢。

【问题讨论】:

  • 可能您的 PDF 文件不完全有效,导致 PDFBox 出错。您可能需要提供 PDF 以供检查。
  • 您确定您启动了正确的main() 方法吗?异常看起来像是您启动了 org.apache.fontbox.afm.AFMParsermain(),它看起来像 PDFBox 代码,而不是您的代码。
  • 你是对的。我重置了运行配置,现在程序可以工作了。非常感谢你,mkl。

标签: java pdfbox


【解决方案1】:

使用PDFBox 2.0.7,这就是我获取 PDF 文本的方式:

static String getText(File pdfFile) throws IOException {
    PDDocument doc = PDDocument.load(pdfFile);
    return new PDFTextStripper().getText(doc);
}

这样称呼它:

try {
    String text = getText(new File("/home/me/test.pdf"));
    System.out.println("Text in PDF: " + text);
} catch (IOException e) {
    e.printStackTrace();
}

自从用户 oivemaria 在 cmets 中询问:

您可以通过将 PDFBox 添加到 build.gradle 中的依赖项来在应用程序中使用 PDFBox:

dependencies {
  compile group: 'org.apache.pdfbox', name: 'pdfbox', version: '2.0.7'
}

Here's more 关于使用 Gradle 进行依赖管理。


如果您想在解析后的文本中保留 PDF 的格式,请尝试PDFLayoutTextStripper

【讨论】:

  • 这比接受的答案要好。我使用相同的方法获取资源作为 InputStream 从src\resources 文件夹加载文件。您还可以使用来自 m2repo mvnrepository.com/artifact/org.apache.pdfbox/pdfbox 的 maven 依赖项
  • PPDocument使用后需要关闭。
【解决方案2】:

我执行了您的代码,并且运行正常。也许您的问题与您提交给文件的FilePath 有关。我将我的 pdf 文件放入 C 驱动器并硬编码文件路径。这是我的代码:

// PDFBox 2.0.8 require org.apache.pdfbox.io.RandomAccessRead
// import org.apache.pdfbox.io.RandomAccessFile;

public class PDFReader{
    public static void main(String args[]) throws IOException {
        PDFTextStripper pdfStripper = null;
        PDDocument pdDoc = null;
        File file = new File("C:/my.pdf");
        PDFParser parser = new PDFParser(new FileInputStream(file));
        parser.parse();
        try (COSDocument cosDoc = parser.getDocument()) {
            pdfStripper = new PDFTextStripper();
            pdDoc = new PDDocument(cosDoc);
            pdfStripper.setStartPage(1);
            pdfStripper.setEndPage(5);
            String parsedText = pdfStripper.getText(pdDoc);
            System.out.println(parsedText);
        }
    }
}

【讨论】:

  • 当我们从计算机获取 pdf 文件时它工作正常,但我试图从 android 的 SD 卡中获取它,然后它给出错误,如“java.lang.ClassNotFoundException:找不到类”java .awt.print.Printable" 在路径上:DexPathList[[zip file "/data/app/com.geeklabs.pdfreader-1/base.apk"],nativeLibraryDirectories=[/vendor/lib, /system/lib]]"
  • 即使添加库来构建路径,也会得到“java.lang.NoClassDefFoundError: org.pdfbox.pdmodel.PDDocument”
  • PDFbox是如何使用的?我是这个概念的新手,但不知道从哪里开始。我已经下载了jar文件,但是双击它不起作用。
  • 使用 pdfbox 2.0.5 此代码无法编译并出现错误:java.io.FileInputStream cannot be cast to org.apache.pdfbox.io.RandomAccessRead
  • 构造函数 PDFParser(FileInputStream) 未定义转换为 org.apache.pdfbox.io.RandomAccessRead 给定错误
【解决方案3】:

PdfBox 2.0.3 也有命令行工具。

  1. 下载jar文件
  2. java -jar pdfbox-app-2.0.3.jar ExtractText [OPTIONS] <inputfile> [output-text-file]
Options:
  -password  <password>        : Password to decrypt document
  -encoding  <output encoding> : UTF-8 (default) or ISO-8859-1, UTF-16BE, UTF-16LE, etc.
  -console                     : Send text to console instead of file
  -html                        : Output in HTML format instead of raw text
  -sort                        : Sort the text before writing
  -ignoreBeads                 : Disables the separation by beads
  -debug                       : Enables debug output about the time consumption of every stage
  -startPage <number>          : The first page to start extraction(1 based)
  -endPage <number>            : The last page to extract(inclusive)
  <inputfile>                  : The PDF document to use
  [output-text-file]           : The file to write the text to

【讨论】:

    【解决方案4】:

    Maven 部门:

        <dependency>
            <groupId>org.apache.pdfbox</groupId>
            <artifactId>pdfbox</artifactId>
            <version>2.0.9</version>
        </dependency>
    

    然后是获取pdf文本为字符串的功能。

    private static String readPDF(File pdf) throws InvalidPasswordException, IOException {
        try (PDDocument document = PDDocument.load(pdf)) {
    
            document.getClass();
    
            if (!document.isEncrypted()) {
    
                PDFTextStripperByArea stripper = new PDFTextStripperByArea();
                stripper.setSortByPosition(true);
    
                PDFTextStripper tStripper = new PDFTextStripper();
    
                String pdfFileInText = tStripper.getText(document);
                // System.out.println("Text:" + st);
    
                // split by whitespace
                String lines[] = pdfFileInText.split("\\r?\\n");
                List<String> pdfLines = new ArrayList<>();
                StringBuilder sb = new StringBuilder();
                for (String line : lines) {
                    System.out.println(line);
                    pdfLines.add(line);
                    sb.append(line + "\n");
                }
                return sb.toString();
            }
    
        }
        return null;
    }
    

    【讨论】:

      【解决方案5】:

      这适用于使用 pdfbox 2.0.6 从包含文本内容的 PDF 文件中提取数据

      import java.io.File;
      import java.io.IOException;
      import org.apache.pdfbox.pdmodel.PDDocument;
      import org.apache.pdfbox.text.PDFTextStripper;
      import org.apache.pdfbox.text.PDFTextStripperByArea;
      
      public class PDFTextExtractor {
         public static void main(String[] args) throws IOException {
             System.out.println(readParaFromPDF("C:\\sample1.pdf",3, "Enter Start Text Here", "Enter Ending Text Here"));
          //Enter FilePath, Page Number, StartsWith, EndsWith
         }
         public static String readParaFromPDF(String pdfPath, int pageNo, String strStartIndentifier, String strEndIdentifier) {
             String returnString = "";
             try {
                 PDDocument document = PDDocument.load(new File(pdfPath));
                 document.getClass();        
                 if (!document.isEncrypted()) {
                     PDFTextStripperByArea stripper = new PDFTextStripperByArea();
                     stripper.setSortByPosition(true);
                     PDFTextStripper tStripper = new PDFTextStripper();
                     tStripper.setStartPage(pageNo);
                     tStripper.setEndPage(pageNo);
                     String pdfFileInText = tStripper.getText(document);
                     String strStart = strStartIndentifier;
                     String strEnd = strEndIdentifier;
                     int startInddex = pdfFileInText.indexOf(strStart);
                     int endInddex = pdfFileInText.indexOf(strEnd);
                     returnString = pdfFileInText.substring(startInddex, endInddex) + strEnd;
                 }
                } catch (Exception e) {
                    returnString = "No ParaGraph Found";
             }
                  return returnString;
         }
      }
      

      【讨论】:

        猜你喜欢
        • 2012-12-30
        • 2021-01-05
        • 2015-11-19
        • 2013-11-15
        • 1970-01-01
        • 1970-01-01
        • 2013-03-22
        • 2018-01-06
        • 2016-12-06
        相关资源
        最近更新 更多