图片转换到PDF

把一系列图片整合到PDF格式

Python代码

python 复制代码
import os
from io import BytesIO
from PIL import Image

os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8'
SUPPORT_SUFFIX = ["jpg", "jpeg", "png"]


def pic_to_pdf(image_bytes: bytes) -> bytes:
    """将单个图片转换为单张PDF
    :param image_bytes: 图片的bytes对象
    :return: PDF的bytes对象
    """
    # 将bytes对象转换为BytesIO对象
    image_bytes_io = BytesIO(image_bytes)
    # 从内存中读取图片
    image_object = Image.open(image_bytes_io)
    # 打开内存中的文件用于保存PDF
    with BytesIO() as result_bytes_io:
        # 将图片保存为单张PDF
        image_object.save(result_bytes_io, "PDF", resolution=100.0)
        # 获取内存中的文件
        data = result_bytes_io.getvalue()
    # 返回PDF的bytes对象
    return data


def batch_convert(image_path: str, pdf_path: str) -> None:
    """批量将图片转换为单张PDF
    :param image_path: 图片的文件夹
    :param pdf_path: PDF文件保存的文件夹
    """
    # 遍历文件夹下所有文件
    for root, dirs, files in os.walk(image_path, topdown=False):
        for name in files:
            # 提取文件的后缀名
            file_suffix = os.path.splitext(name)[-1].lstrip(".").lower()
            # 检测该文件格式是否受到支持
            if file_suffix not in SUPPORT_SUFFIX:
                continue
            # 拼接出图片文件的绝对路径
            source_file_path = os.path.join(root, name)
            # 拼接出PDF文件的绝对路径
            target_file_path = os.path.join(pdf_path, f"{os.path.splitext(name)[0]}.pdf")
            # 将图片文件转换为PDF文件
            with open(source_file_path, "rb") as source:
                with open(target_file_path, "wb") as target:
                    target.write(pic_to_pdf(source.read()))


batch_convert("", "")
相关推荐
Rover Ramble13 小时前
提取大型非扫描pdf文件的表格数据
pdf
2501_9071368216 小时前
电子礼簿系统-红白喜事记账工具,PDF/Execl导出
pdf·软件需求
王五周八18 小时前
html转化为base64编码的pdf文件
前端·pdf·html
ComPDFKit2 天前
ComPDF 与 Aspose:转换 SDK 的全面比较
pdf
优选资源分享2 天前
PDF 电子签章工具 v5.0:全能处理PDF电子签章
pdf
Arvin_Zhang20162 天前
使用python实现从PDF格式的control mapping获取gross die数量
python·pdf
徐同保2 天前
上传文件,在前端用 pdf.js 提取 上传的pdf文件中的图片
前端·javascript·pdf
CodeCraft Studio2 天前
国产化PDF处理控件Spire.PDF教程:使用Python批量自动化将PDF转换为黑白(灰度)
python·pdf·自动化·spire.pdf·文档自动化·pdf开发组件·国产化文档组件
成旭先生2 天前
文档(如word、ppt、pdf等)在线预览解决方案:基于HTML转换的技术实践与对比
pdf·word·powerpoint
m5655bj2 天前
使用 C# 将 RTF 文档转换为 PDF 格式
pdf·c#