【脚本】将一个指定的JPG图像文件插入到另一个指定的PDF文件的第一页,并生成一个新的PDF文件作为输出

这个脚本的作用是将一个指定的JPG图像文件插入到另一个指定的PDF文件的第一页,并生成一个新的PDF文件作为输出。

具体的步骤如下:

  1. 将指定的JPG图像文件转换为PDF格式,并保存为image.pdf文件。
  2. 创建一个PDF写入器对象output_pdf
  3. 读取image.pdf文件,获取其中的第一页,并将其添加到output_pdf对象中。
  4. 读取指定的原始PDF文件,并将其所有页面依次添加到output_pdf对象中。
  5. 指定输出目录路径,将新的PDF文件保存在该目录下,文件名与原始PDF文件相同。

请确保在运行脚本之前,将image_path变量和original_pdf_path变量设置为正确的图像文件路径和原始PDF文件路径,并将output_directory变量设置为希望保存新PDF文件的目录路径。
需要安装以下依赖:pip install pypdf2 img2pdf

import os
import img2pdf
from PyPDF2 import PdfWriter, PdfReader

# 将图像转换为 PDF
image_path = r"D:\360安全浏览器下载\《11招玩转网络安全:用Python,更安全》_hstking_2018-06-01.jpg"
with open(image_path, "rb") as image_file, open("image.pdf", "wb") as pdf_file:
    pdf_file.write(img2pdf.convert(image_file.read()))

# 创建 PDF 写入器
output_pdf = PdfWriter()

# 读取图像 PDF
with open("image.pdf", "rb") as image_pdf_file:
    image_pdf = PdfReader(image_pdf_file)
    # 将图像添加到输出文件
    output_pdf.add_page(image_pdf.pages[0])

# 读取原始 PDF
original_pdf_path = r"E:\未编辑\《11招玩转网络安全:用Python,更安全》_hstking_2018-06-01.pdf"
with open(original_pdf_path, "rb") as original_pdf_file:
    original_pdf = PdfReader(original_pdf_file)
    # 将原始 PDF 的所有页面添加到输出文件
    for page_num in range(len(original_pdf.pages)):
        output_pdf.add_page(original_pdf.pages[page_num])

# 写入新的 PDF
output_directory = r"E:\images_modified"
new_pdf_path = os.path.join(output_directory, os.path.basename(original_pdf_path))
with open(new_pdf_path, "wb") as output_pdf_file:
    output_pdf.write(output_pdf_file)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ascarl2010

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值