import os
from PIL import Image
from PyPDF2 import PdfMerger
def convert_images_to_pdf(image_folder, output_pdf):
# 获取文件夹中所有 JPG 图片的路径
image_files = [f for f in os.listdir(image_folder) if f.endswith('.jpg')]
image_files.sort() # 按名称排序,以确保顺序一致
# 创建一个 PdfMerger 对象
merger = PdfMerger()
temp_pdf_files = []
for image_file in image_files:
image_path = os.path.join(image_folder, image_file)
with Image.open(image_path) as img:
# 转换为 RGB 模式,因为 PDF 不支持透明度
img = img.convert('RGB')
# 保存为临时 PDF 文件
temp_pdf_path = os.path.join(image_folder, f"{os.path.splitext(image_file)[0]}.pdf")
img.save(temp_pdf_path)
temp_pdf_files.append(temp_pdf_path)
for temp_pdf_path in temp_pdf_files:
# 将临时 PDF 文件添加到合并对象中
merger.append(temp_pdf_path)
# 将所有图片合并成一个 PDF 文件
merger.write(output_pdf)
merger.close()
print(f"PDF saved as {output_pdf}")
# 删除临时 PDF 文件
for temp_pdf_path in temp_pdf_files:
os.remove(temp_pdf_path)
def main():
image_folder = r'C:\Users\LiuYang\Desktop\P1'
output_pdf = r'C:\Users\LiuYang\Desktop\output.pdf'
convert_images_to_pdf(image_folder, output_pdf)
main()
将文件夹内的图片打印为1个pdf
最新推荐文章于 2024-08-27 15:37:34 发布