【问题标题】:Python reportlab not generating pdf properlyPython reportlab 无法正确生成 pdf
【发布时间】:2014-01-30 14:38:17
【问题描述】:

我正在尝试生成一个 pdf,它将打印字体大小和一个句子。但是在生成pdf之后,它是重叠的。

from reportlab.lib.units import inch
from reportlab.lib.colors import magenta, red
from reportlab.pdfgen import canvas

lyrics = ['This is first line', 'This is second line', 'This is third line', 'This is the fourth line', 'This is the fifth line']

def textsize(canvas):
    canvas.setFont('Times-Roman', 20)
    canvas.setFillColor(red)
    canvas.drawCentredString(2.75*inch, 2.5*inch, "Font Size examples")
    canvas.setFillColor(magenta)

    size = 7
    y = 2.3 * inch
    x = 1.3 * inch
    for line in lyrics:
        canvas.setFont('Helvetica', size)
    canvas.drawString(x, y, '%s points' % size)
    canvas.drawString(x, y, line)
    y = y - (size * 1.2)
    size = size + 1.5

c = canvas.Canvas('font.pdf')
textsize(c)
c.showPage()
c.save()

【问题讨论】:

    标签: python reportlab


    【解决方案1】:

    你有错误的缩进,drawString的第二行导致重叠。

    from reportlab.lib.units import inch
    from reportlab.lib.colors import magenta, red
    from reportlab.pdfgen import canvas
    
    lyrics = ['This is first line', 'This is second line', 'This is third line', 'This is the fourth line', 'This is the fifth line']
    
    def textsize(canvas):
        canvas.setFont('Times-Roman', 20)
        canvas.setFillColor(red)
        canvas.drawCentredString(2.75*inch, 2.5*inch, "Font Size examples")
        canvas.setFillColor(magenta)
    
        size = 7
        y = 2.3 * inch
        x = 1.3 * inch
        for line in lyrics:
            canvas.setFont('Helvetica', size)
            canvas.drawString(x, y, '%s points' % size)
            print x, y, line
            canvas.drawString(x + 2*inch, y, line)
            y = y - (size * 1.2)
            size = size + 1.5
    
    c = canvas.Canvas('font.pdf')
    textsize( c )
    c.showPage()
    c.save()
    

    【讨论】:

    • 如果我们评论该行,它不会打印列表中的数据。在您的代码之后,它只会打印大小。不是列表歌词的内容
    • 所以只需在第一个drawString中将歌词添加到文本中
    • drawString 采用 3 个参数,因此不会在第一个 drawString 上传递。我们必须写 2 个 drawString 首先将打印大小,第二个将打印列表中的内容。你能告诉你改变的确切位置吗?
    猜你喜欢
    • 2017-03-17
    • 1970-01-01
    • 2020-07-12
    • 1970-01-01
    • 2018-07-28
    • 1970-01-01
    • 2018-01-18
    • 1970-01-01
    • 2016-03-14
    相关资源
    最近更新 更多