几行python代码让图片转换为PDF文件
一、打开PyCharm,设置运行环境,如:python3.9
二、确认 python已经安装了 Pillow 库,如果未安装,可在命令行运行
pip install Pillow
三、创建 OutPdf.py 文件,内容如下:
from PIL import Image
import os
def images_to_pdf(image_files, output_pdf):
images = []
for file in image_files:
if not os.path.exists(file):
print(f"图片文件 {file} 不存在,跳过。")
continue
img = Image.open(file)
if img.mode != 'RGB':
img = img.convert('RGB')
images.append(img)
if images:
images[0].save(output_pdf, save_all=True, append_images=images[1:])
if __name__ == "__main__":
image_file = ["image.jpg"]
output_pdf = "output.pdf"
images_to_pdf(image_file, output_pdf)
四、使用注意事项
1、 代码保存为.py文件并运行,会在指定路径生成 PDF 文件。
2、 运行前需将image_file列表中的文件名替换为实际图片文件名及路径,默认在同一路径下。
3、 output_pdf替换为期望的输出 PDF 文件名及路径,默认在同一路径下。
4、 如果不想修改源码,可以修改图片文件名。然后把此文件(OutPdf.py)和需要转换的图片放在同一目录下,用PyCharm打开此文件,设置运行环境(如:python3.9),运行此文件即可。
5、 注意图片格式对应:如:1.jpg 2.png 3.jpeg 4.gif 5.bmp 6.tiff 7.svg 8.psd
6、需要安装 Pillow 库,如果未安装,可在命令行运行 pip install Pillow。