OCR_API / utils /pdf.py
AdityaAjithKumar
feat: add PDF support — convert first page to image before OCR
ae379dd
Raw
History Blame Contribute Delete
506 Bytes
import io
import fitz # PyMuPDF
def pdf_to_image_bytes(pdf_bytes: bytes, dpi: int = 200) -> bytes:
"""Render the first page of a PDF to JPEG bytes."""
doc = fitz.open(stream=pdf_bytes, filetype="pdf")
if doc.page_count == 0:
raise ValueError("The uploaded PDF has no pages.")
page = doc.load_page(0)
mat = fitz.Matrix(dpi / 72, dpi / 72)
pix = page.get_pixmap(matrix=mat, colorspace=fitz.csRGB)
buffer = io.BytesIO(pix.tobytes("jpeg"))
return buffer.getvalue()