Skip to content

Instantly share code, notes, and snippets.

@stevedep
Created May 28, 2024 12:51
Show Gist options
  • Save stevedep/8fb60847112ab04754746abb09ca397f to your computer and use it in GitHub Desktop.
Save stevedep/8fb60847112ab04754746abb09ca397f to your computer and use it in GitHub Desktop.
import img2pdf
from PIL import Image
from io import BytesIO
def convert_png_to_pdf_multiple_pages(png_path, output_pdf_path, num_pages):
"""Converts a PNG image (of SVG) to a PDF with multiple A4 pages in landscape.
Args:
png_path (str): Path to the PNG image file.
output_pdf_path (str): Path to save the generated PDF file.
num_pages (int): Number of A4 pages to create in the PDF.
"""
with open(png_path, "rb") as f:
png_image = Image.open(f)
png_image.load()
png_width, png_height = png_image.size
# Calculate A4 page dimensions (in pixels) with a small margin
a4_width = 3508 # Standard A4 width in pixels (without margins) for landscape
a4_height = 2480 # Standard A4 height in pixels (without margins) for landscape
margin = 20 # Adjust margin as needed
# Check if image dimensions fit within an A4 page with margins
if png_width > a4_width - 2 * margin or png_height > a4_height - 2 * margin:
print("Warning: Image dimensions exceed A4 page size with margins. Consider resizing or adjusting margins.")
# Create a list to hold the BytesIO objects
image_pages = []
# Calculate the width of each slice
slice_width = png_width // num_pages
for page_num in range(num_pages):
# Slice the image
start_x = page_num * slice_width
end_x = start_x + slice_width if page_num < num_pages - 1 else png_width
slice_image = png_image.crop((start_x, 0, end_x, png_height))
# Save the slice to a BytesIO object
byte_data = BytesIO()
slice_image.save(byte_data, format='PNG')
byte_data.seek(0)
image_pages.append(byte_data)
# Convert the list of BytesIO objects to PDF and save the output
with open(output_pdf_path, "wb") as f:
f.write(img2pdf.convert(image_pages, dpi=350, x=None, y=None))
print(f"Converted PNG to PDF with {num_pages} pages: {output_pdf_path}")
# Example usage
png_path = "C:\\Temp\\SVGEditing\\new3.png"
output_pdf_path = "c:\\Temp\\new3__.pdf"
num_pages = 4 # Adjust number of pages as needed
convert_png_to_pdf_multiple_pages(png_path, output_pdf_path, num_pages)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment