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")
相关推荐
databook4 小时前
Manim实现脉冲闪烁特效
后端·python·动效
程序设计实验室5 小时前
2025年了,在 Django 之外,Python Web 框架还能怎么选?
python
倔强青铜三6 小时前
苦练Python第46天:文件写入与上下文管理器
人工智能·python·面试
用户2519162427119 小时前
Python之语言特点
python
刘立军10 小时前
使用pyHugeGraph查询HugeGraph图数据
python·graphql
数据智能老司机13 小时前
精通 Python 设计模式——创建型设计模式
python·设计模式·架构
数据智能老司机14 小时前
精通 Python 设计模式——SOLID 原则
python·设计模式·架构
c8i16 小时前
django中的FBV 和 CBV
python·django
c8i16 小时前
python中的闭包和装饰器
python
这里有鱼汤19 小时前
小白必看:QMT里的miniQMT入门教程
后端·python