python实现pdf的页面替换

利用第三方库PyPDF2,下面例子中进行的是将 origin.pdf 的第17页替换为 s17.pdf 的第1页:

python 复制代码
import PyPDF2

def replace_pages(original_pdf_path, replacement_pages):
    with open(original_pdf_path, 'rb') as original_file:
        original_pdf = PyPDF2.PdfReader(original_file)
        output_pdf = PyPDF2.PdfWriter()

        for page_num in range(len(original_pdf.pages)):
            if page_num == 16:  # Replace page 17 with first page of s17.pdf
                with open(replacement_pages['s17'], 'rb') as replacement_file:
                    replacement_pdf = PyPDF2.PdfReader(replacement_file)
                    output_pdf.add_page(replacement_pdf.pages[0])
            else:
                output_pdf.add_page(original_pdf.pages[page_num])

        with open('output.pdf', 'wb') as output_file:
            output_pdf.write(output_file)

# 定义要替换的页面和其对应的替换文件
replacement_pages = {
    's17': 's17.pdf',
}

replace_pages('origin.pdf', replacement_pages)

可以根据自己的实际需求进行修改。

相关推荐
郑州光合科技余经理3 分钟前
开发实战:海外版同城o2o生活服务平台核心模块设计
开发语言·git·python·架构·uni-app·生活·智慧城市
Kratzdisteln3 分钟前
【Python】Flask 2
开发语言·python·flask
成旭先生9 分钟前
文档(如word、ppt、pdf等)在线预览解决方案:基于HTML转换的技术实践与对比
pdf·word·powerpoint
程序员三藏9 分钟前
单元测试详解
自动化测试·软件测试·python·测试工具·职场和发展·单元测试·测试用例
540_54013 分钟前
ADVANCE Day44
人工智能·python·深度学习
好好学操作系统21 分钟前
flash_attn ImportError undefined symbol:
开发语言·python
CCPC不拿奖不改名22 分钟前
面向对象编程:继承与多态+面试习题
开发语言·数据结构·python·学习·面试·职场和发展
year--27 分钟前
虚拟环境安装requirements.txt
python
m5655bj28 分钟前
使用 C# 将 RTF 文档转换为 PDF 格式
pdf·c#
num_killer31 分钟前
小白的uv包管理工具使用
python·conda·pip·uv