How do I convert an image to a PDF, then collect all the images into one file by language python?
1-Install necessary libraries:
pip install pillow fpdf
2-Use the following script:
from PIL import Image
from fpdf import FPDF
# Function to convert an image to PDF
def convert_images_to_pdf(image_files, output_pdf):
pdf = FPDF()
for image_file in image_files:
cover = Image.open(image_file)
width, height = cover.size
# Convert pixel dimensions to mm (1 px = 0.264583 mm)
width, height = width * 0.264583, height * 0.264583
# Create a new page with the size of the image
pdf.add_page()
pdf.set_auto_page_break(auto=False, margin=0)
pdf.image(image_file, 0, 0, width, height)
pdf.output(output_pdf, "F")
# List of image files
image_files = ["1.jpeg", "2.jpeg", "3.jpeg", "4.jpeg", "5.jpeg", "6.jpeg", "7.jpeg", "8.jpeg"]
# Output PDF file name
output_pdf = "combined_images.pdf"
# Convert images to PDF
convert_images_to_pdf(image_files, output_pdf)
3-Run the script:
This script will create a single PDF file containing all the specified images.