Programmed books 4

Random position

from fpdf import FPDF
import os
import random

''' Create FPDF object. '''

pdf = FPDF('P', 'mm', format='A5') # 148 × 210 
pdf.set_margins(left=10, top=10, right=10)
pdf.set_font('Helvetica')


''' Title page. '''
pdf.add_page()
pdf.set_font_size(40)
pdf.ln(50)
pdf.multi_cell(0, None, txt='Random positioning', align='C')


''' Render text in different fonts on random positions. '''

pdf.add_page()
pdf.set_font_size(14)
fonts = os.listdir('fonts')
fonts = [font for font in fonts if font.endswith('.ttf')]

for font in fonts:
    
    font_name = os.path.splitext(font)[0]
    font_path = 'fonts/' + font
    
    pdf.add_font(font_name, '', font_path, uni=True)
    pdf.set_font(font_name)
    pdf.set_text_color(random.randint(0,220))
    
    txt = 'The quick brown fox jumps over the lazy dog'
    txt += '\n(' + font_name + ')'
    
    pdf.set_x(random.randint(10, 100))
    pdf.set_y(random.randint(10, 180))
    pdf.multi_cell(w=random.randint(0, 128), h=5, txt=txt,
        align=random.choice(['L', 'C', 'R']))


'''Save PDF.'''

pdf.output('generated_pdfs/007.pdf')

View PDF

007.gif



Image zoom

from fpdf import FPDF
import os

''' Create FPDF object. '''

pdf = FPDF('P', 'mm', format='A5') # 148 × 210
pdf.set_margins(left=20, top=20, right=20)


''' Render an image with increasing size. '''

img_path = 'images/Ghostscript_Tiger.png'
size = 1

for i in range(14):
    pdf.add_page()
    pdf.image(img_path, x = (148-size)/2, y = (210-size)/2, w = size, h = size)
    size *= 2
    

''' Save PDF. '''

pdf.output('generated_pdfs/008.pdf')

View PDF

008.gif



While

from fpdf import FPDF
import os

''' Create FPDF object. '''

pdf = FPDF('P', 'mm', format='A5') # 148 × 210


''' Render lines from top to bottom until the end is reached. '''

pdf.set_margin(0)
line_width = 2
pdf.set_draw_color(0, 80, 180)
pdf.set_line_width(line_width)

y = 0

while y <= 210:
    
    pdf.add_page()
    pdf.line(x1=0, y1=y, x2=148, y2=y)
    y += line_width

''' Save PDF. '''

pdf.output('generated_pdfs/009.pdf')

View PDF

009.gif