Python Image conversion - How do I Convert Image to PDF
Last updated Jan 31, 2022For a number of reasons, you may want to convert an image to PDF. It can be due to the reliability of the PDF format, insufficient storage space, security concerns, etc. This post looks at creating a PDF from an image using Python.
How to Convert Image to PDF in Python
Follow these simple steps for converting an image to PDF in Python:
Step 1: First of all, we need to install img2pdf on our Python. This will enable our python program to convert the selected images to pdf. To do this, simply open your terminal and type the command:
pip install img2pdf |
![]() |
Step 2: Our next step will be to create a simple GUI. To do this, we will need to use Tkinter. Import tkinter into our python program with the following code: import * from tkinter. Then paste the code into our IDE to create a simple GUI.
from tkinter import * root = Tk() root.geometry('300x300') root.title("Convert Image to PDF") Label(root, text="CONVERT IMAGE", font="italic 15 bold").pack(pady=10) Button(root, text="Choose image", relief="solid", font=14). pack(pady=10) Button(root, text="Convert to PDF", relief="solid", font=14). pack(pady=10) root.mainloop() |
When the code above is run, our GUI appears, but the buttons do not work. In the next step, we will make them work
-
Step 3: We now need to add functionality to our buttons. The first button, "choose image," should select the file from which to convert an image, and the second, "convert to PDF," should convert the selected file. To do this, simply add the code below:
To select the image to be converted
ef select_file(): global file_names file_names= askopenfilenames(initialdir="/", title="Select Files") |
To convert image to pdf
def images_to_pdf(): with open(f"file.pdf", "wb") as f: f.write(img2pdf.convert(file_names)) |
In order to make the buttons work, we must use the command attribute, as shown below, to link them with the functions above:
Button(root, text="Choose image", relief="solid", command=select_file, font=14). pack(pady=10) Button(root, text="Convert to PDF", relief="solid", command=images_to_pdf, font=14). pack(pady=10) |
Step 4: We are done. When we run the application, everything works perfectly. Now we can select and convert images to PDF.
![]() |
Article Contributed By :
|
|
|
|
514 Views |