Java 如何使用 Apache PDFBox 从 PDF 文件中提取文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23813727/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 01:22:04  来源:igfitidea点击:

How to extract text from a PDF file with Apache PDFBox

javapdfbox

提问by Benben

I would like to extract text from a given PDF file with Apache PDFBox.

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

I wrote this code:

我写了这段代码:

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

However, I got the following error:

但是,我收到以下错误:

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

I added pdfbox-1.8.5.jar and fontbox-1.8.5.jar to the class path.

我将 pdfbox-1.8.5.jar 和 fontbox-1.8.5.jar 添加到类路径中。

Edit

编辑

I added System.out.println("program starts");to the beginning of the program.

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

I ran it, then I got the same error as mentioned above and program startsdid not appear in the console.

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

Thus, I think I have a problem with the class path or something.

因此,我认为我的类路径有问题。

Thank you.

谢谢你。

采纳答案by Emad

I executed your code and it worked properly. Maybe your problem is related to FilePaththat you have given to file. I put my pdf in C drive and hard coded the file path. Here is my code:

我执行了你的代码,它运行正常。也许您的问题与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);
        }
    }
}

回答by Matthias Braun

Using PDFBox2.0.7, this is how I get the text of a PDF:

使用PDFBox2.0.7,这就是我获取 PDF 文本的方式:

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

Call it like this:

像这样调用它:

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


Since user oivemaria asked in the comments:

由于用户 oivemaria 在评论中询问:

You can use PDFBox in your application by adding it to your dependencies in build.gradle:

您可以在您的应用程序中使用 PDFBox,方法是将其添加到您的依赖项中build.gradle

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

Here's moreon dependency management using Gradle.

这里有更多关于使用 Gradle 进行依赖管理的信息。



If you want to keep the PDF's format in the parsed text, give PDFLayoutTextStrippera try.

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

回答by sonus21

PdfBox2.0.3 has a command line tool as well.

PdfBox2.0.3 也有一个命令行工具。

  1. Download jar file
  2. java -jar pdfbox-app-2.0.3.jar ExtractText [OPTIONS] <inputfile> [output-text-file]
  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
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

回答by Sunil K Chaudhary

This works fine to extract data from a PDF file that has text content using pdfbox 2.0.6

这适用于使用 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;
   }
}

回答by Süniúr

Maven dep:

Maven 部门:

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

Then the fucntion to get the pdf text as String.

然后功能将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;
}