How to count number of pages in a PDF file in Java

Welcome, in this tutorial, we will learn how to count the number of pages of a pdf document with Java using Apache PDFBox.


Prerequisite


Code with Explanation

You have to create an object(or instance) of PDDocument and call the getNumberOfPages() method which returns the total number of pages in the document.

import java.io.File;
import java.io.IOException;
import org.apache.pdfbox.pdmodel.PDDocument;

public class ReadPdfPageExample {

    public static void main(String[] args) {

        PDDocument pdfDoc;
        int pageCount = 0;
        try {
            pdfDoc = PDDocument.load(new File("My_Document.pdf"));
            pageCount = pdfDoc.getNumberOfPages;
        } catch (IOException ex) {
            ex.printStackTrace();
        }

        System.out.println("The total number of pages in the pdf is " + pageCount);

    }
}
Output 
The total number of pages in the pdf is 19

Explanation

  • It is important to import org.apache.pdfbox.pdmodel.PDDocument.
  • In this code, we have to create the reference variable of PDDocument.
  • In the try block, we call PDDocument.load() method with a new File object passing in the name of pdf as a string.
  • Now using the object of PDDocument pdfDoc we call getNumberOfPages() method which returns the Integer value and stores it in the pageCount variable.
  • After the catching exception may throw from the File class.
  • Now display the integer value.

That’s all for a quick review of how to count the number of pages in a PDF file in Java.

Also read: How to generate PDF invoice using Java

Leave a Reply

Your email address will not be published.