Table using only cell borders

The following code draws a table taking advantage of the cell borders. I think this should be a good solution for most cases.

# Import FPDF class
from fpdf import FPDF

# Create instance of FPDF class
# Letter size paper, use inches as unit of measure
pdf=FPDF(format='letter', unit='in')

# Add new page. Without this you cannot create the document.

# Remember to always put one of these at least once.

# Effective page width, or just epw
epw = pdf.w - 2*pdf.l_margin

# Set column width to 1/4 of effective page width to distribute content 
# evenly across table and page
col_width = epw/4

# Since we do not need to draw lines anymore, there is no need to separate
# headers from data matrix.

data = [['First name','Last name','Age','City'],
['Jules','Smith',34,'San Juan'],
'Carlson','Banks',19,'Los Angeles']

# Document title centered, 'B'old, 14 pt
pdf.cell(epw, 0.0, 'Demographic data', align='C')

# Text height is the same as current font size
th = pdf.font_size

for row in data:
    for datum in row:
        # Enter data in colums
        # Notice the use of the function str to coerce any input to the 
        # string type. This is needed
        # since pyFPDF expects a string, not a number.
        pdf.cell(col_width, th, str(datum), border=1)


# Line break equivalent to 4 lines

pdf.cell(epw, 0.0, 'With more padding', align='C')

# Here we add more padding by passing 2*th as height
for row in data:
    for datum in row:
        # Enter data in colums
        pdf.cell(col_width, 2*th, str(datum), border=1)





Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s