FPDF2中pdf.table无法设置X轴位置,仅Y轴生效,如何实现任意定位?
解决fpdf表格X轴定位无效的问题
问题原因
fpdf2的table组件默认遵循文本流排版逻辑:默认左对齐,若当前x位置加上表格宽度超出页面可用宽度,表格会自动换行到下一行的起始位置(左侧边距处),导致set_x()/set_xy()的X参数看似无效。
解决方案
方法1:直接使用table的x/y参数(推荐,fpdf2 2.5.0+支持)
从fpdf2 v2.5.0开始,table()方法新增了x和y参数,可直接指定表格左上角的坐标,无需依赖set_x/set_xy:
from fpdf import FPDF data = ( ("First name", "Last name", "Age", "City"), ("Jules", "Smith", "34", "San Juan"), ("Mary", "Ramos", "45", "Orlando"), ("Carlson", "Banks", "19", "Los Angeles"), ("Lucas", "Cimon", "31", "Saint-Mathurin-sur-Loire"), ) pdf = FPDF(orientation='L') # 横向页面避免X坐标超出范围,按需调整 pdf.set_font("helvetica", size=8) pdf.add_page() with pdf.table( line_height=6, width=60, x=230, # 直接设置表格左上角X坐标 y=80 # 直接设置表格左上角Y坐标 ) as table: for data_row in data: row = table.row() for datum in data_row: row.cell(datum) pdf.output("tuto5.pdf")
方法2:手动计算位置+对齐参数(兼容旧版本)
如果你的fpdf2版本低于2.5.0,可通过计算位置结合align参数实现定位:
- 若要让表格左边缘在
target_x,设置align='RIGHT',并将当前X位置设为target_x + 表格宽度,这样表格右边缘会对齐到该位置,左边缘自然落在target_x:
from fpdf import FPDF data = ( ("First name", "Last name", "Age", "City"), ("Jules", "Smith", "34", "San Juan"), ("Mary", "Ramos", "45", "Orlando"), ("Carlson", "Banks", "19", "Los Angeles"), ("Lucas", "Cimon", "31", "Saint-Mathurin-sur-Loire"), ) pdf = FPDF(orientation='L') pdf.set_font("helvetica", size=8) pdf.add_page() table_width = 60 target_x = 230 # 设置X坐标为目标左边缘+表格宽度,配合右对齐实现定位 pdf.set_xy(target_x + table_width, 80) with pdf.table( line_height=6, width=table_width, align='RIGHT' ) as table: for data_row in data: row = table.row() for datum in data_row: row.cell(datum) pdf.output("tuto5.pdf")
内容的提问来源于stack exchange,提问作者Alex Felipe
相关产品推荐
相关产品推荐

