Created
July 11, 2024 20:10
-
-
Save mara004/f7472307d98a99040fc043ffd8978814 to your computer and use it in GitHub Desktop.
PDF rendering with pymupdf
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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