Skip to content

Instantly share code, notes, and snippets.

@mara004
Last active July 13, 2024 14:31
Show Gist options
  • Save mara004/41471e9b037c4a974d16b1e1a963124e to your computer and use it in GitHub Desktop.
Save mara004/41471e9b037c4a974d16b1e1a963124e to your computer and use it in GitHub Desktop.
PDF rendering with poppler-qt5
# SPDX-FileCopyrightText: 2024 geisserml <geisserml@gmail.com>
# SPDX-License-Identifier: MPL-2.0
# Note that Poppler is GPL-licensed, so this code is altogether affected by copyleft
import io
import PIL.Image
from popplerqt5 import Poppler
from PyQt5.QtCore import QByteArray, QBuffer
def _translate_rotation(rotation):
r_enum = Poppler.Page.Rotation
return {
0: r_enum.Rotate0,
90: r_enum.Rotate90,
180: r_enum.Rotate180,
270: r_enum.Rotate270,
}[rotation]
def invoke_poppler_qt5(filepath, index, scale=4, rotation=0, password=None):
# Note, as of this writing, poppler does not take /UserUnit into account.
if password is None:
pdf = Poppler.Document.load(filepath)
else:
qb_password = QByteArray(password.encode('ascii'))
pdf = Poppler.Document.load(filepath, qb_password, qb_password)
pdf.setRenderHint(Poppler.Document.Antialiasing)
pdf.setRenderHint(Poppler.Document.TextAntialiasing)
page = pdf.page(index)
dpi = scale * 72
qimage = page.renderToImage( # TODO use kwargs?
dpi, dpi,
-1, -1, -1, -1,
_translate_rotation(rotation),
)
qbuffer = QBuffer()
qbuffer.open(QBuffer.ReadWrite)
qimage.save(qbuffer, "PPM")
qbuffer.close()
return PIL.Image.open( io.BytesIO(qbuffer.data()) )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment