Python使用FPDF添加JPG图片报错‘Unsupported image type’求助
问题:FPDF添加JPG图片时报错“Unsupported image type”
我是Python初学者,正在使用FPDF库开发PDF生成程序,添加JPG图片时触发运行时错误:“FPDF error: Unsupported image type”。
完整代码
class PDF(FPDF): def __init__(self): super().__init__() self.header_text = "" self.footer_text = "" self.table_data = [] self.table_header = [] self.image_file = "" self.pdf_title = "" # Page header def header(self): if self.image_file: self.image(self.image_file, 80, 25, 50) if self.pdf_title: self.set_font('Arial', 'B', 15) self.cell(80) self.cell(30, 10, self.pdf_title, 0, 0, 'C') self.ln(50) if self.header_text: self.set_font('Arial', 'B', 12) self.cell(0, 10, self.header_text, 0, 0, 'C') self.ln(20) # Add a table to the PDF def add_table(self, header, data): # Set the font and style for the table self.set_font('Arial', '', 10) # Calculate the width of each column and the height of each row col_width = self.w * 0.9 / len(header) row_height = self.font_size * 1.5 # Add the table header for col_number, column_title in enumerate(header): self.cell(col_width, row_height, str(column_title), border=1) self.ln() # Add the table data self.set_font('Arial', '', 10) for row in data: for item in row: self.cell(col_width, row_height, str(item), border=1) self.ln() # Add text to the PDF def add_text(self): self.add_page() # Set the font and style for the text self.set_font('Arial', '', 12) # Add the text self.multi_cell(0, 10, self.header_text) self.ln() # Add image to the PDF def add_image(self): self.add_page() # Add the image self.image(self.image_file, x=10, y=10, w=190) self.ln() # Page footer def footer(self): if self.footer_text: # Position at 1.5 cm from bottom self.set_y(-15) # Arial italic 8 self.set_font('Arial', 'I', 8) # Page number self.cell(0, 10, self.footer_text + ' - Page ' + str(self.page_no()) + '/{nb}', 0, 0, 'C') # Instantiation of inherited class pdf = PDF() # Printing lines on first page pdf.add_page() pdf.set_font('Times', '', 10) # Switch statement while True: print("1. Add page header") print("2. Add page footer") print("3. Add table") print("4. Add text") print("5. Add image") print("6. Generate PDF and exit") choice = int(input("Enter your choice (1-6): ")) if choice == 1: pdf.header_text = input("Enter the header text: ") pdf.image_file = input("Enter the name of the image file (including extension): ") pdf.pdf_title = input("Enter the title for the PDF: ") elif choice == 2: pdf.footer_text = input("Enter the footer text: ") pdf.footer_page_number = input("Enter the page number for the footer: ") elif choice == 3: # Get user input for number of rows and columns num_cols = int(input("Enter number of columns: ")) # Create empty header and data lists header = [] data = [] # Accept table header from user header_str = input("Enter table header separated by commas: ") header = header_str.split(",") # Accept table data from user while True: row_str = input("Enter table row separated by commas (enter 'done' when finished): ") if row_str.lower() == "done": break else: row = row_str.split(",") data.append(row) # Add the table to the PDF pdf.add_table(header, data) elif choice == 4: text = input("Enter the text: ") pdf.add_text() elif choice == 5: image_file = input("Enter the name of the image file (including extension): ") pdf.add_image() elif choice == 6: pdf.generate_pdf() break else: print("Invalid choice. Please enter a number between 1 and 6.") # Creating File pdf.output('tuto2.pdf')
错误堆栈信息
Enter the name of the image file (including extension): image.jpg Traceback (most recent call last): File "d:\SOFTWARE\PDF in Python\pdf1.py", line 242, in <module> pdf.add_image() File "d:\SOFTWARE\PDF in Python\pdf1.py", line 183, in add_image File "C:\Users\aiena\AppData\Local\Programs\Python\Python311\Lib\site-packages\fpdf\fpdf.py", line 150, in wrapper return fn(self, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\aiena\AppData\Local\Programs\Python\Python311\Lib\site-packages\fpdf\fpdf.py", line 990, in image self.error('Unsupported image type: '+type) File "C:\Users\aiena\AppData\Local\Programs\Python\Python311\Lib\site-packages\fpdf\fpdf.py", line 227, in error raise RuntimeError('FPDF error: '+msg) RuntimeError: FPDF error: Unsupported image type:
错误原因
核心问题是选项5的代码未将用户输入的图片路径赋值给PDF实例的image_file属性:
- 当选择选项5时,代码仅获取了用户输入的
image_file变量,但没有赋值给pdf.image_file - 调用
pdf.add_image()时,self.image_file是空字符串,FPDF无法识别空路径的图片类型,因此抛出错误
此外还有两处潜在问题:
add_image()方法未对self.image_file做非空校验,直接调用image()方法会报错- 未校验图片文件是否存在,若用户输入错误路径也会触发异常
修复方案
1. 修复选项5的赋值逻辑
修改选项5的代码,将用户输入的图片路径赋值给pdf.image_file:
elif choice == 5: pdf.image_file = input("Enter the name of the image file (including extension): ") pdf.add_image()
2. 给add_image()方法添加非空与文件存在校验
增强鲁棒性,避免无效调用:
import os # Add image to the PDF def add_image(self): if not self.image_file: print("Error: No image file specified") return if not os.path.exists(self.image_file): print(f"Error: Image file '{self.image_file}' does not exist") return self.add_page() # Add the image self.image(self.image_file, x=10, y=10, w=190) self.ln()
3. 修复其他无效逻辑
- 移除选项6中不存在的
generate_pdf()调用,直接使用pdf.output() - 修复选项4中未将用户输入文本赋值给
pdf.header_text的问题 - 移除选项2中未使用的
footer_page_number输入逻辑
最终修复后的完整代码
import os from fpdf import FPDF class PDF(FPDF): def __init__(self): super().__init__() self.header_text = "" self.footer_text = "" self.table_data = [] self.table_header = [] self.image_file = "" self.pdf_title = "" # Page header def header(self): if self.image_file: self.image(self.image_file, 80, 25, 50) if self.pdf_title: self.set_font('Arial', 'B', 15) self.cell(80) self.cell(30, 10, self.pdf_title, 0, 0, 'C') self.ln(50) if self.header_text: self.set_font('Arial', 'B', 12) self.cell(0, 10, self.header_text, 0, 0, 'C') self.ln(20) # Add a table to the PDF def add_table(self, header, data): # Set the font and style for the table self.set_font('Arial', '', 10) # Calculate the width of each column and the height of each row col_width = self.w * 0.9 / len(header) row_height = self.font_size * 1.5 # Add the table header for col_number, column_title in enumerate(header): self.cell(col_width, row_height, str(column_title), border=1) self.ln() # Add the table data self.set_font('Arial', '', 10) for row in data: for item in row: self.cell(col_width, row_height, str(item), border=1) self.ln() # Add text to the PDF def add_text(self): self.add_page() # Set the font and style for the text self.set_font('Arial', '', 12) # Add the text self.multi_cell(0, 10, self.header_text) self.ln() # Add image to the PDF def add_image(self): if not self.image_file: print("Error: No image file specified") return if not os.path.exists(self.image_file): print(f"Error: Image file '{self.image_file}' does not exist") return self.add_page() # Add the image self.image(self.image_file, x=10, y=10, w=190) self.ln() # Page footer def footer(self): if self.footer_text: # Position at 1.5 cm from bottom self.set_y(-15) # Arial italic 8 self.set_font('Arial', 'I', 8) # Page number self.cell(0, 10, self.footer_text + ' - Page ' + str(self.page_no()) + '/{nb}', 0, 0, 'C') # Instantiation of inherited class pdf = PDF() # Printing lines on first page pdf.add_page() pdf.set_font('Times', '', 10) # Switch statement while True: print("1. Add page header") print("2. Add page footer") print("3. Add table") print("4. Add text") print("5. Add image") print("6. Generate PDF and exit") choice = int(input("Enter your choice (1-6): ")) if choice == 1: pdf.header_text = input("Enter the header text: ") pdf.image_file = input("Enter the name of the image file (including extension): ") pdf.pdf_title = input("Enter the title for the PDF: ") elif choice == 2: pdf.footer_text = input("Enter the footer text: ") elif choice == 3: # Get user input for number of rows and columns num_cols = int(input("Enter number of columns: ")) # Create empty header and data lists header = [] data = [] # Accept table header from user header_str = input("Enter table header separated by commas: ") header = header_str.split(",") # Accept table data from user while True: row_str = input("Enter table row separated by commas (enter 'done' when finished): ") if row_str.lower() == "done": break else: row = row_str.split(",") data.append(row) # Add the table to the PDF pdf.add_table(header, data) elif choice == 4: pdf.header_text = input("Enter the text: ") pdf.add_text() elif choice == 5: pdf.image_file = input("Enter the name of the image file (including extension): ") pdf.add_image() elif choice == 6: pdf.output('tuto2.pdf') print("PDF generated successfully!") break else: print("Invalid choice. Please enter a number between 1 and 6.")
内容的提问来源于stack exchange,提问作者AIENA JAVED
相关产品推荐
相关产品推荐

