图片转换到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("", "")
相关推荐
拓端研究室21 小时前
专题:2025AI产业应用与投资趋势报告:技术选型、行业落地与效益洞察|附900+份报告PDF、数据、可视化模板汇总下载
pdf
GodFamiliar21 小时前
linux下(华为云)libreoffice工具doc转pdf坑
pdf·华为云
点云-激光雷达-Slam-三维牙齿1 天前
任意PDF与图片的批量信息提取软件 OCR 识别加大模型
pdf·ocr
E_ICEBLUE1 天前
使用 Java 将 PowerPoint 转换为 PDF 的完整指南
java·开发语言·pdf·powerpoint·ppt
qq_296544651 天前
永久免费的PDF转word,PDFgear安卓版,mac版,win版都有,word转PDF,PDF转Excel
pdf·word
Ron丶1 天前
10 款 PDF 处理工具(全解锁 · 免费使用)
pdf
烂不烂问厨房2 天前
前端实现docx与pdf预览
前端·javascript·pdf
一晌小贪欢2 天前
【静态功能网站】构建高效的 Markdown 转 PDF 在线工具
pdf·markdown·markdown转pdf·markdown 转 pdf
拓端研究室2 天前
专题:2025年汽车行业研究报告-重塑之局:新能源、智能网联与全球化|附340+份报告PDF、数据、可视化模板汇总下载
pdf
wxl7812272 天前
从图片PDF到结构化文本:基于Python+Dify的批量OCR自动化解决方案
python·pdf·ocr