python给pdf的指定页添加图片到指定位置

代码如下, 使用了第三方库

import os
import img2pdf
from PIL import Image
from PyPDF2 import PdfReader, PdfWriter, PageObject, Transformation


def image_to_pdf(image_filename, pdf_filename):
    """
    把img转为pdf文件, 临时中转
    :param image_filename:
    :param pdf_filename:
    :return:
    """
    try:
        with open(pdf_filename, "wb") as f:
            img = Image.open(image_filename)
            pdf_bytes = img2pdf.convert(image_filename)
            f.write(pdf_bytes)
        return True
    except Exception:
        return False


def main(image_path, pdf_path, page_number, tx, ty):
    # 先给图片转为pdf文件
    tmp_img_pdf = "tmp.pdf"
    if image_to_pdf(image_path, tmp_img_pdf):
        # 获得指定页PDF页面对象
        pdf_obj = PdfReader(pdf_path)
        old_page = pdf_obj.pages[page_number - 1]
        page_width = float(old_page.mediabox[2])
        page_height = float(old_page.mediabox[3])

        # 获得img以及最大的蒙层
        img_pdf = PdfReader(tmp_img_pdf)
        img_pdf_obj = img_pdf.pages[0]
        new_img_page = PageObject.create_blank_page(None, page_width, page_height)
        new_img_page.merge_page(img_pdf_obj)
        new_img_page.add_transformation(Transformation().translate(tx, ty))

        # 合并图片pdf_page到旧页面
        old_page.merge_page(new_img_page)

        # 写入
        pdf_writer = PdfWriter()
        for p in pdf_obj.pages:
            pdf_writer.add_page(p)
        with open("./output.pdf", 'wb') as output_file:
            pdf_writer.write(output_file)

        os.remove("./tmp.pdf")
    else:
        pass

if __name__ == '__main__':
    main("./1687244044766.jpg", "./0420新增指标.pdf", 2, 100, 100)