How to horizontally center a table? align="CENTER" is not working for me #1304
-
I was wondering how to horizontally center a table on the page? I know about the I have included the code I am using to generate the table below from a pandas dataframe (df) df = df.applymap(str)
COLUMNS = [list(df)]
ROWS = df.values.tolist()
DATA = COLUMNS + ROWS
with self.table(
borders_layout="NONE",
headings_style=FontFace(emphasis="BOLD", color="#000000", fill_color="#ececec"),
cell_fill_color="#ffffff",
cell_fill_mode="EVEN_ROWS",
line_height=self.font_size * 1.5,
text_align=(
"LEFT",
"CENTER",
"CENTER",
"CENTER",
"CENTER",
"CENTER",
"CENTER",
"CENTER",
"CENTER",
"CENTER",
),
col_widths=(190, 70, 70, 70, 70, 70, 70, 70),
align="CENTER"
) as table:
for i, data_row in enumerate(DATA):
# some entries of data_row are conditionally modified here
# in order to ensure the table has the correct data
# the code within this function does not interface with any FPDF code
data_row = modify_data_row()
if i == 0:
table.row(data_row)
else:
table.row(data_row, style=FontFace(color=color, fill_color=fill_color)) |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 5 replies
-
Hi @DerekRobin Thank you for the report. Despite being mentioned in our documentation: https://py-pdf.github.io/fpdf2/Tables.html#setting-table-column-widths
...it seems that this never worked properly... 😅 I tested the following code with from fpdf import FPDF
TABLE_DATA = (
("First name", "Last name", "Age", "City"),
("Jules", "Smith", "34", "San Juan"),
("Mary", "Ramos", "45", "Orlando"),
("Carlson", "Banks", "19", "Los Angeles"),
("Lucas", "Cimon", "31", "Angers"),
)
pdf = FPDF()
pdf.add_page()
pdf.set_font("Times", size=16)
with pdf.table(col_widths=pdf.epw / 5, align="C") as table:
for data_row in TABLE_DATA:
row = table.row()
for datum in data_row:
row.cell(datum)
pdf.output("./test/table/table_with_fixed_col_width_and_align.pdf") ...and the table is NOT horizontally centered on the page! Wooops. I'm converting this discussion into a bug report, and I will look into fix it: |
Beta Was this translation helpful? Give feedback.
-
Hey @Lucas-C, thanks for the fix! I have tested the code and it seems to work for other tables in my document except for the tables created by the code I provided above, which is very strange. I believe that it has something to do with the fact that the tables created by this code can have a max of 8 columns but may have less. Although this is just a hunch and isn't back by anything. |
Beta Was this translation helpful? Give feedback.
Hi @DerekRobin
Thank you for the report.
Despite being mentioned in our documentation: https://py-pdf.github.io/fpdf2/Tables.html#setting-table-column-widths
...it seems that this never worked properly... 😅
I tested the following code with
fpdf2
version 2.7.0, where tables were originally introduced in this documentation was redacted: