java - 如何逐行阅读pdf

标签 java pdf pdfbox

我有一个名为 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
    }
}

引用 - extract text line by line from pdf

关于java - 如何逐行阅读pdf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45167592/

相关文章:

java - getEntityManager.persist(object) 之后如何提交和回滚数据

pdf - 如何在PDF中加粗文本?

macos - 如何使用命令行将 PDF 中的一系列页面提取到单个文件中?

java - pdfbox 标题版本信息错误

java - 使用 PDFBox 并使用 Maven 构建时出现 NoClassDefFoundError

java - 打印多维数组时出现问题

java - 如何在Java中捕获外部jar的异常

java - 配置 Manuel 容器 IntelliJ Arquillian Wildfly

php - 将 php 输出保存为 PDF

php - 我尝试过application/pdf...如何上传pdf?