DEV Community

IDRSolutions
IDRSolutions

Posted on

How to search a PDF file in Java (Tutorial)

This tutorial shows you how to find words in a PDF file in simple steps using the JPedal Java PDF library. JPedal is the best Java PDF library for developers. It includes a PDF search engine that provides an easy-to-use Java PDF API to find words and phrases in a PDF document.

How to search PDF file in Java

  1. Download JPedal trial jar.
  2. Create a File handle, InputStream or URL pointing to the PDF file
  3. Include a password if file password protected
  4. Open the PDF file
  5. Scan the pages
  6. Close the PDF file

and the Java code to search a PDF…

File file = new File("/path/to/document.pdf"));
FindTextInRectangle extract=new FindTextInRectangle(String.valueOf(file));
//extract.setPassword("password");
if (extract.openPDFFile()) {
    int pageCount = extract.getPageCount();
    for (int page = 1; page <= pageCount; page++) {
        float[] coords = extract.findTextOnPage(page, "textToFind",
                SearchType.MUTLI_LINE_RESULTS ) ;
    }
}
extract.closePDFfile();

Enter fullscreen mode Exit fullscreen mode

Why can’t I just search the PDF file directly?

You cannot simply search inside a PDF file because the text data is stored in a special binary format.

Related tutorials

If you are looking to search PDF files in JPedal, we recommend you start with this tutorials:-

Top comments (0)