PDFBox extracting paragraphs

public static void main(String[] args) throws InvalidPasswordException, IOException {
    File file = new File("File Path");
    PDDocument document = PDDocument.load(file);        
    PDFTextStripper pdfStripper = new PDFTextStripper();
    pdfStripper.setParagraphStart("/t");
    pdfStripper.setSortByPosition(true);


    for (String line: pdfStripper.getText(document).split(pdfStripper.getParagraphStart()))
            {
                System.out.println(line);
                System.out.println("********************************************************************");
            }
}

Guys please try the above code. This works for sure with PDFBox-2.0.8 Jar


Text in PDF documents is absolutely positioned. So instead of words, lines and paragraphs, one only has absolutely positioned characters.

Let's say you have a paragraph:

Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit

Roughly speaking, in the PDF file it will be represented as characters N at some position, e a bit right to it, q, u, e more to the right, etc.

PDFBox tries to guess how the characters make words, lines and paragraphs. So it will look for a lot of characters at approximately same vertical position, for groups of characters that are near to each other and similar to try and find what you need. It does that by extracting the text from the entire page and then processing it character by character to create text (it can also try and extract text from just one rectangular area inside a page). See the appropriate class PDFTextStripper (or PDFTextStripperByArea). For usage, see ExtractText.java in PDFBox sources.

That means that you cannot extract paragraphs easily using PDFBox. It also means that PDFBox can and sometimes will miss when extracting text (there are a lot of very different PDF documents out there).

What you can do is extract text from the entire page and then try and find your paragraph searching through that text. Regular expressions are usually well suited for such tasks (available in Java either through Pattern and Matcher classes, or convenience methods on String class).

Tags:

Pdfbox