PyPDF3 拆分PDF

拆分所有页

python 复制代码
from PyPDF3 import PdfFileWriter, PdfFileReader
path = "C://Users//Administrator//Desktop//拆分//"
input_pdf = PdfFileReader(path+"example.pdf")  # PdfFileReader读取原始文件
output = PdfFileWriter()  
# 获取PDF页数
num_pages = input_pdf.getNumPages()

for page_num in range(num_pages):
    output = PdfFileWriter()
    # PdfFileWriter().addPage()将PDF页面添加到新的PDF中并保存
    output.addPage(input_pdf.getPage(page_num))

    with open("{}page_{}.pdf".format(path,page_num + 1), 'wb') as output_pdf:
        output.write(output_pdf)

拆分指定页

python 复制代码
from PyPDF3 import PdfFileReader, PdfFileWriter


def split_pdf(input_pdf_path, output_prefix, start_page, end_page):
    # 读取PDF
    reader = PdfFileReader(input_pdf_path)

    # 循环从start_page到end_page,每页创建新的PDF
    for page_number in range(start_page, end_page + 1):
        output = PdfFileWriter()
        # 将特定页面添加到输出PDF
        output.addPage(reader.pages[page_number - 1])
        # 写入PDF到文件
        with open(f"{output_prefix}-page_{page_number}.pdf", "wb") as output_pdf:
            output.write(output_pdf)


# 使用split_pdf函数拆分PDF
# 文件名,输出名,起始页,结束页
split_pdf("example.pdf", "output", 1, 3)  # 拆分从第1页到第3页的PDF

多文件合并PDF

python 复制代码
import os
from PyPDF3 import PdfFileMerger
path = "C://Users//Administrator//Desktop//拆分//新建文件夹//"
pdf_lst = [f for f in os.listdir(path) if f.endswith('.pdf')]
pdf_lst = [os.path.join(path, filename) for filename in pdf_lst]

file_merger = PdfFileMerger()
for pdf in pdf_lst:
    file_merger.append(pdf)
file_merger.write(path + "合并文件.pdf")
相关推荐
复园电子1 小时前
跨平台PDF签名解析器设计:多方签署与自签名证书(野鸡CA)过滤
pdf·电子合同
LadenKiller2 小时前
最新量化软件选择,先按能力判断表达生成和执行
人工智能·python
iuu_star2 小时前
Python大模型智能学习平台——设计与实现(AI教学系统)
大数据·人工智能·python·学习
天才测试猿2 小时前
如何封装自动化测试框架?
自动化测试·软件测试·python·selenium·测试工具·职场和发展·测试用例
overmind2 小时前
oeasy Python 102 集合_运算_交集_并集_差集_对称差集
开发语言·python
爱吃提升3 小时前
Python自动驾驶图像识别完整实战教程(OpenCV+YOLOv8,附可直接运行源码)
python·opencv·自动驾驶
statistican_ABin3 小时前
2026 FIFA 世界杯比赛与球队数据探索性分析
人工智能·python·数据挖掘·数据分析
qetfw3 小时前
yt-dlp:下载公开视频、字幕、封面和音频的实用命令
python·音视频·开源项目·效率工具
QH_ShareHub3 小时前
GPU 完整运行过程:驱动、CUDA Toolkit、Conda、Python PyTorch 与 R torch
pytorch·python·conda
AbsoluteLogic3 小时前
Python——必学内置模块 Sys
python