Welcome folks today in this blog post we will be converting all images present in directory to pdf document using pillow library in tkinter. All the full source code of the application is shown below.
Get Started
In order to get started you need to install the below libraries using the pip
command as shown below
pip install pillow
And after that we can now make an app.py
file and copy paste the below code
The directory structure of the app is shown below
As you can see we need to create a directory of images
inside the root directory and copy paste all the images. Now we need to make an app.py
file and copy paste the below code
app.py
1 2 3 4 |
from PIL import Image from glob import glob import os import tkinter as tk |
As you can see we are importing the above dependencies which is pillow
and tkinter
as shown above. And also we are importing the glob
module to target all the images which is stored in images folder.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
root = tk.Tk() text = tk.Label(root, text="Nome del file:").pack() namepdf = tk.StringVar() text = tk.Entry(root, textvariable=namepdf) text.pack() button = tk.Button(root, text="Create pdf", command=lambda: create_pdf(namepdf.get()) ) button.pack() root.mainloop() |
As you can see we are making the label widget where we are showing the name the file
and then we have the input file where we need to enter the output filename and then we have the button to create the pdf document. And we are making the button using the button widget and also we are attaching the command or onclick listener which is create_pdf()
here we are passing the value which the user has entered.
And also we are adding the button widget to the tkinter window using the pack()
window. And then we are starting out the tkinter application.
And now we will be writing the function to create the pdf
document which will contain all the images
which is present inside the images folder
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
def create_pdf(name_pdf): files = glob("images/*.png") iml = [] print(f"{files=}") files = sorted(files) for img in files: imgs = Image.open(img) rgb_im = imgs.convert('RGB') # to prevent errors: cannot save mode RGBA iml.append(rgb_im) pdf = name_pdf + ".pdf" print(iml) image = iml[0] iml.pop(0) image.save(pdf, "PDF" , resolution=100.0, save_all=True, append_images=iml) os.system(pdf) |
And as you can see we are targeting all the images using the glob module and inside that we are passing the path of the images folder and after that we are adding the * operator to target all the files which are present inside the images directory and after that we are using pillow to export all these images to pdf document using the for loop. And then we are saving the output resultant pdf file in local disk with the custom file name that we received in this component.
If you run the python
app in the command line
python app.py