In this article, you will learn how to convert images to PDF in Python.
Convert images to PDF
You can use the Python package PyPDF2 to convert images to PDF in Python. Here’s an example code:
import os from PIL import Image from PyPDF2 import PdfFileMerger # Set the directory containing the images directory = './images/' # Get a list of all the image file names in the directory image_files = [filename for filename in os.listdir(directory) if filename.endswith('.jpg')] # Sort the file names alphabetically image_files.sort() # Create a new PDF file pdf_output = './output.pdf' pdf_merger = PdfFileMerger() # Loop through all the image files and convert each one to a PDF page for image_file in image_files: # Open the image and convert it to grayscale image = Image.open(directory + image_file).convert('RGB') # Create a new PDF page and add the image to it pdf_page = Image.new('RGB', image.size, 'white') pdf_page.paste(image, mask=image.convert('RGBA')) # Add the PDF page to the PDF file pdf_merger.append(pdf_page) # Save the PDF file pdf_merger.write(pdf_output) pdf_merger.close()
In this code, we use the Pillow library (a fork of the Python Imaging Library or PIL) to open the image files and convert them to grayscale. Then, we create a new PDF page and paste the image onto it. Finally, we use the PdfFileMerger class from the PyPDF2 library to merge all the PDF pages into a single PDF file. Note that in this example, we assume that all the images are in JPEG format and that they are located in a directory named “images” in the current working directory.