图片转换到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("", "")
相关推荐
FL16238631291 小时前
pdf批量转ofd本地离线操作简单支持win10及以上系统
pdf
薛定猫AI3 小时前
【技术干货】大模型文档结构化提取实战:Python解析PDF发票并批量生成CSV
java·python·pdf
庖丁AI4 小时前
PDF 表格提取到 CSV 和 JSON 怎么做?复杂版式要先解决结构化解析
pdf·json
王莎莎-MinerU4 小时前
解析回归集:RAG 和 Agent 上线前,先把表格、公式、版面测清楚
人工智能·算法·数据挖掘·回归·pdf·ocr
复园电子8 小时前
企业级PDF批量盖章方案选型指南
数据库·pdf
罗政20 小时前
PDF 批量合并工具:本地 AI 自动排序、识别正文日期与合同编号
数据库·pdf·php
Metaphor6921 天前
使用 Python 添加、隐藏和删除 PDF 图层
python·pdf·图层
SEO-狼术1 天前
Navigate PDF Documents with Page Thumbnails
pdf
SEO-狼术2 天前
Organize PDF Navigation with Bookmarks
pdf