我正在尝试用 Python 制作一个将图像转换为 PDF 的转换器。仅选择一张图像时效果很好,但是当我选择多张图像时,它会出现以下错误:“str”objct 没有属性“encoderinfo”。
这是我的完整代码:
import tkinter as tk
from tkinter import filedialog
from tkinter import messagebox
from PIL import Image
import os
# function to convert images to PDF
def images_to_pdf(images, pdf_name):
try:
# create a new pdf file
pdf = Image.open(images[0])
pdf.save(pdf_name, "PDF", resolution=100.0,
save_all=True, append_images=images[1:])
messagebox.showinfo("Success",
"Images have been successfully converted to PDF.")
except Exception as e:
messagebox.showerror("Error",
"Failed to convert images to PDF.\nError: " + str(e))
# function to select images
def select_images():
images = filedialog.askopenfilenames(title="Select Images",
filetypes=(("Image files", "*.jpg;*.jpeg;*.png"),
("All files", "*.*")), initialdir = "C:/")
return images
# function to select pdf name and path
def select_pdf():
pdf = filedialog.asksaveasfilename(title="Save PDF As",
defaultextension=".pdf", initialdir = "C:/",
filetypes=(("PDF files", "*.pdf"),("All files", "*.*")))
return pdf
# create GUI
root = tk.Tk()
root.title("Convert Images to PDF")
select_images_btn = tk.Button(root,
text="Select Images", command=select_images)
select_pdf_btn = tk.Button(root, text="Select PDF",
command=select_pdf)
convert_btn = tk.Button(root, text="Convert",
command=lambda: images_to_pdf(select_images(), select_pdf()))
select_images_btn.pack()
select_pdf_btn.pack()
convert_btn.pack()
root.mainloop()
如何选择多张图像并将其放入一个完整的 PDF 文件中?
编辑:另外,很抱歉错过了回溯消息。在这里:
Traceback (most recent call last):
File "c:\Users\username\OneDrive\Desktop\ConvertImageToPdf\ImageToPdf.py", line 13, in images_to_pdf
pdf.save(pdf_name, "PDF", resolution=100.0,
File "C:\Users\username\AppData\Local\Programs\Python\Python312\Lib\site-packages\PIL\Image.py", line 2459, in save
save_handler(self, fp, filename)
File "C:\Users\username\AppData\Local\Programs\Python\Python312\Lib\site-packages\PIL\PdfImagePlugin.py", line 43, in _save_all
_save(im, fp, filename, save_all=True)
File "C:\Users\username\AppData\Local\Programs\Python\Python312\Lib\site-packages\PIL\PdfImagePlugin.py", line 221, in _save
append_im.encoderinfo = im.encoderinfo.copy()
^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'str' object has no attribute 'encoderinfo'
我没有测试过,但我同意@TheLizzard - 你必须打开/加载所有图像
imgs = [Image.open(x) for x in images]
稍后使用 then 代替文件名
pdf = imgs[0]
pdf.save(..., append_images=imgs[1:])