Create PDF from multiple images in Python
In this tutorial, we will learn how to create a PDF file from multiple images using our favorite language, Python. At times, you feel the need to convert images into PDF files, and then you open the app and select and then convert, or you open the tool available online and then do your work. What if I tell you that you can do it by just running a simple Python code?
Images to PDF conversion
We will require two libraries, reportlab
, and Pillow
, to handle PDFs and images, respectively. Install it in your system using the below command:
pip install reportlab Pillow
from reportlab.lib.pagesizes import letter from reportlab.pdfgen import canvas from PIL import Image def create_pdf(images, output_file): c = canvas.Canvas(output_file, pagesize=letter) for img_path in images: img = Image.open(img_path) width, height = img.size c.setPageSize((width, height)) c.drawImage(img_path, 0, 0, width, height) c.showPage() c.save() if __name__ == "__main__": images = ["/content/celestial.png", "/content/lion.jpg"] output_file = "output.pdf" create_pdf(images, output_file)
Explanation
First, we import the page size and canvas from the reportlab
library. We are using the letter size in pdf. You can change it as per your choice. Now create the function where you generate canvas from the file and, using .drawImage
you copy the image in your pdf file. At last, we save the canvas, and it gets saved in the form of a pdf file.
Also check: Delete empty pages from pdf file in Python, Create a PDF file using pyPdf Python module
Images stored in a directory
If your images are stored in a directory, we can use the os
library to access it and you have to change the for loop from the above code. Let’s see the changes:
from reportlab.lib.pagesizes import letter from reportlab.pdfgen import canvas from PIL import Image import os def create_pdf_from_folder(folder_path, output_file): c = canvas.Canvas(output_file, pagesize=letter) for filename in os.listdir(folder_path): if filename.endswith(".jpg") or filename.endswith(".png"): # Adjust file extensions as needed img_path = os.path.join(folder_path, filename) img = Image.open(img_path) width, height = img.size c.setPageSize((width, height)) c.drawImage(img_path, 0, 0, width, height) c.showPage() c.save() if __name__ == "__main__": folder_path = "path/to/your/folder" # Replace with the path to your folder output_file = "output.pdf" create_pdf_from_folder(folder_path, output_file)
Here, you can see that we have accessed each image file using the os.path
function. Don’t forget to change the path while running the above code.
Leave a Reply