Skip to content

Instantly share code, notes, and snippets.

@mara004
Last active September 6, 2024 18:40
Show Gist options
  • Save mara004/fa978bc46de054c1d54a65fbe754a31f to your computer and use it in GitHub Desktop.
Save mara004/fa978bc46de054c1d54a65fbe754a31f to your computer and use it in GitHub Desktop.
PDF rendering with poppler-gtk
# SPDX-FileCopyrightText: 2024 geisserml <[email protected]>
# SPDX-License-Identifier: MPL-2.0
# Note that Poppler is GPL-licensed, so this code is altogether affected by copyleft
import math
from pathlib import Path
import PIL.Image
import cairo
import gi
gi.require_version('Poppler', '0.18')
from gi.repository import Poppler
def invoke_poppler_gtk(filepath, index, scale=4, rotation=0, password=None):
# Note, as of this writing, poppler does not take /UserUnit into account.
pdf = Poppler.Document.new_from_file(pathlib.Path(filepath).as_uri(), password)
page = pdf.get_page(index)
width, height = page.get_size()
width, height = math.ceil(width), math.ceil(height)
sc_width, sc_height = math.ceil(width*scale), math.ceil(height*scale)
if rotation in (90, 270):
width, height = height, width
sc_width, sc_height = sc_height, sc_width
cr_surface = cairo.ImageSurface(cairo.Format.ARGB32, sc_width, sc_height)
cr_context = cairo.Context(cr_surface)
cr_context.scale(scale, scale)
cr_context.set_source_rgba(255, 255, 255, 255)
cr_context.rectangle(0, 0, width, height)
cr_context.fill()
cr_context.rotate((rotation/180) * math.pi) # TODO math.radians(rotation)
if rotation == 90:
cr_context.translate(0, -width)
elif rotation == 180:
cr_context.translate(-width, -height)
elif rotation == 270:
cr_context.translate(-height, 0)
page.render(cr_context)
pil_image = PIL.Image.frombytes(
"RGBA",
(sc_width, sc_height),
bytes(cr_surface.get_data()),
"raw",
"BGRa",
0, 1,
)
return pil_image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment