Changing margins

To change the margins of a page you need to set them before the `add_page` method or you won’t see the changes.

You can set the margins using different methods: `set_margins()`, `set_left_margin()`, `set_top_margin()`, `set_right_margin()` but I prefer to use the margin variables directly: `l_margin`, `r_margin`, `t_margin`, `b_margin`. Is less verbose, concise and gives me more control.

# Import FPDF class
from fpdf import FPDF

# Create instance of FPDF class
pdf=FPDF(format='letter',unit='in')

# Set margins BEFORE add_page!
# Margin sizes multiples of default size
pdf.l_margin = pdf.l_margin*4.0
pdf.r_margin = pdf.r_margin*4.0
pdf.t_margin = pdf.t_margin*4.0
pdf.b_margin = pdf.b_margin*4.0

# Now we add a page. It is in this step that margins settings take effect.
pdf.add_page()

# Effective page width and height
epw = pdf.w - pdf.l_margin - pdf.r_margin
eph = pdf.h - pdf.t_margin - pdf.b_margin

# Draw new margins.
pdf.rect(pdf.l_margin, pdf.t_margin, w=epw, h=eph)


# Remember to put at least one of this font declarations when you are going
# to render text.  Not needed if not drawing text.
pdf.set_font('Times','',12)

# Text height
th = pdf.font_size

# Draw margin sizes.
# Need this line break, otherwise top line crosses text. Still have not
# figure that one out but it has to do with how text is positioned with
# respect x and y coordinates.

pdf.ln(th)

pdf.cell(epw,0, 'Left: %s in, Right: %s in, Top: %s in, Bottom: %s in' % \
(pdf.l_margin, pdf.r_margin, pdf.t_margin, pdf.b_margin))

pdf.ln(2*th)

loremipsum = """Lorem ipsum dolor sit amet, vel ne quando dissentias. Ne his oporteat expetendis. Ei tantas explicari quo, sea vidit minimum menandri ea. His case errem dicam ex, mel eruditi tibique delicatissimi ut. At mea wisi dolorum contentiones, in malis vitae viderer mel.

Vis at dolores ocurreret splendide. Noster dolorum repudiare vis ei, te augue summo vis. An vim quas torquatos, electram posidonium eam ea, eros blandit ea vel. Reque summo assueverit an sit. Sed nibh conceptam cu, pro in graeci ancillae constituto, eam eu oratio soleat instructior. No deleniti quaerendum vim, assum saepe munere ea vis, te tale tempor sit. An sed debet ocurreret adversarium, ne enim docendi mandamus sea.
"""

pdf.multi_cell(epw,th, loremipsum)

pdf.output('margins-change.pdf','F')

pyfpdf set margins

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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