53 lines
1.5 KiB
Python
Executable File
53 lines
1.5 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
|
|
import sys
|
|
from pathlib import Path
|
|
from PIL import Image
|
|
from reportlab.lib.pagesizes import A4
|
|
from reportlab.pdfgen import canvas
|
|
from reportlab.lib.units import mm
|
|
|
|
def image_to_pdf(image_path, output_pdf=None):
|
|
image_path = Path(image_path)
|
|
|
|
if not image_path.exists():
|
|
raise FileNotFoundError(f"File not found: {image_path}")
|
|
|
|
if output_pdf is None:
|
|
output_pdf = image_path.with_suffix(".pdf")
|
|
|
|
img = Image.open(image_path)
|
|
img_width, img_height = img.size
|
|
|
|
# A4 page size (points)
|
|
page_width, page_height = A4
|
|
|
|
# Convert pixels to points assuming 300 DPI
|
|
dpi = img.info.get("dpi", (300, 300))[0]
|
|
img_width_pt = img_width * 72 / dpi
|
|
img_height_pt = img_height * 72 / dpi
|
|
|
|
# Scale to fit page while preserving aspect ratio
|
|
scale = min(page_width / img_width_pt, page_height / img_height_pt)
|
|
draw_width = img_width_pt * scale
|
|
draw_height = img_height_pt * scale
|
|
|
|
x = (page_width - draw_width) / 2
|
|
y = (page_height - draw_height) / 2
|
|
|
|
c = canvas.Canvas(str(output_pdf), pagesize=A4)
|
|
c.drawImage(str(image_path), x, y, draw_width, draw_height)
|
|
c.showPage()
|
|
c.save()
|
|
|
|
print(f"✔ PDF created: {output_pdf}")
|
|
|
|
if __name__ == "__main__":
|
|
if len(sys.argv) < 2:
|
|
print("Usage: cover_to_pdf.py <image.jpg/png> [output.pdf]")
|
|
sys.exit(1)
|
|
|
|
image = sys.argv[1]
|
|
output = sys.argv[2] if len(sys.argv) > 2 else None
|
|
image_to_pdf(image, output)
|