fpdf2 多单元格长字符串问题,单元格无法调整大小
我对 fpdf2 lib 有问题, 我有一长串文本想要放入单元格中,但单元格无法调整大小。
from fpdf import FPDF
data = (
("First name", "Last name", "Age", "Cities"),
("Jules", "Smith", "34", "Warsaw, New York, Sydney, Berlin, Moscow, Washington, Hamburg, Monachium, Lipsk, Essen, Dresno, Bonn, Hannover, Stuttgart, Rome, San Diego, Los Angeles"),
("Mary", "Ramos", "45", "Orlando"),
("Carlson", "Banks", "19", "Los Angeles"),
("Lucas", "Cimon", "31", "Saint-Mahturin-sur-Loire"),
)
pdf = FPDF()
pdf.add_page()
pdf.set_font("Times", size=10)
line_height = pdf.font_size * 2.5
col_width = pdf.epw / 4 # distribute content evenly
for row in data:
for datum in row:
pdf.multi_cell(col_width, line_height, datum, border=1, ln=3, max_line_height=pdf.font_size)
pdf.ln(line_height)
pdf.output('table_with_cells.pdf')
I Have problem with fpdf2 lib,
I have a long string of text that I want to fit into a cell, but cell not going resize.
result of bad multicell processing
from fpdf import FPDF
data = (
("First name", "Last name", "Age", "Cities"),
("Jules", "Smith", "34", "Warsaw, New York, Sydney, Berlin, Moscow, Washington, Hamburg, Monachium, Lipsk, Essen, Dresno, Bonn, Hannover, Stuttgart, Rome, San Diego, Los Angeles"),
("Mary", "Ramos", "45", "Orlando"),
("Carlson", "Banks", "19", "Los Angeles"),
("Lucas", "Cimon", "31", "Saint-Mahturin-sur-Loire"),
)
pdf = FPDF()
pdf.add_page()
pdf.set_font("Times", size=10)
line_height = pdf.font_size * 2.5
col_width = pdf.epw / 4 # distribute content evenly
for row in data:
for datum in row:
pdf.multi_cell(col_width, line_height, datum, border=1, ln=3, max_line_height=pdf.font_size)
pdf.ln(line_height)
pdf.output('table_with_cells.pdf')
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
据我发现,库中没有解决方案,但我写了这个小解决方法。
输入稍微更改为 pandas DataFrame。
该解决方案根据行中字符串的最大长度和提供的列宽度来估计每行需要多少行。
不幸的是,字母没有固定的宽度。我用字体大小 * 0.6 估计宽度。您可能想根据您使用的字体来尝试它。
There is no solution in the library as far as I found, but I wrote this little workaround.
The input is slightly changed to a pandas DataFrame.
The solution estimates for each row how many lines it is going to need based on the maximum length of the strings in the row and a provided column width.
Unfortunately, letters don't have a fixed width. I estimate the width with font size * 0.6. You might want to play around with it based on what font you use.