准备:
python:3.6.8
reportlab:3.6.8
问题1:用reportlab生成pdf文件,中文就会变成黑色的小方块
解决:
1.下载中文字体SimSun.ttf/SimSun-Bold.ttf
2.把下载下来的字体放到解释器目录site-packages/reportlab/fonts文件夹下。(文件夹根据自己安装的reportlab的路径来)
3.注册字体并使用
pdfmetrics.registerFont(TTFont('SimSun', 'SimSun.ttf')) # 中文字体
pdfmetrics.registerFont(TTFont('SimSun-Bold', 'SimSun-Bold.ttf')) # 中文加粗字体
问题2:使用Table制作单元格,设置表格固定总宽度,单元格文本自动换行
针对这个问题查找了很多资料,大部分都是使用
WORDWRAP
参数,但经过尝试没有效果。('WORDWRAP', (1, 1), (-1, -1), True) # 设置自动换行
- 解决:
将文字包装在样式 [“BodyText”] 中,这将允许您的文本根据您指定的单元格宽度自行对齐。您还可以包括类似于 HTML 文本格式的格式。 然后使用 TableStyle 对表格中的内容进行格式化,例如,彩色文本、居中段落、跨行/列等。
from reportlab.lib import colors
from reportlab.lib.pagesizes import landscape, A4
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.lib.units import cm, inch
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.platypus import Paragraph, Table, SimpleDocTemplate
pdf = SimpleDocTemplate('report.pdf', pagesize=landscape(A4), topMargin=0.3 * inch,
bottomMargin=0.3 * inch, leftMargin=1 * inch, rightMargin=1 * inch)
content = list() # 创建内容对应的空列表
pdfmetrics.registerFont(TTFont('SimSun', 'SimSun.ttf')) # 注册中文字体
pdfmetrics.registerFont(TTFont('SimSun-Bold', 'SimSun-Bold.ttf')) # 注册中文加粗字体
styles = getSampleStyleSheet()
styleN = styles["BodyText"]
styleN.fontName = 'SimSun-Bold' # 中文加粗字体
styleN.fontSize = 7 # 字体大小
styleN.alignment = 1 # 居中
table_data = [
["姓名", "年龄", "性别"],
]
# 关键,列宽度
col_width = [1.5 * cm, 1.3 * cm, 1.3 * cm]
# 关键,使用文本方式作为单元格内容
data_list = [Paragraph("李四", styleN), Paragraph("18", styleN), Paragraph("男", styleN)]
table_data.append(data_list)
style = [
('FONTNAME', (0, 0), (-1, -1), 'SimSun-Bold'), # 字体
('FONTSIZE', (0, 0), (-1, -1), 7), # 第一行的字体大小
('ALIGN', (0, 0), (-1, -1), 'CENTER'), # 第一行水平居中
('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), # 所有表格上下居中对齐
('GRID', (0, 0), (-1, -1), 0.5, colors.black), # 设置表格框线为grey色,线宽为0.5
]
table = Table(table_data, colWidths=col_width, style=style)
content.append(table)
pdf.build(content)
问题3:单元格下边框设置
使用
WORDWRAP
参数,但经过尝试没有效果。
('BOX', (0, 0), (-1, 0), 1, colors.black, True) # 仅在第一行绘制下框线
- 解决:暂时未解决