|
| 1 | +# Tables # |
| 2 | + |
| 3 | +Tables can be built either using **cells** |
| 4 | +or with [`write_html`](HTML.html). |
| 5 | + |
| 6 | + |
| 7 | +## Using cells ## |
| 8 | + |
| 9 | +There is a method to build tables allowing for multilines content in cells: |
| 10 | + |
| 11 | +```python |
| 12 | +from fpdf import FPDF |
| 13 | + |
| 14 | +data = ( |
| 15 | + ("First name", "Last name", "Age", "City"), |
| 16 | + ("Jules", "Smith", "34", "San Juan"), |
| 17 | + ("Mary", "Ramos", "45", "Orlando"), |
| 18 | + ("Carlson", "Banks", "19", "Los Angeles"), |
| 19 | + ("Lucas", "Cimon", "31", "Saint-Mahturin-sur-Loire"), |
| 20 | +) |
| 21 | + |
| 22 | +pdf = FPDF() |
| 23 | +pdf.add_page() |
| 24 | +pdf.set_font("Times", size=10) |
| 25 | +line_height = pdf.font_size * 2.5 |
| 26 | +col_width = pdf.epw / 4 # distribute content evenly |
| 27 | +for row in data: |
| 28 | + for datum in row: |
| 29 | + pdf.multi_cell(col_width, line_height, datum, border=1, ln=3, max_line_height=pdf.font_size) |
| 30 | + pdf.ln(line_height) |
| 31 | +pdf.output('table_with_cells.pdf') |
| 32 | +``` |
| 33 | + |
| 34 | + |
| 35 | +## Using write_html ## |
| 36 | + |
| 37 | +An alternative method using [`fpdf.HTMLMixin`](HTML.html), |
| 38 | +with the same `data` as above, and column widths defined as percent of the effective width: |
| 39 | + |
| 40 | +```python |
| 41 | +from fpdf import FPDF, HTMLMixin |
| 42 | + |
| 43 | +class PDF(FPDF, HTMLMixin): |
| 44 | + pass |
| 45 | + |
| 46 | +pdf = PDF() |
| 47 | +pdf.set_font_size(16) |
| 48 | +pdf.add_page() |
| 49 | +pdf.write_html( |
| 50 | + f"""<table border="1"><thead><tr> |
| 51 | + <th width="25%">{data[0][0]}</th> |
| 52 | + <th width="25%">{data[0][1]}</th> |
| 53 | + <th width="15%">{data[0][2]}</th> |
| 54 | + <th width="35%">{data[0][3]}</th> |
| 55 | +</tr></thead><tbody><tr> |
| 56 | + <td>{'</td><td>'.join(data[1])}</td> |
| 57 | +</tr><tr> |
| 58 | + <td>{'</td><td>'.join(data[2])}</td> |
| 59 | +</tr><tr> |
| 60 | + <td>{'</td><td>'.join(data[3])}</td> |
| 61 | +</tr><tr> |
| 62 | + <td>{'</td><td>'.join(data[4])}</td> |
| 63 | +</tr></tbody></table>""", |
| 64 | + table_line_separators=True, |
| 65 | +) |
| 66 | +pdf.output('table_html.pdf') |
| 67 | +``` |
0 commit comments