我使用Reportlab复现这个表单的方法正确吗?

1 投票
3 回答
956 浏览
提问于 2025-04-15 22:09

我需要用Python和reportlab生成这里看到的表单。

http://www.flickr.com/photos/49740282@N06/4563137758/sizes/o/

我打算通过创建一个自定义的可流动组件来制作顶部的标题(带有绘制的框框),然后在下面放一个表格组件来显示珠宝的内容。这个例子中的珠宝表可能会有多个表格。我在让我的绘制标题“流动”时遇到了问题。它是被绘制出来了,但我的表格数据却覆盖在上面,而不是出现在下面。

这是我第一次使用reportlab。在我真正开始调试之前,我想先问问有reportlab经验的人,我的做法是否正确。谢谢!

3 个回答

0

我同意 dugres 的看法,对于在 Flickr 上展示的那个表单,你不需要什么特别的可定制的流程。你只需要使用表格和表格样式就能完成你的工作。

在你深入研究 reportlab 之前,有几点需要考虑:你的表格不要太长,否则会跑到下一页。这样的话,表格样式就需要手动调整。下一页的表格中的合并单元格会出错。不过,如果只是做一个单页的解决方案,使用 reportpdf 是个不错的选择。

如果想要更炫的输出效果,漂亮的图形效果,你需要按照 dugres 的建议去做。

下面是一个关于如何开发表格的入门代码:

from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import A4, cm
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.platypus import Paragraph, Table, TableStyle
from reportlab.lib.enums import TA_JUSTIFY, TA_LEFT, TA_CENTER
from reportlab.lib import colors

width, height = A4
styles = getSampleStyleSheet()
styleN = styles["BodyText"]
styleN.alignment = TA_LEFT
styleBH = styles["Normal"]
styleBH.alignment = TA_CENTER

def coord(x, y, unit=1):
    x, y = x * unit, height -  y * unit
    return x, y

# Headers
hdescrpcion = Paragraph('''<b>descrpcion</b>''', styleBH)
hpartida = Paragraph('''<b>partida</b>''', styleBH)
hcandidad = Paragraph('''<b>candidad</b>''', styleBH)
hprecio_unitario = Paragraph('''<b>precio_unitario</b>''', styleBH)
hprecio_total = Paragraph('''<b>precio_total</b>''', styleBH)

# Texts
descrpcion = Paragraph('long paragraph', styleBH)
partida = Paragraph('1', styleN)
candidad = Paragraph('120', styleN)
precio_unitario = Paragraph('$52.00', styleN)
precio_total = Paragraph('$6240.00', styleN)

data= [[hdescrpcion, hcandidad,hcandidad, hprecio_unitario, hprecio_total],
       [partida, candidad, descrpcion, precio_unitario, precio_total]]

table = Table(data, colWidths=[2.05 * cm, 2.7 * cm, 5 * cm,
                               3* cm, 3 * cm])

table.setStyle(TableStyle([
                       ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),
                       ('BOX', (0,0), (-1,-1), 0.25, colors.black),
                       ]))

c = canvas.Canvas("a.pdf", pagesize=A4)
table.wrapOn(c, width, height)
table.drawOn(c, *coord(1.8, 9.6, cm))
c.save()
0

我觉得这里没有必要使用自定义的可流动元素。

你可以直接用表格(和表格样式)来做“标题”。

如果你想要一些特别的背景,另一个简单的办法是先画一张图片(比如 JPG 格式),然后再在上面写上你需要的文字。

-1

我对reportlab不太熟悉,所以帮不了你(我之前用它遇到了一些问题,搞得我很头疼,所以放弃了)。不过,如果你考虑用其他工具来生成Python中的PDF,我建议你看看xhtml2pdf。如果你在使用reportlab的过程中没有走得太远,这可能是个不错的选择。如果你对HTML有点了解,使用起来可能会更简单。这个工具的原理很简单:它会把你提供的HTML转换成PDF文件。当然,你需要先生成一些HTML代码(我通常用django模板来做这件事)。

撰写回答