PDF文件转换之输出指定页到新的 PDF 文件

背景

一份 PDF 学习资料需要打印其中某几页,文件有几百兆,看到 WPS 有PDF拆分功能,但是需要会员,开了一个月会员后完成了转换。突然想到,会员到期后如果还要拆解的话,怎么办呢?PDF 文件拆解功能,自己写一个呗。

输入需求

Python 实现对 PDF从截取某几页的功能

根据输出的方案,拷贝代码到 PyCharm 编辑器:

bash 复制代码
from PyPDF2 import PdfFileWriter, PdfFileReader

def extract_pages(input_pdf_path, output_pdf_path, start_page, end_page):
    """
    从PDF文件中截取指定页码范围的页面,并保存为新的PDF文件。
    
    :param input_pdf_path: 输入PDF文件路径
    :param output_pdf_path: 输出PDF文件路径
    :param start_page: 开始页码(从0开始)
    :param end_page: 结束页码(不包含该页)
    """
    # 创建PdfFileWriter对象
    output = PdfFileWriter()
    
    # 打开输入PDF文件
    with open(input_pdf_path, "rb") as input_pdf_file:
        pdf_file = PdfFileReader(input_pdf_file)
        pdf_pages_len = pdf_file.getNumPages()
        
        # 检查页码范围是否有效
        if start_page < 0 or end_page > pdf_pages_len or start_page >= end_page:
            raise ValueError("无效的页码范围")
        
        # 添加指定页码范围的页面到输出文件
        for i in range(start_page, end_page):
            output.addPage(pdf_file.getPage(i))
        
        # 保存输出文件
        with open(output_pdf_path, "wb") as output_pdf_file:
            output.write(output_pdf_file)

# 示例调用
input_pdf_path = "input.pdf"
output_pdf_path = "output.pdf"
start_page = 0  # 从第一页开始(页码从0开始)
end_page = 5    # 截止到第5页(不包含第5页)

extract_pages(input_pdf_path, output_pdf_path, start_page, end_page)

依赖安装及运行

第一步,执行命令pip install PyPDF2 完成依赖的安装。

第二步,修改 input_pdf_path 、output_pdf_path 及页码信息。

第三步,执行脚本,有报错:

  1. PdfFileWriter is deprecated and was removed in PyPDF2 3.0.0. Use PdfWriter instead.
  2. PdfFileReader is deprecated and was removed in PyPDF2 3.0.0. Use PdfReader instead.
  3. reader.getNumPages is deprecated and was removed in PyPDF2 3.0.0. Use len(reader.pages) instead.
  4. reader.getPage(pageNumber) is deprecated and was removed in PyPDF2 3.0.0. Use reader.pages[page_number] instead.
  5. addPage is deprecated and was removed in PyPDF2 3.0.0. Use add_page instead.

按照提示,修改废弃方法为最新方法后的代码如下:

bash 复制代码
from PyPDF2 import PdfWriter, PdfReader


def extract_pages(input_pdf_path, output_pdf_path, start_page, end_page):
    """
    从PDF文件中截取指定页码范围的页面,并保存为新的PDF文件。

    :param input_pdf_path: 输入PDF文件路径
    :param output_pdf_path: 输出PDF文件路径
    :param start_page: 开始页码(从0开始)
    :param end_page: 结束页码(不包含该页)
    """
    # 创建PdfWriter对象
    output = PdfWriter()

    # 打开输入PDF文件
    with open(input_pdf_path, "rb") as input_pdf_file:
        pdf_file = PdfReader(input_pdf_file)
        pdf_pages_len = len(pdf_file.pages)

        # 检查页码范围是否有效
        if start_page < 0 or end_page > pdf_pages_len or start_page >= end_page:
            raise ValueError("无效的页码范围")

        # 添加指定页码范围的页面到输出文件
        for i in range(start_page, end_page):
            output.add_page(pdf_file.pages[i])

        # 保存输出文件
        with open(output_pdf_path, "wb") as output_pdf_file:
            output.write(output_pdf_file)


# 示例调用
input_pdf_path = "/Applications/2022MyTextFiles/A.pdf"
output_pdf_path = "/Applications/2022MyTextFiles/B.pdf"
start_page = 0  # 从第一页开始(页码从0开始)
end_page = 5  # 截止到第5页(不包含第5页)

extract_pages(input_pdf_path, output_pdf_path, start_page, end_page)

运行正常,搞定了!

白开了一个月的会员啊!

相关推荐
zone77391 小时前
001:简单 RAG 入门
后端·python·面试
F_Quant2 小时前
🚀 Python打包踩坑指南:彻底解决 Nuitka --onefile 配置文件丢失与重启报错问题
python·操作系统
允许部分打工人先富起来3 小时前
在node项目中执行python脚本
前端·python·node.js
IVEN_3 小时前
Python OpenCV: RGB三色识别的最佳工程实践
python·opencv
haosend3 小时前
AI时代,传统网络运维人员的转型指南
python·数据网络·网络自动化
曲幽4 小时前
不止于JWT:用FastAPI的Depends实现细粒度权限控制
python·fastapi·web·jwt·rbac·permission·depends·abac
IVEN_21 小时前
只会Python皮毛?深入理解这几点,轻松进阶全栈开发
python·全栈
Ray Liang1 天前
用六边形架构与整洁架构对比是伪命题?
java·python·c#·架构设计
AI攻城狮1 天前
如何给 AI Agent 做"断舍离":OpenClaw Session 自动清理实践
python
千寻girling1 天前
一份不可多得的 《 Python 》语言教程
人工智能·后端·python