Skip to content

Instantly share code, notes, and snippets.

@aspose-com-gists
Created July 17, 2026 08:02
Show Gist options
  • Select an option

  • Save aspose-com-gists/9ed679b77d7494a4a0403999861f205a to your computer and use it in GitHub Desktop.

Select an option

Save aspose-com-gists/9ed679b77d7494a4a0403999861f205a to your computer and use it in GitHub Desktop.
Generate PDF from Images in Python

Generate PDF from Images in Python

Learn to generate a PDF from images in Python with Aspose.PDF for Python via .NET. The tutorial covers prerequisites, installation, a step-by-step implementation using the Python Imaging Library, compression settings, and a ready-to-use code sample.

Read the full guide here: https://blog.aspose.com/pdf/generate-pdf-from-images-in-python/

import os
import io
from PIL import Image
import aspose.pdf as ap
# -------------------- Configuration --------------------
image_folder = "input_images" # Folder containing source images
output_pdf = "output/result.pdf" # Destination PDF file
jpeg_quality = 80 # Compression quality (0‑100)
# -------------------- Load Images --------------------
image_paths = [os.path.join(image_folder, f) for f in os.listdir(image_folder)
if f.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.gif'))]
images = [Image.open(p) for p in image_paths]
# -------------------- Create PDF Document --------------------
pdf_doc = ap.Document()
for img in images:
page = pdf_doc.pages.add()
with io.BytesIO() as img_stream:
img.save(img_stream, format='PNG')
img_stream.seek(0)
pdf_image = page.resources.images.add(ap.Image(img_stream))
page.page_info.width = img.width
page.page_info.height = img.height
# Apply compression if the original is JPEG
if img.format == 'JPEG':
pdf_image.compression = ap.ImageCompression.JPEG
pdf_image.jpeg_quality = jpeg_quality
# -------------------- Save PDF --------------------
pdf_doc.save(output_pdf)
print(f"PDF generated successfully at {output_pdf}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment