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")
相关推荐
专注仿真12 分钟前
智能体训练之模仿学习:GAIL 算法详解与实战
python·算法·仿真·多智能体强化学习·afsim智能体训练
databook1 小时前
处理一批 PDF,怎么算真的处理完了
后端·python
承渊政道3 小时前
【Python编程快速上手—让繁琐工作自动化】(列表:把数据排成队,从下标取值到深拷贝)
开发语言·python·pycharm·自动化·列表
大胖爱学习_MJ3 小时前
Agent 如何安全地拿数据库密码?基于 HashiCorp Vault 的动态凭证下发
经验分享·python
tryCbest4 小时前
Python 爬虫从入门到实战(一):基础篇——从零写出第一个爬虫
开发语言·爬虫·python
无小道4 小时前
Python语句的特色
python·语句
2601_967980115 小时前
python pytest如何编写测试
python·测试用例·pytest·函数·assert
2601_967980116 小时前
Python中heapq模块的各种用法实例
数据结构·python·算法·应用实例·heapq模块
大胖爱学习_MJ6 小时前
超越向量检索:用 Spring Boot + Neo4j 手搓 GraphRAG 知识图谱记忆
java·后端·python
RobinDevNotes6 小时前
24GB Mac 做数字人:声音放本地,画面租云端
人工智能·python·macos·开发工具