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

问题描述 投票:25回答:5

我想用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没有出现在控制台中。

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

谢谢。

java pdfbox
5个回答
33
投票

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

33
投票

使用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在评论中提到:

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

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

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


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


4
投票

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

1
投票

Maven dep:

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

然后是将pdf文本作为String获取的函数。

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

0
投票

这适用于使用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;
   }
}
© www.soinside.com 2019 - 2024. All rights reserved.