Paperjet/backend/app/services/thumbnails.py

40 lines
1.1 KiB
Python

"""Thumbnail generation service."""
import pymupdf
from app.config import settings
def generate_thumbnail(file_id: str) -> bool:
"""Generate a PNG thumbnail for the first page of a PDF."""
pdf_path = settings.PDF_STORAGE_PATH / f"{file_id}.pdf"
thumb_path = settings.THUMBNAILS_PATH / f"{file_id}.png"
if not pdf_path.exists():
return False
try:
with pymupdf.open(pdf_path) as doc:
if len(doc) == 0:
return False
page = doc[0]
# Zoom to approximately 600px width
rect = page.rect
zoom = 600.0 / rect.width if rect.width > 0 else 1.0
mat = pymupdf.Matrix(zoom, zoom)
# Render pixmap
pix = page.get_pixmap(matrix=mat, alpha=False)
# Save as PNG
pix.save(thumb_path, output="png")
return True
except Exception as err:
print(f"Failed to generate thumbnail for {file_id}: {err}")
return False
def delete_thumbnail(file_id: str) -> None:
"""Delete a thumbnail file."""
thumb_path = settings.THUMBNAILS_PATH / f"{file_id}.png"
thumb_path.unlink(missing_ok=True)