Introduction
Hello! ๐ In this tutorial I will show you how you can easily convert an image file into a PDF file easily using Python.
I recently had to do this for work so I thought I'd make my own tool. ๐ธ
Creating The Virtual Environment
First we need to create a virtual environment, this is a practice I like doing because it doesn't interfere with the system packages.
Open up a terminal and type the following to create the virtual environment:
python3 -m venv env
Next active it with the following:
source env/bin/activate
Next we need to install the libraries required for the project, open up a file called "requirements.txt" and fill it with the following:
pillow
reportlab
Save and close the file and then run the following command to install the libraries:
pip install -r requirements.txt
Great now we can start coding. ๐
Creating The Converter
Now that we have the needed libraries installed we can now move onto actually coding the project. Open a file called "main.py" and first add the following imports:
from PIL import Image
from reportlab.pdfgen import canvas
Once we have imported the above, we next need to create a function that actually does the converting:
def image_to_pdf(image_path, output_pdf):
# Open the image file
with Image.open(image_path) as img:
# Get image dimensions
img_width, img_height = img.size
# Create a new PDF with the same dimensions as the image
c = canvas.Canvas(output_pdf, pagesize=(img_width, img_height))
c.drawInlineImage(image_path, 0, 0, width=img_width, height=img_height)
# Save the PDF file
c.save()
I've decided to let the comments speak for themselves, basically we create a new PDF file with the same dimensions as the image passed.
Finally we can now called the main function:
if __name__ == "__main__":
input_image = input("Enter the path of the image file: ")
output_file = input("Enter the name for the output PDF file (e.g. output.pdf): ")
image_to_pdf(input_image, output_file)
print(f"PDF saved as {output_file}")
Done! ๐ The above can be run via the following command:
python main.py
Enter an imput image and an output PDF and your image should be converted into a PDF file. ๐
Conclusion
In this tutorial I have provided a way on you can create a Python script that converts an image into a PDF file.
I hope you find this tutorial useful, and as always happy coding. ๐
As always you can find the source code for the above at my Github. https://github.com/ethand91/image-to-pdf
Like my work? I post about a variety of topics, if you would like to see more please like and follow me. Also I love coffee.
If you are looking to learn Algorithm Patterns to ace the coding interview I recommend the following course