Get the Number of Pages in a PDF File Using Java

Andrew Wilson
1 min readJul 5, 2021

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.

<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>http://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.pdf.free</artifactId>
<version>4.3.0</version>
</dependency>
</dependencies>

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
doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\test.pdf");

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

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

Result:

--

--

Andrew Wilson

Explore C#, Java and Python solutions for processing Word/Excel/PowerPoint/PDF files.