无法将“可流动”单元格的表写入PDF

1 投票
1 回答
2242 浏览
提问于 2025-04-17 19:20

我有以下代码。我想让它变得更灵活,具体来说:
- 我不想手动设置单元格的宽度
- HTML单元格应该是“可流动”的,也就是说,单元格的长度会根据数据的大小自动调整。还要支持“自动换行”
- 列的数量可以变化
- 我可以从数据库表中获取数据,把它转换成HTML,然后把表格写入PDF中

我尝试过搜索,发现PyFDF似乎支持这个功能,http://python.6.n6.nabble.com/PyFPDF-1-54b-HTML-rendering-templates-and-web2py-integration-td2120415.html,但看起来我必须使用web2py。有没有办法不使用网络框架就能做到这一点?

import fpdf as pyfpdf
from fpdf import FPDF, HTMLMixin

class MyFPDF(FPDF, HTMLMixin):
    pass

pdf=MyFPDF()

#First page
#pdf = pyfpdf.FPDF(format='letter')
pdf.add_page()
#set the font
pdf.set_font("Arial", size=10)

#define the html text
html = """<H1 align="center">Summary of Transactions</H1>
<h3>Date:</h3>
<h3>Branch:</h3>"""
html += """
<table border="1" align="center" width="100%">
<thead><tr><th width="20%">Date of Transaction</th><th width="20%">Name of Customer</th><th width="20%">Address</th><th width="20%">Contact Number</th><th width="20%">Status</th></tr></thead>
<tbody>
<tr><td>cell 1hgjhh jhjhjk jhjfsafsafsafsaf</td><td>cell 2</td><td>cell 3</td><td>cell 4</td><td>cell 5</td></tr>
<tr><td>cell 1</td><td>cell 2</td><td>cell 3</td><td>cell 4</td><td>cell 5</td></tr>
"""
html += '<tr><td>' + 'data' + '</td><td>' + 'data' +'</td> <td>' + 'data' +'</td> <td>' + 'data' +'</td><td>' + 'data' +'</td></tr>'
html += """</tbody></table>"""

#write the html text to PDF
pdf.write_html(html)
pdf.output('html.pdf','F')

我想实现的效果类似于这里的listings.pdf演示 https://code.google.com/p/pyfpdf/wiki/Web2Py

1 个回答

0

我不确定这是否有帮助,但你可以看看 PyfPDF 模板

撰写回答