You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python的PyPDF2库统计PDF页数?含弃用方法替代方案

使用PyPDF2统计PDF总页数(替代已弃用的numPages方法)

在PyPDF2 2.0及以上版本中,原有的numPages属性已被正式弃用,官方推荐使用len(reader.pages)来获取PDF总页数——因为pages是一个包含所有页面对象的可迭代序列,其长度就是总页数。

完整实现代码

from PyPDF2 import PdfReader
import os

def get_pdf_page_count(pdf_path):
    # 检查文件是否存在
    if not os.path.exists(pdf_path):
        raise FileNotFoundError(f"文件不存在: {pdf_path}")
    
    # 读取PDF文件
    with open(pdf_path, 'rb') as file:
        reader = PdfReader(file)
        # 获取总页数
        page_count = len(reader.pages)
        return page_count

# 示例用法
if __name__ == "__main__":
    try:
        pdf_file = "example.pdf"  # 替换为你的PDF文件路径
        count = get_pdf_page_count(pdf_file)
        print(f"该PDF文件总页数为: {count}")
    except Exception as e:
        print(f"处理出错: {str(e)}")

关键说明

  • PdfReader是PyPDF2新版本的核心读取类(替代旧版的PdfFileReader)
  • reader.pages返回包含所有PageObject的序列,直接用len()即可得到总页数
  • 代码包含基础异常处理,避免因文件不存在、损坏或权限问题导致崩溃

版本要求

确保PyPDF2版本在2.0以上,若版本过低可执行升级命令:

pip install PyPDF2 --upgrade

内容的提问来源于stack exchange,提问作者Mounesh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 10:10:26