import os
import re
from PIL import Image
from reportlab.pdfgen import canvas
def natural_sort_key(s):
return [int(text) if text.isdigit() else text for text in re.split('([0-9]+)', s)]
def images_to_pdf(folder_path, output_pdf):
image_files = [f for f in os.listdir(folder_path) if f.lower().endswith(('.png', '.jpg', '.jpeg', '.gif'))]
image_files.sort(key=natural_sort_key)
c = canvas.Canvas(output_pdf)
for image_file in image_files:
image_path = os.path.join(folder_path, image_file)
img = Image.open(image_path)
width, height = img.size
c.setPageSize((width, height))
c.drawImage(image_path, 0, 0, width, height)
c.showPage()
c.save()
folder_path = r''
output_pdf = 'output.pdf'
images_to_pdf(folder_path, output_pdf)
import os
import re
from PIL import Image
from reportlab.pdfgen import canvas
def natural_sort_key(s):
return [int(text) if text.isdigit() else text for text in re.split('([0-9]+)', s)]
def get_selected_folder(base_path):
folders = [f for f in os.listdir(base_path) if os.path.isdir(os.path.join(base_path, f))]
for idx, folder in enumerate(folders, start=1):
print(f"{idx}. ({folder})")
choice = int(input("选择文件夹的编号: ")) - 1
if 0 <= choice < len(folders):
return os.path.join(base_path, folders[choice])
else:
raise ValueError("无效的选择")
def images_to_pdf(folder_path, output_pdf):
image_files = [f for f in os.listdir(folder_path) if f.lower().endswith(('.png', '.jpg', '.jpeg', '.gif'))]
image_files.sort(key=natural_sort_key)
c = canvas.Canvas(output_pdf)
for image_file in image_files:
image_path = os.path.join(folder_path, image_file)
with Image.open(image_path) as img:
width, height = img.size
c.setPageSize((width, height))
c.drawImage(image_path, 0, 0, width, height)
c.showPage()
c.save()
selected_folder = get_selected_folder(os.getcwd())
output_pdf = os.path.basename(selected_folder) + '.pdf'
images_to_pdf(selected_folder, output_pdf)