Python-如何更改PDF表中的列宽度以适合所有内容?
如何更改以下代码中表的列宽度以适合所有文本?第一列需要大于第二行和第三行。目前,列宽度分布均匀。
代码:
from fpdf import FPDF
pdf = FPDF()
alfa = 5
lasna = 5
pdf.add_page()
pdf.set_font("Times", size = 16)
TABLE_COL_NAMES = ("Propriedade", "Valor", "Unidade")
TABLE_DATA = (
("Ângulo da vertente", str(alfa), "º"),
("Comprimento de cada asna", str(lasna), "m"),
)
pdf.set_font("Times", size=16)
line_height = pdf.font_size * 2
col_width = pdf.epw / 4 # distribute content evenly
def render_table_header():
pdf.set_font(style="B") # enabling bold text
for col_name in TABLE_COL_NAMES:
pdf.cell(col_width, line_height, col_name, border=1)
pdf.ln(line_height)
pdf.set_font(style="") # disabling bold text
render_table_header()
for _ in range(1): # repeat data rows
for row in TABLE_DATA:
if pdf.will_page_break(line_height):
render_table_header()
for datum in row:
pdf.cell(col_width, line_height, datum, border=1)
pdf.ln(line_height)
pdf.output("Relatório_TED.pdf")
How can I change the columns width of the tables in the code below in order to fit all text? The first column needs to be larger than the second and third row. For now the columns width is distributed evenly.
Code:
from fpdf import FPDF
pdf = FPDF()
alfa = 5
lasna = 5
pdf.add_page()
pdf.set_font("Times", size = 16)
TABLE_COL_NAMES = ("Propriedade", "Valor", "Unidade")
TABLE_DATA = (
("Ângulo da vertente", str(alfa), "º"),
("Comprimento de cada asna", str(lasna), "m"),
)
pdf.set_font("Times", size=16)
line_height = pdf.font_size * 2
col_width = pdf.epw / 4 # distribute content evenly
def render_table_header():
pdf.set_font(style="B") # enabling bold text
for col_name in TABLE_COL_NAMES:
pdf.cell(col_width, line_height, col_name, border=1)
pdf.ln(line_height)
pdf.set_font(style="") # disabling bold text
render_table_header()
for _ in range(1): # repeat data rows
for row in TABLE_DATA:
if pdf.will_page_break(line_height):
render_table_header()
for datum in row:
pdf.cell(col_width, line_height, datum, border=1)
pdf.ln(line_height)
pdf.output("Relatório_TED.pdf")
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您将需要弄清每列的最长宽度是什么,然后可以使用flpdf内置的功能
getTringWidth来计算每列的最大宽度。
只有主要问题是处理情况,如果将所有3列宽度在一起的情况少于分配的空间,则您需要在每列之间添加一个缓冲区,而Vise Versa如果所有3列宽度都太宽,则需要vise。然后,您将需要弄清楚在这种情况下该怎么做。
文档 - > http://www.fpdf.org/en/en/en/doc/doc/getStringwidth.htm
You will need to figure out what is the longest width of each column and then you can use the FPDF built in function
getstringwidth to calculate the max width of each column is required.
only major issue would be to deal with situation where if all 3 columns width together is less then the allocated space you will need to add a buffer between each column, and vise versa if the column width of all 3 together is too wide for the pdf then you will need to figure out what to do in those situation.
Documentation - > http://www.fpdf.org/en/doc/getstringwidth.htm