Spaces:
Sleeping
Sleeping
File size: 1,687 Bytes
80a3675 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | #!/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()
|