Как извлечь текст из файла PDF с помощью Apache PDFBox
Я хотел бы извлечь текст из данного файла PDF с Apache PDFBox.
Я написал этот код:
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
не появился в консоли.
Таким образом, я думаю, что у меня есть проблема с путем класса или чем-то.
Спасибо.
Ответы
Ответ 1
Я выполнил ваш код, и он работал правильно. Возможно, ваша проблема связана с 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);
}
}
}
Ответ 2
Используя 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'
}
Подробнее об управлении зависимостями с помощью Gradle.
Если вы хотите сохранить формат PDF в разобранном тексте, попробуйте PDFLayoutTextStripper.
Ответ 3
PdfBox 2.0.3 также имеет инструмент командной строки.
- Загрузить файл jar
-
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 dep:
<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
Это отлично работает, чтобы извлечь данные из PDF файла с текстовым контентом, используя pdfbox 2.0.6
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;
}
}