To convert an image to PDF in Python, the Pillow library (an enhanced fork of the original Python Imaging Library or PIL) is commonly used. Here's how you can achieve the conversion using Pillow:
Install Pillow:
If you haven't already, you'll need to install the Pillow library:
pip install Pillow
Convert Image to PDF:
Use the following code to convert an image to a PDF:
from PIL import Image image_path = "path_to_your_image.jpg" pdf_path = "output_path.pdf" image = Image.open(image_path) image.save(pdf_path, "PDF", resolution=100.0, save_all=True, append_images=[image])
In this code:
resolution=100.0 is the resolution of the saved PDF. You can adjust it as needed.save_all=True is used to save all frames of the image (if it's a multi-frame image like a GIF).append_images is a list of images to append. In this example, the same image is appended, but you could easily append other images if needed.Convert Multiple Images to a Single PDF:
If you have multiple images that you want to combine into a single PDF:
from PIL import Image image_paths = ["path_to_image1.jpg", "path_to_image2.png", "path_to_image3.jpeg"] pdf_path = "output_path.pdf" images = [Image.open(image_path) for image_path in image_paths] # Save the first image and append others images[0].save(pdf_path, save_all=True, append_images=images[1:])
Now, when you execute this code, you will get a PDF file with the image(s) embedded.
telerik identityserver4 floating oracle-spatial local-storage onblur angular-filters pylint roblox datagrid