Images with borders

The next piece of code creates a border around an image using the `rect(x,y,w,h,style)` method. The `rect` method draws a rectangle given top, left coordinate, its width and height and style. In this example we won’t declare the style to leave the rectangle empty (without fill color).

The colors are set using the `set_draw_color(rgb_triplet)` method.

The images were obtained from the `matplotlib` 1.2.1 gallery.

# 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.
pdf.add_page()

# Remember to always put one of these at least once.
pdf.set_font('Times','',10.0) 
th = pdf.font_size

# Store image width in inches (same unit as page)
widths = [1.0, 3.5, 5.5]

# list of colors
colors = [(0,0,0),(255,0,0),(255,165,0)]

# list of images
images = ['animation_demo.png','fill_demo1.png','mri_with_eeg.png']

for img_num, image in enumerate(images):

    top_image = pdf.y
    pdf.image(image, w=widths[img_num])
    
    # Set line color
    pdf.set_draw_color(*colors[img_num])
    
    # Draw empty (style = '') rectangle around the image.
    pdf.rect(pdf.x, top_image, w=widths[img_num], h= pdf.y - top_image)
    
    pdf.ln(2*th)
    
pdf.output('images-borders.pdf','F')

pyfpdf-images-borders

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