How to make a pdf from many png files

Here is how. I use this script all the time, it’s very handful to me. Let’s see how you can create a pdf just putting together all the images in a folder, launching this script. In cas you want to go even faster I will tell you a way to launch a python script from every folder, so that you do not need to have the script in the folder where you got the images.

Let’s see the script for the moment and come soon here to see what I told you just now.

from fpdf import FPDF
from PIL import Image
import os
from glob import glob


def makePdf():
    """ Takes filename and number of pages abd creates pdf """
    lst_files = sorted(glob("*.png"))
    # lst_files = os.listdir()
    print(lst_files)
    w = 800
    h = 600
    for f in lst_files:
        cover = Image.open(f)
        if cover.size[0] > w:
            w = cover.size[0]
        if cover.size[1] > h:
            h = cover.size[1]
    nomefile = input("Nomedelfile: ")
    pdf = FPDF(unit="pt", format=[w, h])
    for page in lst_files:
        pdf.add_page()
        pdf.image(page, 0, 0)
    pdf.output(nomefile + ".pdf", "F")
    os.startfile(nomefile + ".pdf")

makePdf()

Subscribe to the newsletter for updates
Tkinter templates
Avatar My youtube channel

Twitter: @pythonprogrammi - python_pygame

Videos

Speech recognition game

Pygame's Platform Game

Other Pygame's posts

Published by pythonprogramming

Started with basic on the spectrum, loved javascript in the 90ies and python in the 2000, now I am back with python, still making some javascript stuff when needed.