图片转换到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("", "")
相关推荐
ElasticPDF-新国产PDF编辑器39 分钟前
【最新·免费PDF编辑器·不限终端·最高性价比SDK】直接编辑 PDF 原有图片!裁剪、替换、旋转与图层管理
pdf
gb42152872 小时前
python中pypdf库和langchain-unstructured库在解析pdf文件的时候的区别?
python·langchain·pdf
ElasticPDF-新国产PDF编辑器4 小时前
【最新·免费PDF编辑器·不限终端·最高性价比SDK】高亮、评论、图章、手绘与签名,一套完成 PDF 批注
pdf·编辑器
SunnyDays10115 小时前
Java 如何为 PDF 添加、修改和删除书签
java·pdf
Elastic 中国社区官方博客7 小时前
一个字段,覆盖所有模态:Elasticsearch 的 semantic 字段如何自动索引和搜索图像、音频、视频和 PDF
大数据·数据库·elasticsearch·ai·云原生·pdf·全文检索
zyplayer-doc9 小时前
核心制度不该被随手修改:用zyplayer-doc锁定文档和全部子文档
大数据·数据库·人工智能·笔记·pdf·ocr
2601_965912831 天前
PDF添加页码功能横向评测:7款免费方案实测数据对比
pdf
AmyLin_20011 天前
PDF 色彩保真工程实践【5】核心实现(下):拼装 Image XObject、页面资源与内容流
c++·pdf·sdk·颜色空间·印刷·icc·cmyk
Jazz_z1 天前
如何用Python将彩色PDF一键转为黑白(灰度)
java·python·pdf
SamChan901 天前
PDF拆分+翻译+合并:一条流水线处理大文档的Python方案
java·python·ai·pdf·自动化