python reportlab表格显示中文

问题描述 投票:0回答:1

我的问题是如何在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.")

所以,它正确显示了英文。但是,它不能显示中文。 这是一张照片。

python pdf reportlab
1个回答
0
投票

嗯,经过一番研究,我发现了问题所在。

('FONTNAME', (0, 0), (-1, -1), 'msyh'),  # Use the "Microsoft YaHei" font for the header

基本上,二元组是为我放置汉字的区域设置字体“msyh”。 这是结果:

© www.soinside.com 2019 - 2024. All rights reserved.