Images in a PDF

Images in a PDF#

fpdf2 image documentation

from fpdf import FPDF
from diffusers.utils import load_image

# VARIABLES
pdf_width = 148
pdf_height = 210
pdf_border = 20
img_width = pdf_width - (2*pdf_border)
img_height = pdf_height - (2*pdf_border)


# PDF SETUP
pdf = FPDF('P', 'mm', format=(pdf_width, pdf_height))
pdf.set_margins(left=pdf_border, top=pdf_border, right=pdf_border)

# Adding page and image(s)

img = load_image("https://thispersondoesnotexist.com/")

# without scaling
pdf.add_page()
pdf.image(img, x=0, y=0, keep_aspect_ratio=True)

# with defined position, width and height
pdf.add_page()
pdf.image(img, x=20, y=20, w=img_width, h=img_height)

# keeping the aspect ratio
pdf.add_page()
pdf.image(img, x=20, y=20, w=img_width, h=img_height, keep_aspect_ratio=True)

pdf.output('pdfs/image.pdf')

image pdf