如何逐行阅读pdf

时间:2017-07-18 13:01:28

标签: java pdf pdfbox

我有一个名为" example1.pdf"的pdf。我想逐行阅读。第一行是#34;你好我的名字是jhon"。所以我想在一个名为line的String中。 我正在尝试使用pdfTextStripper和pdfBox,但没有任何方法来做到这一点。 任何帮助都将得到满足

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

这种方法要容易得多。

public static void main(String[] args) throws Exception, IOException 
{
    File file = new File("File.pdf"); 
    PDDocument document = PDDocument.load(file);
    PDFTextStripper pdfStripper = new PDFTextStripper();
    pdfStripper.setStartPage(1);
    pdfStripper.setEndPage(1);

    //load all lines into a string
    String pages = pdfStripper.getText(document);

    //split by detecting newline
    String[] lines = pages.split("\r\n|\r|\n");

    int count=1;   //Just to indicate line number
    for(String temp:lines)
    {
        System.out.println(count+" "+temp);
        count++;
    }
}