You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用bash或Python将多级目录图片按序批量生成对应卷的PDF

解决方案

以下提供两种可直接使用的实现方案,均满足自动适配任意卷、章节、图片数量,严格按编号排序,兼容多格式图片的需求。

Bash 实现方案

依赖安装

需要用到img2pdf工具进行无损图片转PDF,安装方式:

  • Debian/Ubuntu 系:sudo apt install img2pdf
  • macOS:brew install img2pdf
  • 全平台通用pip安装:pip install img2pdf

脚本代码

#!/bin/bash
# 遍历所有vol开头的卷目录
for vol_dir in vol*/; do
    vol_name="${vol_dir%/}"
    output_pdf="${vol_name}.pdf"
    # 临时存储图片路径列表
    > img_list.tmp
    # 按自然数字排序遍历当前卷下的所有chap章节目录
    for chap_dir in $(find "$vol_dir" -maxdepth 1 -type d -name "chap*" | sort -V); do
        # 按自然数字排序收集章节内所有jpg、jpeg、png格式图片,忽略大小写
        find "$chap_dir" -maxdepth 1 -type f \( -iname "*.jpg" -o -iname "*.jpeg" -o -iname "*.png" \) | sort -V >> img_list.tmp
    done
    # 生成对应卷的PDF
    img2pdf --output "$output_pdf" $(cat img_list.tmp)
    rm img_list.tmp
    echo "生成完成:$output_pdf"
done

使用方法

将脚本保存为gen_manga_pdf.sh,放在所有vol目录的同级目录下,执行chmod +x gen_manga_pdf.sh && ./gen_manga_pdf.sh即可。

Python 实现方案

依赖安装

需要用到Pillow处理图片、natsort做自然排序,安装命令:
pip install pillow natsort

代码实现

import os
from natsort import natsorted
from PIL import Image

def generate_manga_pdfs():
    # 自动识别所有vol开头的卷目录并自然排序
    vol_dirs = [d for d in os.listdir(".") if os.path.isdir(d) and d.startswith("vol")]
    vol_dirs = natsorted(vol_dirs)

    for vol_dir in vol_dirs:
        all_imgs = []
        # 识别当前卷下所有chap开头的章节目录并自然排序
        chap_dirs = [
            os.path.join(vol_dir, d)
            for d in os.listdir(vol_dir)
            if os.path.isdir(os.path.join(vol_dir, d)) and d.startswith("chap")
        ]
        chap_dirs = natsorted(chap_dirs)

        for chap_dir in chap_dirs:
            # 收集章节内所有支持格式的图片并自然排序
            valid_suffix = (".jpg", ".jpeg", ".png", ".JPG", ".JPEG", ".PNG")
            chap_imgs = [
                os.path.join(chap_dir, f)
                for f in os.listdir(chap_dir)
                if f.endswith(valid_suffix) and os.path.isfile(os.path.join(chap_dir, f))
            ]
            all_imgs.extend(natsorted(chap_imgs))
        
        if not all_imgs:
            print(f"{vol_dir} 下无有效图片,跳过生成")
            continue
        
        # 转换图片格式并生成PDF
        pil_img_list = [Image.open(img_path).convert("RGB") for img_path in all_imgs]
        output_path = f"{vol_dir}.pdf"
        pil_img_list[0].save(output_path, save_all=True, append_images=pil_img_list[1:])
        print(f"生成完成:{output_path}")

if __name__ == "__main__":
    generate_manga_pdfs()

使用方法

将代码保存为gen_manga_pdf.py,放在所有vol目录的同级目录下,执行python gen_manga_pdf.py即可。

内容的提问来源于stack exchange,提问作者Cla

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 21:36:02