我的问题是如何在reportlab表中正确显示中文
我写下定义:
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.platypus import SimpleDocTemplate, Table
def df_2_pdf(df, fp_pdf):
# Create a PDF document
pdf_filename = fp_pdf
doc = SimpleDocTemplate(pdf_filename)
# Load the "simhei" font
pdfmetrics.registerFont(TTFont('msyh', r'C:\Windows\Fonts\msyh.ttc'))
# Convert the DataFrame to a list of lists (table data)
table_data = [df.columns] + df.values.tolist()
# Create a Table object and set its properties
table = Table(table_data)
table.setStyle([
('TEXTCOLOR', (0, 0), (-1, 0), (0, 0, 1)), # Header row text color
('ALIGN', (0, 0), (-1, -1), 'CENTER'), # Center alignment
('FONTNAME', (0, 0), (-1, 0), 'msyh'), # Use the "simhei" font for the header
('BOTTOMPADDING', (0, 0), (-1, 0), 12), # Header padding
('BACKGROUND', (0, 0), (-1, 0), (0.9, 0.9, 0.9)) # Header background color
])
# Build the PDF document
doc.build([table])
print(f"PDF file '{pdf_filename}' has been created with the DataFrame.")