Python: Count the Number of Pages in a PDF File

2023-11-29 01:02:37 Written by  support iceblue
Rate this item
(0 votes)

To get the number of pages in a PDF file, you can open the file in a PDF viewer such as Adobe, which has a built-in page count feature. However, when there is a batch of PDF files, opening each file to check how many pages it contains is a time-consuming task. In this article, you will learn how to quicky count the number of pages in a PDF file through programming using Spire.PDF for Python.

Install Spire.PDF for Python

This scenario requires Spire.PDF for Python and plum-dispatch v1.7.4. They can be easily installed in your Windows through the following pip command.

pip install Spire.PDF

If you are unsure how to install, please refer to this tutorial: How to Install Spire.PDF for Python on Windows

Count the Number of Pages in a PDF File in Python

Spire.PDF for Python offers the PdfDocument.Pages.Count property to quickly count the number of pages in a PDF file without opening it. The following are the detailed steps.

  • Create a PdfDocument object.
  • Load a sample PDF document using PdfDocument.LoadFromFile() method.
  • Count the number of pages in the PDF document using PdfDocument.Pages.Count property.
  • Write the result to a TXT file or print it out directly.
  • Python
from spire.pdf.common import *
from spire.pdf import *

def AppendText(fname: str, text: str):
    fp = open(fname, "w")
    fp.write(text + "\n")
    fp.close()

# Specify the input and output files
inputFile = "contract.pdf"
outputFile = "GetNumberOfPages.txt"

# Create a PdfDocument object
pdf = PdfDocument()

# Load a PDF document from disk
pdf.LoadFromFile(inputFile)

# Count the number of pages in the document
count = pdf.Pages.Count
# Print the result
print("Total Pages:", count)

# Write the result to a TXT file
AppendText(
    outputFile, "The number of pages in the pdf document is: " + str(count))
pdf.Close()

Python: Count the Number of Pages in a PDF File

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Additional Info

  • tutorial_title:
Last modified on Thursday, 25 April 2024 02:23