#!/usr/bin/env python3 """Image to PDF converter using Pillow + reportlab.""" import argparse, json, sys, os from pathlib import Path def convert(input_paths, output_path): from PIL import Image from reportlab.lib.pagesizes import A4 from reportlab.pdfgen import canvas if not output_path: output_path = str(Path(input_paths[0]).with_suffix('.pdf')) c = canvas.Canvas(output_path, pagesize=A4) page_w, page_h = A4 margin = 36 # 0.5 inch for img_path in input_paths: img = Image.open(img_path) img_w, img_h = img.size available_w = page_w - 2 * margin available_h = page_h - 2 * margin scale = min(available_w / img_w, available_h / img_h) draw_w = img_w * scale draw_h = img_h * scale x = (page_w - draw_w) / 2 y = (page_h - draw_h) / 2 c.drawImage(img_path, x, y, draw_w, draw_h, preserveAspectRatio=True) c.showPage() c.save() return output_path def main(): parser = argparse.ArgumentParser(description='Convert images to PDF') parser.add_argument('--input', required=True, nargs='+', help='Input image paths') parser.add_argument('--output', required=True) args = parser.parse_args() try: result = convert(args.input, args.output) print(json.dumps({"success": True, "output": result, "message": "Images converted to PDF successfully"})) except Exception as e: print(json.dumps({"success": False, "output": "", "message": str(e)})) sys.exit(1) if __name__ == '__main__': main()