How to Convert an Image Into a PDF Using Python

News

HomeHome / News / How to Convert an Image Into a PDF Using Python

Aug 14, 2023

How to Convert an Image Into a PDF Using Python

Organize your images into PDFs and learn how to use Tkinter to build this handy utility. From business reports to photography portfolios, you'll often come across a need to use images in PDFs. An

Organize your images into PDFs and learn how to use Tkinter to build this handy utility.

From business reports to photography portfolios, you'll often come across a need to use images in PDFs. An image-to-PDF converter can help streamline the process. While there are many free tools available online, their need for you to upload images may be a privacy or security concern.

Instead, you can build an offline image-to-PDF converter using Python. Select multiple images in JPG or PNG format, get a preview, and convert them into a PDF while maintaining the original image size.

Tkinter is the standard GUI library for Python. It offers a variety of widgets like buttons, labels, and text boxes that make it easy to develop apps like a music player or a weight conversion tool. To install Tkinter in your system, open a terminal, and type:

The Pillow module is a powerful Python imaging library that makes it easy to perform operations on images such as resizing, cropping, and filtering. Integrating this with OpenAI API and DALL·E 2, you can generate images using a text prompt.

To install Pillow, run this command:

ReportLab is an open-source Python library for generating PDFs and graphics. It has various tools you can use to generate documents with images, text, and tables which makes it useful to generate reports via programming. With this, you can build business reports, invoices, and certificates while also adding a text watermark. To install ReportLab:

You can find the entire source code for building the image-to-PDF converter using Python in this GitHub repository.

Import the necessary modules and create a class named ImageToPDFConverter. Define a constructor method that initializes the class and takes Tkinter's root window object as an argument. Initialize an empty list to store the paths of the images the user selects. Set the title and dimensions of the application. Create two buttons named Select Images and Convert to PDF.

Pass the window you want to place the button in, the text they should display, the command that they should execute when clicked, and the font format they should apply. Organize the buttons using the pack() method and give them a padding of 10 in the vertical direction.

Define a label by passing it the parent window to place it in, the text it should display, the font format it should use, and a vertical padding of 10 (pixels).

Similarly, define a frame to preview the selected image and set its parent window, width, and height. Organize it with a padding of 10.

Define a method, select_images(). Use Tkinter's filedialog class to open a dialog box to select multiple images and store them in the images_path list. Pass the initial directory the dialog box should open, the title it should display, and the file types it allows for selection.

Define a loop that iterates over all the paths of the images the user selected. Use Pillow's open() method to open the image file and pass the maximum dimension it should possess to the resize method. Convert this PIL image to PhotoImage that is compatible with Tkinter. Create a label that resides in the preview frame you created earlier and display the image. Use the grid manager to organize the images in a grid layout with three columns.

Define a method, resize_image() that resizes the image taking into account the image's dimension and the maximum dimension you defined earlier. Calculate the aspect ratio and use it to set the new width and height. Use PIL's resize method to resize the image keeping the aspect ratio intact. Use bilinear interpolation as resampling for a smoother result.

Define a function, convert_to_pdf(). Use the filedialog to ask for the destination path for the PDF. Set the default extension and file type as .pdf. Use ReportLab's canvas module to draw a landscape page. Iterate over the path of the images, open them, set the dimensions of the PDF's page the same as that of the image, and draw the image from the top left corner with the specified dimensions.

The showPage() method allows the PDF to move to the next page. Once the program completes this process, save the PDF and show a message box along with the path.

Create the Tkinter root window and pass it to the class instance. The mainloop() function tells Python to run the Tkinter event loop and listen for events until you close the window.

Put all the code together and the image-to-PDF Converter is ready to use.

On running the app, you'll see a window with two buttons and a blank space instructing you to select the images.

On clicking the Select Images button, a window pops up asking you to choose the images. You can select any number of images in any combination.

Once you have selected your desired images, you'll see a preview of them:

On clicking the Convert to PDF button, you can select the name and the path where you want to store the PDF file. Once the program finishes the conversion, it displays a message box saying it has saved the PDF followed by the path name. On opening the PDF you will find that the program has converted the images without changing their dimensions.

You can build a full-fledged PDF application that performs operations such as merging, compressing, protecting, and unlocking PDFs. You can build a feature to split the PDF into multiple pages, rotate them, remove particular pages, sort it, and add page numbers.

You can experiment with other file formats as well for converting a document or a presentation into PDF. Several modules, like PyPDF2, PDFMiner, fpdf, and pdfrw, can help you achieve these more conveniently.

Sai Ashish is a highly skilled software engineer with industry experience in coding, designing, deploying, and debugging development projects.He is a former Google Developer Students Club lead and also held the position of Technical Head during his studies at the esteemed University of Mumbai, India. He is certified in C++, Java, and Python. Since 2018, he has shared his technical knowledge via his passion for writing, speaking at sessions, and online tutorials.

ImageToPDFConverterSelect ImagesConvert to PDFpack()select_images()filedialogimages_path open() PhotoImagegridresize_image()convert_to_pdf().pdfshowPage() mainloop()Select Images