图片转换到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("", "")
相关推荐
2501_9307077810 小时前
使用C#代码替换 PDF 文档中的文本
pdf
周末也要写八哥14 小时前
Visual C++6.0下载安装流程及PDF学习手册资源
c++·学习·pdf
优化控制仿真模型14 小时前
2026初中英语考纲词汇表(1600词)PDF电子版
经验分享·pdf
2401_8769641316 小时前
27考研优路|肖睿|唐辛|师大集训营|大牙|B站橙啦101公共课PDF
考研·pdf
2401_8769641316 小时前
27余峰|苏一|大李子|鹿吖101公共课托管班网课PDF
pdf
SEO-狼术16 小时前
Visualize Trends with Bar Charts
pdf·.net
私人珍藏库16 小时前
【PC】[吾爱大神原创工具] PDFImageViewer V1 永久免费的PDF图像查看和导出工具
windows·pdf·工具·软件·多功能
小饕16 小时前
RAG 数据加载全攻略:从文本到 PDF 的 Loader 选型指南
人工智能·pdf
其实秋天的枫17 小时前
【26年】考研数学一、二、三历年真题及答案解析PDF电子版(1987-2026年)
经验分享·pdf
夏日清风有你17 小时前
WPS pdf 页面替换和编辑使用
pdf