Python生成PDF:Reportlab的六种使用方式
Reportlab是Python创建PDF文档的功能库
这里是整理过的六种Reportlab使用方式,主要参考的是《ReportLab User Guide》
一、使用文档模板DocTemplate
Reportlab的基础使用方式是创建内容块(Flowable),再使用文档模板(DocTemplate)创建Pdf文档。
关注点:
- Paragraph(段落)
- Image(图像)
- Table(表格)
- VerticalBarChart(柱形图表)
from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont from reportlab.lib.styles import getSampleStyleSheet from reportlab.platypus import Paragraph, SimpleDocTemplate, Image, Table from reportlab.platypus import Spacer from reportlab.graphics.shapes import Drawing from reportlab.graphics.charts.barcharts import VerticalBarChart from reportlab.graphics.charts.legends import Legend from reportlab.lib import colors from reportlab.lib.pagesizes import A4 from reportlab.lib.units import cm def draw_text(st, text: str): return Paragraph(text, st) def draw_img(path): img = Image(path) # 读取指定路径下的图片 img.drawWidth = 6*cm # 设置图片的宽度 img.drawHeight = 5*cm # 设置图片的高度 return img def draw_table(*args): col_width = 120 style = [ ("FONTNAME", (0, 0), (-1, -1), "song"), # 字体 ("FONTSIZE", (0, 0), (-1, 0), 12), # 第一行的字体大小 ("FONTSIZE", (0, 1), (-1, -1), 10), # 第二行到最后一行的字体大小 ("BACKGROUND", (0, 0), (-1, 0), "#d5dae6"), # 设置第一行背景颜色 ("ALIGN", (0, 0), (-1, -1), "CENTER"), # 第一行水平居中 ("ALIGN", (0, 1), (-1, -1), "LEFT"), # 第二行到最后一行左右左对齐 ("VALIGN", (0, 0), (-1, -1), "MIDDLE"), # 所有表格上下居中对齐 ("TEXTCOLOR", (0, 0), (-1, -1), colors.darkslategray), # 设置表格内文字颜色 ("GRID", (0, 0), (-1, -1), 0.5, colors.grey), # 设置表格框线为grey色,线宽为0.5 ("SPAN", (0, 1), (2, 1)), # 合并第二行一二三列 ] table = Table(args, colWidths=col_width, style=style) return table def draw_bar(bar_data: list, ax: list, items: list): drawing = Drawing(500, 200) bc = VerticalBarChart() bc.x = 45 # 整个图表的x坐标 bc.y = 45 # 整个图表的y坐标 bc.height = 150 # 图表的高度 bc.width = 350 # 图表的宽度 bc.data = bar_data bc.strokeColor = colors.black # 顶部和右边轴线的颜色 bc.valueAxis.valueMin = 0 # 设置y坐标的最小值 bc.valueAxis.valueMax = 20 # 设置y坐标的最大值 bc.valueAxis.valueStep = 5 # 设置y坐标的步长 bc.categoryAxis.labels.dx = 2 bc.categoryAxis.labels.dy = -8 bc.categoryAxis.labels.angle = 20 bc.categoryAxis.labels.fontName = "song" bc.categoryAxis.categoryNames = ax # 图示 leg = Legend() leg.fontName = "song" leg.alignment = "right" leg.boxAnchor = "ne" leg.x = 475 # 图例的x坐标 leg.y = 140 leg.dxTextSpace = 10 leg.columnMaximum = 3 leg.colorNamePairs = items drawing.add(leg) drawing.add(bc) return drawing