图片转换到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("", "")
相关推荐
『 时光荏苒 』17 小时前
网页变成PDF下载到本地
前端·javascript·pdf·网页下载成
chenchihwen18 小时前
AI代码开发宝库系列:PDF文档解析MinerU
人工智能·python·pdf·dashscope
Source.Liu1 天前
【PDF-rs】pdf子项目的lib.rs文件
pdf
学会用脚编程1 天前
word转Pdf,在window正常,放在linux服务器上就转出来中文是空白
pdf·word
机器学习算法与Python实战1 天前
最好的大模型训练、微调教程.pdf
pdf
CodeCraft Studio1 天前
PPT处理控件Aspose.Slides教程:使用Java将PowerPoint笔记导出为PDF
java·笔记·pdf·powerpoint·aspose·ppt转pdf·java将ppt导出pdf
深蓝电商API1 天前
告别混乱文本:基于深度学习的 PDF 与复杂版式文档信息抽取
人工智能·深度学习·pdf
hu55667982 天前
Adobe Acrobat DC PDF如何批量文本替换
adobe·pdf
Datawhale3 天前
《Hello-Agents》完整PDF首发,智能体教程免费下载!
pdf
hnxaoli3 天前
win10程序(十四)pdf转docx简易版
开发语言·python·pdf