pythonpython-3.xpdfprintingpyfpdf

Python: Fitting images inside A4 PDF


I have some images that i want to convert to pdf. currently i'm using this code with FPDF:

def image_to_pdf(image_url, pdf_url):
    from fpdf import FPDF
    pdf_model = FPDF()
    pdf_model.add_page()
    pdf_model.image(image_url, 0, 0)
    pdf_model.output(pdf_url)
    return pdf_url

This code is putting the image directly inside PDF which may cause some problems. One of them is that if the image is bigger than the A4 paper, it would get out of paper and some parts of it would not be printed.

I'm also ok with using pillow but i don't know how to use it.


Solution

  • import fitz  # PyMuPDF
    
    images =[...]  # list of image file names
    doc= fitz.open()  # new, empty PDF
    for image in images:  # read image file names
        page = doc.new_page()  # makes a new empty A4 page: (width=595, height=842)
        page.insert_image(page.rect, filename=image)
    doc.ez_save("output.pdf")
    

    Above puts every image on its own A4 page - scaled to the maximum possible extent and centered - meaning image center and page center are the same.