我有一个名为 example1.pdf 的 pdf 文件。
我想逐行阅读它。让第一行是你好,我的名字是jhon
。所以我想把它放在一个名为 line
的字符串中。
我正在尝试使用 PDFTextStripper 和 pdfBox,但没有任何方法可以做到这一点。
任何帮助将不胜感激。
最佳答案
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.pdfbox.text.TextPosition;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
/**
* This is an example on how to extract text line by line from pdf document
*/
public class GetLinesFromPDF extends PDFTextStripper {
static List<String> lines = new ArrayList<String>();
public GetLinesFromPDF() throws IOException {
}
/**
* @throws IOException If there is an error parsing the document.
*/
public static void main( String[] args ) throws IOException {
PDDocument document = null;
String fileName = "example1.pdf";
try {
document = PDDocument.load( new File(fileName) );
PDFTextStripper stripper = new GetLinesFromPDF();
stripper.setSortByPosition( true );
stripper.setStartPage( 0 );
stripper.setEndPage( document.getNumberOfPages() );
Writer dummy = new OutputStreamWriter(new ByteArrayOutputStream());
stripper.writeText(document, dummy);
// print lines
for(String line:lines){
System.out.println(line);
}
}
finally {
if( document != null ) {
document.close();
}
}
}
/**
* Override the default functionality of PDFTextStripper.writeString()
*/
@Override
protected void writeString(String str, List<TextPosition> textPositions) throws IOException {
lines.add(str);
// you may process the line here itself, as and when it is obtained
}
}
关于java - 如何逐行阅读pdf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45167592/