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")
相关推荐
佛珠散了一地4 小时前
ONNX Runtime GPU 推理配置指南
python
派葛穆5 小时前
Python-pip切换镜像源
开发语言·python·pip
CTA终结者5 小时前
2026年AI量化提效,工具重点要按阶段调整
人工智能·python
xxie1237945 小时前
Python 闭包:函数嵌套的 “状态捕获” 机制
开发语言·python
c_lb72886 小时前
最新AI量化提效,交易认知和技术实现要接上
人工智能·python
机汇五金_6 小时前
钣金外壳定制厂家助力设备升级
大数据·人工智能·python·物联网
xxie1237946 小时前
Python 闭包的调用方法与实践
开发语言·python
HZZD_HZZD6 小时前
用电行为异常检测VAE-基于PyTorch设计用电行为异常检测模型:从时序特征提取到变分自编码器部署的完整实战
人工智能·pytorch·python
思-无-涯6 小时前
AI Agent技能编写与质量保障
人工智能·python
2601_956319887 小时前
2026年下半年AI量化学习,分清表达开发和验证
人工智能·python