import os
import math
from pdf2image import convert_from_path
from docx2pdf import convert
from PIL import Image
def convert_docx_to_pdf(input_path, output_path):
"""
Convert a .docx file to .pdf
"""
convert(input_path, output_path)
def convert_pdf_to_images(pdf_path, dpi=200):
"""
Convert each page of a PDF to an image.
Returns a list of PIL Image objects.
"""
images = convert_from_path(pdf_path, dpi=dpi)
return images
def calculate_grid_size(num_pages):
"""
Calculate the grid size (width and height) to be as square as possible.
"""
grid_size = math.ceil(math.sqrt(num_pages))
return grid_size, grid_size
def combine_images_into_grid(images, grid_width, grid_height, image_width, image_height):
"""
Combine a list of images into a single grid image.
"""
# Create a blank canvas
grid_image = Image.new('RGB', (grid_width * image_width, grid_height * image_height), color=(255, 255, 255))
for index, img in enumerate(images):
row = index // grid_width
col = index % grid_width
x = col * image_width
y = row * image_height
grid_image.paste(img, (x, y))
return grid_image
def process_document(input_path, output_path):
"""
Process the input document (PDF or DOCX) and save a single combined PNG image.
"""
# Check the file extension
file_ext = os.path.splitext(input_path)[1].lower()
if file_ext == '.docx':
print(f"Converting {input_path} to PDF...")
pdf_path = 'temp_converted.pdf'
convert_docx_to_pdf(input_path, pdf_path)
elif file_ext == '.pdf':
pdf_path = input_path
else:
raise ValueError("Unsupported file type. Please provide a PDF or DOCX file.")
# Convert PDF to images
print(f"Converting {pdf_path} to images...")
images = convert_pdf_to_images(pdf_path)
num_pages = len(images)
print(f"Total pages: {num_pages}")
# Determine grid size
grid_width, grid_height = calculate_grid_size(num_pages)
print(f"Grid size: {grid_width}x{grid_height}")
# Optionally, resize images to a standard size (e.g., 800x1000)
# This step is optional and depends on the desired output
standard_width = max(img.width for img in images)
standard_height = max(img.height for img in images)
resized_images = [img.resize((standard_width, standard_height), Image.ANTIALIAS) for img in images]
# Combine images into a grid
print("Combining images into a single grid...")
combined_image = combine_images_into_grid(resized_images, grid_width, grid_height, standard_width, standard_height)
# Save the combined image
combined_image.save(output_path, 'PNG')
print(f"Saved combined image to {output_path}")
# Clean up temporary PDF if converted from DOCX
if file_ext == '.docx':
os.remove(pdf_path)
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="Combine PDF or DOCX pages into a single PNG grid image.")
parser.add_argument('input_file', help="Path to the input PDF or DOCX file.")
parser.add_argument('output_file', help="Path to the output PNG file.")
args = parser.parse_args()
process_document(args.input_file, args.output_file)