File: Tables.md

package info (click to toggle)
fpdf2 2.8.4-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 53,828 kB
  • sloc: python: 39,486; sh: 133; makefile: 12
file content (648 lines) | stat: -rw-r--r-- 17,291 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
# Tables

_New in [:octicons-tag-24: 2.7.0](https://github.com/py-pdf/fpdf2/blob/master/CHANGELOG.md)_

Tables can be built using the `table()` method.
Here is a simple example:

```python
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() as table:
    for data_row in TABLE_DATA:
        row = table.row()
        for datum in data_row:
            row.cell(datum)
pdf.output('table.pdf')
```

Result:

![](table-simple.jpg)

## Features

* support cells with content wrapping over several lines
* control over column & row sizes (automatically computed by default)
* allow to style table headings (top row), or disable them
* control over borders: color, width & where they are drawn
* handle splitting a table over page breaks, with headings repeated
* control over cell background color
* control over cell borders
* control table width & position
* control over text alignment in cells, globally or per row
* allow to embed images in cells
* merge cells across columns and rows

## Setting table & column widths
The `col_widths` optional parameter can be provided to configure this.

If a **single number** is provided as `col_widths`, it is interpreted as a **fixed column width in document units**.

If an **array of numbers** is provided as `col_widths`, the values are considered to be **fractions of the full effective page width**, meaning that `col_widths=(1, 1, 2)` is strictly equivalent to `col_widths=(25, 25, 50)`.

```python
...
with pdf.table(width=150, col_widths=(30, 30, 10, 30)) as table:
    ...
```

Result:

![](table-with-fixed-column-widths.jpg)

`align` can be passed to `table()` to set the table horizontal position relative to the page,
when it's not using the full page width. It's centered by default.

## Setting text alignment

This can be set globally, or on a per-column basis:

```python
...
with pdf.table(text_align="CENTER") as table:
    ...
pdf.ln()
with pdf.table(text_align=("CENTER", "CENTER", "RIGHT", "LEFT")) as table:
    ...
```

Result:

![](table_align.jpg)

## Setting cell padding

_New in [:octicons-tag-24: 2.7.6](https://github.com/PyFPDF/fpdf2/blob/master/CHANGELOG.md)_

Cell padding (the space between the cells content and the edge of the cell) can be set globally or on a per-cell basis.

Following the CCS standard the padding can be specified using 1,2 3 or 4 values.

- When one value is specified, it applies the same padding to all four sides.
- When two values are specified, the first padding applies to the top and bottom, the second to the left and right.
- When three values are specified, the first padding applies to the top, the second to the right and left, the third to
  the bottom.
- When four values are specified, the paddings apply to the top, right, bottom, and left in that order (clockwise)

```python
    ...
red = (255, 0, 0)
style = FontFace(color=black, fill_color=red)
with pdf.table(line_height=pdf.font_size, padding=2) as table:
    for irow in range(5):
        row = table.row()
        for icol in range(5):
            datum = "Circus"
            if irow == 3 and icol % 2 == 0:
                row.cell("custom padding", style=style, padding=(2 * icol, 8, 8, 8))
            else:
                row.cell(datum)
```

(also an example of coloring individual cells)

![img.png](img_table_padding.png)

Note: the `c_margin` parameter (default 1.0) also controls the horizontal margins in a cell. If a non-zero padding for
left and right is supplied then c_margin is ignored.

## Setting vertical alignment of text in cells

_New in [:octicons-tag-24: 2.7.6](https://github.com/PyFPDF/fpdf2/blob/master/CHANGELOG.md)_

Can be set globally, per row or per cell, by passing a string or a [VAlign](https://py-pdf.github.io/fpdf2/fpdf/enums.html#fpdf.enums.VAlign) enum value as `v_align`:
```python
...
with pdf.table(v_align=VAlign.M) as table:
    ...
    row.cell(f"custom v-align", v_align="TOP")
```

## Setting row height
First, `line_height` can be provided to set the height of every individual line of text:
```python
...
with pdf.table(line_height=2.5 * pdf.font_size) as table:
    ...
```

_New in [:octicons-tag-24: 2.8.3](https://github.com/py-pdf/fpdf2/blob/master/CHANGELOG.md)_

Second, a global `min_row_height` can be set,
or configured per row as `min_height`:
```python
...
with pdf.table(min_row_height=30) as table:
    row = table.row()
    row.cell("A")
    row.cell("B")
    row = table.row(min_height=50)
    row.cell("C")
    row.cell("D")
```

## Disable table headings

By default, `fpdf2` considers that the first row of tables contains its headings.
This can however be disabled:

```python
...
with pdf.table(first_row_as_headings=False) as table:
    ...
```

_New in [:octicons-tag-24: 2.7.9](https://github.com/py-pdf/fpdf2/blob/master/CHANGELOG.md)_

The **repetition** of table headings on every page can also be disabled:

```python
...
with pdf.table(repeat_headings=0) as table:
    ...
```

`"ON_TOP_OF_EVERY_PAGE"` is an equivalent valid value for `repeat_headings`
, _cf._ [documentation on `TableHeadingsDisplay`](https://py-pdf.github.io/fpdf2/fpdf/enums.html#fpdf.enums.TableHeadingsDisplay).

## Style table headings

```python
from fpdf.fonts import FontFace

...
blue = (0, 0, 255)
grey = (128, 128, 128)
headings_style = FontFace(emphasis="ITALICS", color=blue, fill_color=grey)
with pdf.table(headings_style=headings_style) as table:
    ...
```

Result:

![](table-styled.jpg)

It's possible to override the style of individual cells in the heading. The overriding style will take
precedence for any specified values, while retaining the default style for unspecified values:
```python
...
headings_style = FontFace(emphasis="ITALICS", color=blue, fill_color=grey)
override_style = FontFace(emphasis="BOLD")
with pdf.table(headings_style=headings_style) as table:
    headings = table.row()
    headings.cell("First name", style=override_style)
    headings.cell("Last name", style=override_style)
    headings.cell("Age")
    headings.cell("City")
    ...
```

Result:

![](table-styled-override.jpg)

## Set cells background

```python
...
greyscale = 200
with pdf.table(cell_fill_color=greyscale, cell_fill_mode="ROWS") as table:
    ...
```

Result:

![](table-with-cells-filled.jpg)

```python
...
lightblue = (173, 216, 230)
with pdf.table(cell_fill_color=lightblue, cell_fill_mode="COLUMNS") as table:
    ...
```

Result:

![](table-with-cells-filled2.jpg)

The cell color is set following those settings, ordered by priority:

1. The cell `style`, provided to `Row.cell()`
2. The row `style`, provided to `Table.row()`
3. The table setting `headings_style.fill_color`, if the cell is part of some headings row
4. The table setting `cell_fill_color`, if `cell_fill_mode` indicates to fill a cell
5. The document `.fill_color` set before rendering the table

_New in [:octicons-tag-24: 2.7.9](https://github.com/py-pdf/fpdf2/blob/master/CHANGELOG.md)_

Finally, it is possible to define your own cell-filling logic:

```python
class EvenOddCellFillMode():
    @staticmethod
    def should_fill_cell(i, j):
        return i % 2 and j % 2

...
with pdf.table(cell_fill_color=lightblue, cell_fill_mode=EvenOddCellFillMode()) as table:
    ...
```


## Set borders layout

```python
...
with pdf.table(borders_layout="INTERNAL") as table:
    ...
```

Result:

![](table_with_internal_layout.jpg)

```python
...
with pdf.table(borders_layout="MINIMAL") as table:
    ...
```

Result:

![](table_with_minimal_layout.jpg)

```python
...
pdf.set_draw_color(50)  # very dark grey
pdf.set_line_width(.5)
with pdf.table(borders_layout="SINGLE_TOP_LINE") as table:
    ...
```

Result:

![](table_with_single_top_line_layout.jpg)

It is also possible to create a custom border layout, controlling thickness, color, and dash pattern:
```python
from fpdf.table import TableBordersLayout, TableBorderStyle, TableCellStyle

gray = (150, 150, 150)
red = (255, 0, 0)
custom_layout = TableBordersLayout(
    cell_style_getter=lambda row_num, col_num, num_heading_rows, num_rows, num_cols: TableCellStyle(
        left=(
            True if col_num == 0
            else TableBorderStyle(color=(150, 150, 150), dash=2) if col_num == 2
            else False
        ),        bottom=True if row_num == num_rows - 1 else False,
        right=True if col_num == num_cols - 1 else False,
        top=(
            True if row_num == 0
            else TableBorderStyle(thickness=1) if row_num == num_heading_rows
            else TableBorderStyle(color=red, dash=2)
        ),
    )
)

with pdf.table(borders_layout=custom_layout) as table:
    ...
```

Result:

![](table-with-custom-border-layout.jpg)


All the possible layout values are described
there: [`TableBordersLayout`](https://py-pdf.github.io/fpdf2/fpdf/enums.html#fpdf.enums.TableBordersLayout).

## Set cell borders

_New in [:octicons-tag-24: 2.8.2](https://github.com/py-pdf/fpdf2/blob/master/CHANGELOG.md)_

```python
from fpdf import FPDF

pdf = FPDF()
pdf.add_page()
pdf.set_font("Times", size=16)
with pdf.table() as table:
    for data_row in TABLE_DATA:
        row = table.row()
        for datum in data_row:
            row.cell(datum, border="LEFT")
pdf.output('table.pdf')
```

Result:

![](table_with_cell_border_left.jpg)

```python
from fpdf import FPDF

pdf = FPDF()
pdf.add_page()
pdf.set_font("Times", size=16)
with pdf.table() as table:
    for data_row in TABLE_DATA:
        row = table.row()
        for datum in data_row:
            row.cell(datum, border="TOP")
pdf.output('table.pdf')
```

Result:

![](table_with_cell_border_top.jpg)

```python
from fpdf import FPDF
from fpdf.enums import CellBordersLayout

pdf = FPDF()
pdf.add_page()
pdf.set_font("Times", size=16)
with pdf.table() as table:
    for data_row in TABLE_DATA:
        row = table.row()
        for datum in data_row:
            row.cell(datum, border=CellBordersLayout.TOP | CellBordersLayout.LEFT)
pdf.output('table.pdf')
```

Result:

![](table_with_cell_border_left_top.jpg)

All the possible borders values are described there: [`CellBordersLayout`](https://py-pdf.github.io/fpdf2/fpdf/enums.html#fpdf.enums.CellBordersLayout).


## Insert images

```python
TABLE_DATA = (
    ("First name", "Last name", "Image", "City"),
    ("Jules", "Smith", "shirt.png", "San Juan"),
    ("Mary", "Ramos", "joker.png", "Orlando"),
    ("Carlson", "Banks", "socialist.png", "Los Angeles"),
    ("Lucas", "Cimon", "circle.bmp", "Angers"),
)
pdf = FPDF()
pdf.add_page()
pdf.set_font("Times", size=16)
with pdf.table() as table:
    for i, data_row in enumerate(TABLE_DATA):
        row = table.row()
        for j, datum in enumerate(data_row):
            if j == 2 and i > 0:
                row.cell(img=datum)
            else:
                row.cell(datum)
pdf.output('table_with_images.pdf')
```

Result:

![](table_with_images.jpg)

By default, images height & width are constrained by the row height (based on text content)
and the column width. To render bigger images, you can set the `line_height` to increase the row height, or
pass `img_fill_width=True` to `.cell()`:

```python
                    row.cell(img=datum, img_fill_width=True)
```

Result:

![](table_with_images_and_img_fill_width.jpg)

## Adding links to cells

```python
row.cell(..., link="https://py-pdf.github.io/fpdf2/")
row.cell(..., link=pdf.add_link(page=1))
```

## Syntactic sugar

To simplify `table()` usage, shorter, alternative usage forms are allowed.

This sample code:

```python
with pdf.table() as table:
    for data_row in TABLE_DATA:
        row = table.row()
        for datum in data_row:
            row.cell(datum)
```

Can be shortened to the following code,
by passing lists of strings as the `cells` optional argument of `.row()`:

```python
with pdf.table() as table:
    for data_row in TABLE_DATA:
        table.row(data_row)
```

And even shortened further to a single line,
by passing lists of lists of strings as the `rows` optional argument of `.table()`:

```python
with pdf.table(TABLE_DATA):
    pass
```

## Gutter

Spacing can be introduced between rows and/or columns:

```python
with pdf.table(TABLE_DATA, gutter_height=3, gutter_width=3):
    pass
```

Result:

![](table_with_gutter.jpg)

## Column span and row span

Cells spanning multiple columns or rows can be defined by passing a `colspan` or `rowspan` argument to `.cell()`.
Only the cells with data in them need to be defined. This means that the number of cells on each row can be different.

```python
    ...
with pdf.table(col_widths=(1, 2, 1, 1)) as table:
    row = table.row()
    row.cell("0")
    row.cell("1")
    row.cell("2")
    row.cell("3")

    row = table.row()
    row.cell("A1")
    row.cell("A2", colspan=2)
    row.cell("A4")

    row = table.row()
    row.cell("B1", colspan=2)
    row.cell("B3")
    row.cell("B4")
...
```

result:

![](image-colspan.png)



```python
    ...
with pdf.table(text_align="CENTER") as table:
    row = table.row()
    row.cell("A1", colspan=2, rowspan=3)
    row.cell("C1", colspan=2)
    
    row = table.row()
    row.cell("C2", colspan=2, rowspan=2)
    
    row = table.row()
    # all columns of this row are spanned by previous rows
    
    row = table.row()
    row.cell("A4", colspan=4)
    
    row = table.row()
    row.cell("A5", colspan=2)
    row.cell("C5")
    row.cell("D5")
    
    row = table.row()
    row.cell("A6")
    row.cell("B6", colspan=2, rowspan=2)
    row.cell("D6", rowspan=2)
    
    row = table.row()
    row.cell("A7")
...
```

result:

![](image-rowspan.png)

Alternatively, the spans can be defined using the placeholder elements `TableSpan.COL` and `TableSpan.ROW`.
These elements merge the current cell with the previous column or row respectively.

For example, the previous example table can be defined as follows:

```python
    ...
TABLE_DATA = [
    ["A",           "B",            "C",            "D"],
    ["A1",          TableSpan.COL,  "C1",           TableSpan.COL],
    [TableSpan.ROW, TableSpan.ROW,  "C2",           TableSpan.COL],
    [TableSpan.ROW, TableSpan.ROW,  TableSpan.ROW,  TableSpan.ROW],
    ["A4",          TableSpan.COL,  TableSpan.COL,  TableSpan.COL],
    ["A5",          TableSpan.COL,  "C5",           "D5"],
    ["A6",          "B6",           TableSpan.COL,  "D6"],
    ["A7",          TableSpan.ROW,  TableSpan.ROW,  TableSpan.ROW],
]

with pdf.table(TABLE_DATA, text_align="CENTER"):
    pass
...
```

result:

![](image-rowspan.png)




## Table with multiple heading rows

The number of heading rows is defined by passing the `num_heading_rows` argument to `Table()`. The default value is `1`. To guarantee backwards compatibility with the `first_row_as_headings` argument, the following applies:
- If `num_heading_rows==1`: The value of `first_row_as_headings` defines whether the first row is treated as heading or standard row.
- Otherwise, the value of `num_heading_rows` decides the number of heading rows.
```python
with pdf.table(TABLE_DATA, num_heading_rows=2):
    pass
```

Result:

![](table_with_multiple_headings.png)

## Table from pandas DataFrame or spreadsheet files
We have dedicated pages about those topics:

* [Maths documentation page](Maths.md#using-pandas)
* [Rendering spreadsheets as PDF tables](RenderingSpreadsheetsAsPDFTables.md)

## Using write_html

Tables can also be defined in HTML using [`FPDF.write_html`](HTML.md).
With the same `data` as above, and column widths defined as percent of the effective width:

```python
from fpdf import FPDF

pdf = FPDF()
pdf.set_font_size(16)
pdf.add_page()
pdf.write_html(
    f"""<table border="1"><thead><tr>
    <th width="25%">{TABLE_DATA[0][0]}</th>
    <th width="25%">{TABLE_DATA[0][1]}</th>
    <th width="15%">{TABLE_DATA[0][2]}</th>
    <th width="35%">{TABLE_DATA[0][3]}</th>
</tr></thead><tbody><tr>
    <td>{'</td><td>'.join(TABLE_DATA[1])}</td>
</tr><tr>
    <td>{'</td><td>'.join(TABLE_DATA[2])}</td>
</tr><tr>
    <td>{'</td><td>'.join(TABLE_DATA[3])}</td>
</tr><tr>
    <td>{'</td><td>'.join(TABLE_DATA[4])}</td>
</tr></tbody></table>""",
    table_line_separators=True,
)
pdf.output('table_html.pdf')
```

Note that `write_html` has [some limitations, notably regarding multi-lines cells](HTML.md#supported-html-features).

## "Parsabilty" of the tables generated

The PDF file format is not designed to embed structured tables.
Hence, it can be tricky to extract tables data from PDF documents.

In our tests suite, we ensure that several PDF-tables parsing Python libraries can successfully extract tables in
documents generated with `fpdf2`.
Namely, we
test [camelot-py](https://camelot-py.readthedocs.io) & [tabula-py](https://tabula-py.readthedocs.io): [test/table/test_table_extraction.py](https://github.com/py-pdf/fpdf2/blob/master/test/table/test_table_extraction.py).

Based on those tests, if you want to ease table extraction from the documents you produce, we recommend the following
guidelines:

* avoid splitting tables on several pages
* avoid the `INTERNAL` / `MINIMAL` / `SINGLE_TOP_LINE` borders layouts