Skip to content

Instantly share code, notes, and snippets.

@mara004
Created July 11, 2024 20:10
Show Gist options
  • Save mara004/f7472307d98a99040fc043ffd8978814 to your computer and use it in GitHub Desktop.
Save mara004/f7472307d98a99040fc043ffd8978814 to your computer and use it in GitHub Desktop.
PDF rendering with pymupdf
# SPDX-FileCopyrightText: 2024 geisserml <[email protected]>
# SPDX-License-Identifier: MPL-2.0
# Note that (py)mupdf is AGPL-licensed, so this code is altogether affected by copyleft
import PIL.Image
import fitz as pymupdf
def invoke_pymupdf(filepath, index, scale=4, rotation=0, password=None):
pdf = pymupdf.Document(filepath)
if pdf.is_encrypted:
if password is not None:
pdf.authenticate(password)
else:
raise ValueError("Missing password.")
page = pdf[index]
page.set_rotation(rotation)
# mupdf takes userunit into account on its own
pixmap = page.get_pixmap(matrix=pymupdf.Matrix(scale, scale))
pil_image = PIL.Image.frombuffer("RGB", (pixmap.width, pixmap.height), pixmap.samples)
pdf.close()
return pil_image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment