Python脚本:一键将图片按顺序合成PDF
前言在日常工作和学习中我们经常需要将多张图片如扫描件、截图、照片合并成一个PDF文件。虽然有很多现成的工具可以实现但用Python自己写一个脚本不仅灵活还能避免上传到第三方网站带来的隐私风险。今天分享一个实用的Python脚本可以将文件夹中的图片按名称序号从小到大自动排序然后合成一个PDF文件。--- 脚本功能· 支持常见图片格式.jpg、.jpeg、.png、.bmp、.gif、.tiff· 智能自然排序正确识别文件名中的数字实现 1,2,3...10,11 而不是 1,10,11,2,3· 自动处理透明背景PNG RGBA模式转为RGB· 支持命令行参数和交互式输入两种方式· 可自定义输出PDF文件名--- 依赖安装脚本需要 Pillow 库来处理图片使用前请先安装bashpip install Pillow--- 核心代码解析1. 自然排序函数pythonimport redef natural_sort_key(filename):提取文件名中的数字用于自然排序numbers re.findall(r\d, filename)return [int(num) for num in numbers] if numbers else [filename]这个函数使用正则表达式提取文件名中的所有数字并将其转换为整数作为排序键。例如· img2.jpg → [2]· page10.jpg → [10]· image_1_2.jpg → [1, 2]2. 图片转PDF主函数pythonfrom PIL import Imagedef images_to_pdf(image_folder, output_pdf_nameoutput.pdf):# 获取所有图片文件image_files [f for f in os.listdir(image_folder)if f.lower().endswith(supported_formats)]# 自然排序image_files.sort(keynatural_sort_key)# 处理第一张图片first_image Image.open(first_image_path)if first_image.mode RGBA:first_image first_image.convert(RGB)# 处理剩余图片并保存为PDFfirst_image.save(output_pdf_name, save_allTrue,append_imagesimages, quality95)关键点· 第一张图片作为PDF的基础页· 剩余图片通过 append_images 参数追加· quality95 控制输出质量1-1003. 两种使用方式python# 方式1命令行参数python script.py C:\Pictures my_doc.pdf# 方式2交互式输入python script.py# 然后按提示输入文件夹路径和输出文件名--- 完整脚本pythonimport osimport sysfrom PIL import Imageimport redef natural_sort_key(filename):numbers re.findall(r\d, filename)return [int(num) for num in numbers] if numbers else [filename]def images_to_pdf(image_folder, output_pdf_nameoutput.pdf):supported_formats (.jpg, .jpeg, .png, .bmp, .gif, .tiff)image_files [f for f in os.listdir(image_folder)if f.lower().endswith(supported_formats)]if not image_files:print(文件夹中没有找到图片文件)returnimage_files.sort(keynatural_sort_key)print(f找到 {len(image_files)} 张图片)for i, img in enumerate(image_files, 1):print(f {i}. {img})images []try:first_image_path os.path.join(image_folder, image_files[0])first_image Image.open(first_image_path)if first_image.mode RGBA:first_image first_image.convert(RGB)for img_file in image_files[1:]:img_path os.path.join(image_folder, img_file)img Image.open(img_path)if img.mode RGBA:img img.convert(RGB)elif img.mode ! RGB:img img.convert(RGB)images.append(img)print(f已加载: {img_file})first_image.save(output_pdf_name, save_allTrue,append_imagesimages, quality95)print(f\n✅ 成功生成PDF: {output_pdf_name} ({len(image_files)}页))except Exception as e:print(f❌ 出错: {e})finally:if first_image in locals():first_image.close()for img in images:img.close()def main():if len(sys.argv) 1:image_folder sys.argv[1]output_pdf sys.argv[2] if len(sys.argv) 2 else output.pdfelse:image_folder input(图片文件夹路径回车使用当前目录: ).strip()if not image_folder:image_folder .output_pdf input(输出PDF文件名回车使用output.pdf: ).strip()if not output_pdf:output_pdf output.pdfif not output_pdf.lower().endswith(.pdf):output_pdf .pdfif not os.path.exists(image_folder):print(f错误文件夹 {image_folder} 不存在)returnimages_to_pdf(image_folder, output_pdf)if __name__ __main__:main()--- 使用示例场景将扫描的书籍图片合成PDF假设文件夹结构scans/├── page_1.jpg├── page_2.jpg├── page_3.jpg├── ...└── page_20.jpg运行命令bashpython images_to_pdf.py ./scans book.pdf输出找到 20 张图片排序后的图片顺序1. page_1.jpg2. page_2.jpg...20. page_20.jpg已加载: page_2.jpg...✅ 成功生成PDF: book.pdf (20页)--- 扩展建议1. 调整图片尺寸统一可在保存前将所有图片缩放到相同尺寸pythonimg img.resize((width, height), Image.Resampling.LANCZOS)2. 添加密码保护可使用 pypdf 或 pdfkit 库对生成的PDF加密3. 支持子文件夹递归添加 os.walk() 遍历子目录4. 设置页面方向根据图片宽高比自动判断横竖版--- 总结这个脚本只有不到100行代码却解决了日常工作中一个很常见的需求。它的优点是· ✅ 轻量只需Pillow一个依赖· ✅ 智能自然排序无需手动重命名· ✅ 安全本地运行不上传任何数据· ✅ 灵活支持命令行和交互式两种模式希望这个脚本对你有帮助如果你有改进建议或问题欢迎在评论区交流。--- 推荐阅读· Pillow官方文档· Python正则表达式从入门到精通本文为原创转载请注明出处。
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2480183.html
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!