python实现图片转PDF

import os

from PIL import Image
from reportlab.pdfgen import canvas


def image_resize(img, width, height):
    """
    图片缩放
    :param img: 图片路径
    :param width: 宽
    :param height: 高
    :return: 宽高
    """
    image = Image.open(img)
    image.resize((width, height), Image.ANTIALIAS).save(img, quality=95, dpi=(72, 72))
    return width, height


def image_to_pdf(img, pdf_path=None, resize=True):
    """
    图片转PDF
    :param img: 图片路径
    :param pdf_path: 生成的PDF路径
    :param resize: 是否缩放图片至A4大小
    :return: None
    """
    pix_x, pix_y = 595, 842  # 分辨率为72像素时的A4纸大小
    if not pdf_path:
        pdf_path = f'{os.path.splitext(img)[0]}.pdf'
    w, h = Image.open(img).size
    if resize:
        w, h = image_resize(img, pix_x, pix_y)
        width = (pix_x - w) // 2
        height = (pix_y - h) // 2
        user = canvas.Canvas(pdf_path)
        if width > 1 and height > 1:  # 图片size是否小于最小值
            user.drawImage(img, width, height)  # PDF中居中显示
        else:
            user.drawImage(img, 0, 0)
    else:
        user = canvas.Canvas(pdf_path, pagesize=(w, h))
        user.drawImage(img, 0, 0)
    user.showPage()
    user.save()
posted @ 2021-07-01 16:53  cnblogs用户  阅读(681)  评论(0编辑  收藏  举报