Get the Number of Pages in a PDF File Using Java

This article will share how to use a free library named Free Spire.PDF for Java to get the number of pages in a PDF file without opening it.

Import jar dependency (2 Methods)
● Download the free library and unzip it. Then add the Spire.Pdf.jar file to your project as dependency.

● Directly add the jar dependency to maven project by adding the following configurations to the pom.xml.


A screenshot of the input PDF file which contains 53 pages:

Sample Code:

import com.spire.pdf.PdfDocument;

public class CountPagesOfPDF {

public static void main(String[] args) {

//Instantiate a PdfDocument object
PdfDocument doc=new PdfDocument();
//Load the PDF file

//Get the number of pages in the PDF file
int pageCount = doc.getPages().getCount();

System.out.print("This PDF file contains "+pageCount+" pages");