Java - 使用 OCR 从 PDF 中提取文本

Dax*_*min 4 java pdf text-extraction pdfbox pdftextstream

我有一个 pdf 文件(下面给出了其中的一部分),并且想从中提取文本。我使用过 PDFTextStream,但它不适用于此文件。(但是它可以与其他具有简单文本的文件一起使用)。

还有哪些其他 OCR 库能够做到这一点?

请帮忙。谢谢。

pdf 文件一览

pdf 文件预览

Dax*_*min 5

我尝试使用 PDFBox,结果令人满意。

以下是使用 PDFBox 从 PDF 中提取文本的代码:

import java.io.*;

import org.apache.pdfbox.pdmodel.*;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.pdfbox.util.*;

public class PDFTest {

 public static void main(String[] args){
 PDDocument pd;
 BufferedWriter wr;
 try {
         File input = new File("C:/BillOCR/data/bill.pdf");  // The PDF file from where you would like to extract
         File output = new File("D:/SampleText.txt"); // The text file where you are going to store the extracted data
         pd = PDDocument.load(input);
         System.out.println(pd.getNumberOfPages());
         System.out.println(pd.isEncrypted());
         pd.save("CopyOfBill.pdf"); // Creates a copy called "CopyOfInvoice.pdf"
         PDFTextStripper stripper = new PDFTextStripper();
         stripper.setStartPage(1); //Start extracting from page 3
         stripper.setEndPage(1); //Extract till page 5
         wr = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(output)));
         stripper.writeText(pd, wr);
         if (pd != null) {
             pd.close();
         }
        // I use close() to flush the stream.
        wr.close();
 } catch (Exception e){
         e.printStackTrace();
        }
     }
}
Run Code Online (Sandbox Code Playgroud)

  • 所以你根本不需要 OCR。 (9认同)
  • 如果您有格式良好的 pdf,这将起作用。如果某些拍照并另存为 pdf 则不会给出结果。为此你需要 OCR (5认同)