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")
相关推荐
JOJO数据科学1 小时前
JupyterLab Electron 鸿蒙 PC 适配全记录:从 Python 原生崩溃到 node-static 本地工作台
python·electron·harmonyos
xufengzhu1 小时前
第三方 Python 库 redis-py + hiredis 的使用
开发语言·redis·python
llxxyy卢1 小时前
polar夏季赛部分题目
开发语言·python
闵孚龙2 小时前
PyTorch 系列 之 nn.Module:所有模型的骨架
人工智能·pytorch·python
AI玫瑰助手2 小时前
Python模块:from...import...导入指定内容
开发语言·python·信息可视化
小森林之主2 小时前
Python re 模块速查:从实战对比中掌握正则表达式
python·正则表达式·性能测试·re模块·编程实战
郭wes代码2 小时前
Win10 拒绝访问、长期关机自动维护与声音图标灰色故障解决记录
windows·python·开源
伊布拉西莫2 小时前
LangChain LCEL源码深度剖析
python·langchain
用心_承载未来2 小时前
从“复制链接→打开APP“到“一键解析“:我做了个短视频去水印工具
python·去水印·短视频去水印
TYUT_xiaoming2 小时前
yolo模型训练
人工智能·python·yolo