import os
from PIL import Image
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas
def get_jpg_files(directory):
"""
获取指定目录下所有JPG文件的路径
"""
jpg_files = [os.path.join(directory, f) for f in os.listdir(directory) if f.lower().endswith('.jpg')]
return jpg_files
def convert_multiple_jpg_to_pdf(jpg_paths, pdf_path):
"""
将多个JPG文件转换为一个PDF文件
"""
if not jpg_paths:
print("No JPG files found.")
return
# 打开第一个JPG图像以获取尺寸
first_image = Image.open(jpg_paths[0])
width, height = first_image.size
# 创建PDF文件
c = canvas.Canvas(pdf_path, pagesize=(width, height))
for jpg_path in jpg_paths:
# 打开JPG图像
image = Image.open(jpg_path)
# 在PDF页面上绘制图像
c.drawImage(jpg_path, 0, 0, width, height)
# 添加新页面
c.showPage()
# 保存PDF文件
c.save()
print(f"PDF saved as {pdf_path}")
# D盘根目录
directory = "D:\\"
jpg_files = get_jpg_files(directory)
# 目标PDF文件路径
output_pdf = "D:\\output.pdf"
# 转换并保存为PDF
convert_multiple_jpg_to_pdf(jpg_files, output_pdf)
标签:files,python,jpg,JPG,D盘,pdf,PDF,path
From: https://blog.csdn.net/qq490525427/article/details/139577872