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")
相关推荐
VW_4041 小时前
csdn-2026-11-23-第一站踩坑
爬虫·python
yiangL_1 小时前
课后作业4:基于 Python 的古诗词词云可视化(P205)
开发语言·python
Dmz丶1 小时前
前端转 AI 100 天 Day 52:RAG 项目实战(一)——从零搭建企业知识库
python
卷无止境5 小时前
用 SimPy 做离散事件仿真:时钟不走步,事件自己排队
后端·python
撸码猿6 小时前
数据采集场景的语序点选验证码:90.2% 整词准确率的本地 OCR 实践
python·ocr
用户0332126663676 小时前
使用 Python 在 Excel 中创建折线图和条形图
python·excel
木子欢儿7 小时前
Ubuntu 26.04 LTS 安装Python 3.12
linux·运维·服务器·python·ubuntu
Wellijohn8 小时前
Python 异步并发:我把 5 个坑踩完了,你照着抄模板就行
python
AI创界者8 小时前
Python 进阶实战(六十二章):分布式定时任务、异步工作流与幂等补偿机制实战
人工智能·python·aigc
炸薯条!9 小时前
Python面向对象基础:类与对象、实例方法、魔法方法和属性详解
java·开发语言·python