使用 ReportLab 在 PDF 文档中绘制长方形
要使用 ReportLab 生成一个长方形并将其添加到 Story 中生成文档,可以按照以下步骤进行:
-
导入 ReportLab 库中的相关模块:
from reportlab.lib.pagesizes import letter from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer from reportlab.lib import colors from reportlab.lib.styles import getSampleStyleSheet from reportlab.graphics.shapes import Rect -
创建一个空的 Story 列表:
story = [] -
创建一个长方形对象,并设置其属性(如位置、大小、边框颜色等):
rect = Rect(x=100, y=100, width=200, height=100, strokeWidth=1, strokeColor=colors.black) -
将长方形对象添加到 Story 中:
story.append(rect) -
创建文档模板,并将 Story 添加到文档中:
doc = SimpleDocTemplate('rectangle.pdf', pagesize=letter) doc.build(story)
完整代码示例:
from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer
from reportlab.lib import colors
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.graphics.shapes import Rect
# 创建空的 Story 列表
story = []
# 创建长方形对象
rect = Rect(x=100, y=100, width=200, height=100, strokeWidth=1, strokeColor=colors.black)
# 将长方形对象添加到 Story 中
story.append(rect)
# 创建文档模板,并将 Story 添加到文档中
doc = SimpleDocTemplate('rectangle.pdf', pagesize=letter)
doc.build(story)
运行以上代码后,将会生成一个名为'rectangle.pdf'的文档,其中包含了一个长方形。
原文地址: https://www.cveoy.top/t/topic/pZhJ 著作权归作者所有。请勿转载和采集!