使用python将多张图片合成PDF

先安装 pillow 介绍

pip install pillow

将多张图片合成PDF

from PIL import Image
import os

# 防止字符串乱码
os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8'

def pic2pdf(img_path, pdf_path):
    file_list = os.listdir(img_path)
    sources = []
    jpg_files = []
    for file in file_list:
        if 'png' in file or 'jpg' in file:
            jpg_files.append(file)
    
    jpg_files.sort(key=lambda x: int(x.split('.')[0]))
    output = Image.open(img_path + jpg_files[0])
    jpg_files.pop(0)
    for file in jpg_files:
        jpg_file = Image.open(img_path + file)
        if jpg_file.mode == "RGB":
            jpg_file = jpg_file.convert("RGB")
        sources.append(jpg_file)
    output.save(pdf_path, "pdf", save_all=True, append_images=sources)


# 待转换图像路径
img_path = "../data/materials/ABC/"
# 转换后的pdf
pdf_path = "../data/materials/ABC.pdf"
pic2pdf(img_path=img_path, pdf_path=pdf_path)

 

posted @ 2022-09-20 14:16  慕尘  阅读(622)  评论(0编辑  收藏  举报