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")
相关推荐
会Tk矩阵群控的小木31 分钟前
基于Python的iMessage短信群发与社媒多账号统一管理系统实现
开发语言·windows·python·新媒体运营·开源软件·个人开发
质造者1 小时前
LangChain + Ollama + Tavily 实现旅游问答系统
linux·人工智能·python·langchain·rag
伊布拉西莫1 小时前
【流畅的Python】第20章:并发执行器 — 学习笔记
笔记·python·学习
IT策士1 小时前
Redis 从入门到精通:Python 操作 Redis
redis·python·bootstrap
编码者卢布1 小时前
【Azure AI Search】 searchMode=any 和 searchMode=all 有什么区别?
人工智能·python·flask
Samooyou1 小时前
大模型微调(Fine Tuning)
人工智能·python·ai·语言模型
qq_8573058192 小时前
python语法
开发语言·python·算法
AI行业学习2 小时前
CC-Switch v3.16.1 官方下载 | 安装配置详细教程【2026.6.10】
java·开发语言·vue.js·python·mysql·eclipse·html
早起CaiCai2 小时前
【Pytorch 实践1】手写数字
人工智能·pytorch·python
吴梓穆2 小时前
Python 语法基础 函数
开发语言·python