如何使用Reportlab在单个段落中添加行间距

2024-09-22 16:36:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个文本块,它是从数据库中动态提取的,在被服务给用户之前放在PDF中。文本被放置在有线条的背景上,就像记事本一样。我想将文本隔开,以便在每个背景行之间只有一行文本。

我能够使用以下代码在段落之间创建垂直间距(用于生成PDF的另一部分)。

    style = getSampleStyleSheet()['Normal']
    style.fontName = 'Helvetica'
    style.spaceAfter = 15
    style.alignment = TA_JUSTIFY

    story = [Paragraph(choice.value,style) for choice in chain(context['question1'].itervalues(),context['question2'].itervalues())]
    generated_file = StringIO()
    frame1 = Frame(50,100,245,240, showBoundary=0)
    frame2 = Frame(320,100,245,240, showBoundary=0)
    page_template = PageTemplate(frames=[frame1,frame2])
    doc = BaseDocTemplate(generated_file,pageTemplates=[page_template])
    doc.build(story)

但是,这里不起作用,因为我只有一个大段落。


Tags: 文本pdfstylecontextframegeneratedfile段落
2条回答

很确定你想改变的是领先。从第6章的用户手册。

To get double-spaced text, use a high leading. If you set autoLeading(default "off") to "min"(use observed leading even if smaller than specified) or "max"(use the larger of observed and specified) then an attempt is made to determine the leading on a line by line basis. This may be useful if the lines contain different font sizes etc.

前导的定义见第2章:

Interline spacing (Leading)

The vertical offset between the point at which one line starts and where the next starts is called the leading offset.

因此,尝试不同的前导值,例如:

style = getSampleStyleSheet()['Normal']
style.leading = 24

添加前导到段落样式

orden = ParagraphStyle('orden')
orden.leading = 14
orden.borderPadding = 10
orden.backColor=colors.gray
orden.fontSize = 14

生成PDF

buffer = BytesIO()
p = canvas.Canvas(buffer, pagesize=letter)

text = Paragraph("TEXT Nro 0001", orden)
text.wrapOn(p,500,10)
text.drawOn(p, 45, 200)


p.showPage()
p.save()
pdf = buffer.getvalue()
buffer.close()

结果 enter image description here

相关问题 更多 >