versao compilada
tests / ci (push) Canceled after 0s

This commit is contained in:
2026-10-15 17:37:00 +02:00
parent 9a96ee8dfe
commit c13f250b87
935 changed files with 210656 additions and 272 deletions
@@ -0,0 +1,16 @@
# SPDX-FileCopyrightText: 2026 geisserml <geisserml@gmail.com>
# SPDX-License-Identifier: Apache-2.0 OR BSD-3-Clause
import pypdfium2._library_scope
from pypdfium2.version import *
from pypdfium2._helpers.unsupported import *
from pypdfium2._helpers.misc import *
from pypdfium2._helpers.matrix import *
from pypdfium2._helpers.bitmap import *
from pypdfium2._helpers.document import *
from pypdfium2._helpers.attachment import *
from pypdfium2._helpers.page import *
from pypdfium2._helpers.pageobjects import *
from pypdfium2._helpers.textpage import *
from pypdfium2._helpers.sysfontinfo import *
from pypdfium2 import raw, internal
@@ -0,0 +1,17 @@
# SPDX-FileCopyrightText: 2026 geisserml <geisserml@gmail.com>
# SPDX-License-Identifier: Apache-2.0 OR BSD-3-Clause
import sys
import os.path
import warnings
from pypdfium2_cli.__main__ import *
_DEPRECATION_REASON = "Using a separate submodule is necessary to allow for proper preparation before library init (e.g. set up logging), since a module's __main__.py implies its __init__.py."
if __name__ == "__main__":
_py_exe = os.path.basename(sys.executable)
warnings.simplefilter("always")
warnings.warn(f"`{_py_exe} -m pypdfium2` is deprecated. Use `{_py_exe} -m pypdfium2_cli` or the `pypdfium2` entrypoint script instead. " + _DEPRECATION_REASON, category=DeprecationWarning, stacklevel=2)
cli_main()
else:
warnings.warn("Importing pypdfium2.__main__ is deprecated. Use pypdfium2_cli.__main__ instead. " + _DEPRECATION_REASON, category=DeprecationWarning, stacklevel=2)
@@ -0,0 +1,179 @@
# SPDX-FileCopyrightText: 2026 geisserml <geisserml@gmail.com>
# SPDX-License-Identifier: Apache-2.0 OR BSD-3-Clause
__all__ = ("PdfAttachment", )
import ctypes
from codecs import decode
import pypdfium2.raw as pdfium_c
import pypdfium2.internal as pdfium_i
from pypdfium2.internal import FPDF_WCHAR_size
from pypdfium2._helpers.misc import PdfiumError
class PdfAttachment (pdfium_i.AutoCastable):
"""
Attachment helper class. See PDF 1.7, Section 7.11 "File Specifications".
Attributes:
raw (FPDF_ATTACHMENT):
The underlying PDFium attachment handle.
pdf (PdfDocument):
Reference to the document this attachment belongs to. Must remain valid as long as the attachment is used.
"""
# TODO consider using AutoCloseable machienery to guarantee `pdf` remains alive as long as the attachment object exists
# Limitations of PDFium's attachment API: https://crbug.com/pdfium/893
def __init__(self, raw, pdf):
self.raw = raw
self.pdf = pdf
def get_name(self):
"""
Returns:
str: Name of the attachment.
"""
n_bytes = pdfium_c.FPDFAttachment_GetName(self, None, 0)
if not n_bytes:
raise PdfiumError("Failed to get attachment name.")
n_units = -(n_bytes // -FPDF_WCHAR_size) # ceildiv
buffer = (pdfium_c.FPDF_WCHAR * n_units)()
pdfium_c.FPDFAttachment_GetName(self, buffer, n_bytes)
return decode(memoryview(buffer)[:n_units-1], "utf-16-le")
def get_data(self):
"""
Returns:
ctypes.Array: The attachment's file data (as :class:`~ctypes.c_char` array).
"""
n_bytes = ctypes.c_ulong()
pdfium_c.FPDFAttachment_GetFile(self, None, 0, n_bytes)
n_bytes = n_bytes.value
if not n_bytes:
raise PdfiumError(f"Failed to extract attachment (no data).")
buffer = (ctypes.c_char * n_bytes)()
out_buflen = ctypes.c_ulong()
ok = pdfium_c.FPDFAttachment_GetFile(self, buffer, n_bytes, out_buflen)
out_buflen = out_buflen.value
if not ok:
raise PdfiumError("Failed to extract attachment (error status).")
if n_bytes < out_buflen:
raise PdfiumError(f"Failed to extract attachment (expected {n_bytes} bytes, but got {out_buflen}).")
return buffer
def set_data(self, data):
"""
Set the attachment's file data.
If this function is called on an existing attachment, it will be changed to point at the new data, but the previous data will not be removed from the file (as of PDFium 5418).
Parameters:
data (bytes | ctypes.Array):
New file data for the attachment. May be any data type that can be implicitly converted to :class:`~ctypes.c_void_p`.
"""
ok = pdfium_c.FPDFAttachment_SetFile(self, self.pdf, data, len(data))
if not ok:
raise PdfiumError("Failed to set attachment data.")
def has_key(self, key):
"""
Parameters:
key (str):
A key to look for in the attachment's params dictionary.
Returns:
bool: True if *key* is contained in the params dictionary, False otherwise.
"""
return pdfium_c.FPDFAttachment_HasKey(self, (key+"\x00").encode("utf-8"))
def get_value_type(self, key):
"""
Returns:
int: Type of the value of *key* in the params dictionary (:attr:`FPDF_OBJECT_*`).
"""
return pdfium_c.FPDFAttachment_GetValueType(self, (key+"\x00").encode("utf-8"))
def get_str_value(self, key):
"""
Returns:
str: The value of *key* in the params dictionary, if it is a string or name.
Otherwise, an empty string will be returned. On other failures, an exception will be raised.
"""
enc_key = (key+"\x00").encode("utf-8")
n_bytes = pdfium_c.FPDFAttachment_GetStringValue(self, enc_key, None, 0)
if n_bytes <= 0:
raise PdfiumError(f"Failed to get value of key '{key}'.")
n_units = -(n_bytes // -FPDF_WCHAR_size) # ceildiv
buffer = (pdfium_c.FPDF_WCHAR * n_units)()
pdfium_c.FPDFAttachment_GetStringValue(self, enc_key, buffer, n_bytes)
return decode(memoryview(buffer)[:n_units-1], "utf-16-le")
def set_str_value(self, key, value):
"""
Set the attribute specified by *key* to the string *value*.
Parameters:
value (str): New string value for the attribute.
"""
enc_key = (key+"\x00").encode("utf-8")
enc_value = (value+"\x00").encode("utf-16-le")
enc_value_ptr = ctypes.cast(enc_value, pdfium_c.FPDF_WIDESTRING)
ok = pdfium_c.FPDFAttachment_SetStringValue(self, enc_key, enc_value_ptr)
if not ok:
raise PdfiumError(f"Failed to set attachment param '{key}' to '{value}'.")
# The interface of FPDFAttachment_GetSubtype() and FPDFAttachment_GetDescription() seems pretty much the same, just targeting different fields.
def get_subtype(self):
"""
Returns:
str: The attachment's MIME type (``/Subtype``), as string.
Returns an empty string if the attachment does not specify the subtype key.
Hint:
Checking the attached file's signature with ``libmagic`` may be a more reliable way of determining the MIME type; however, this implies calling :meth:`.get_data`.
"""
n_bytes = pdfium_c.FPDFAttachment_GetSubtype(self, None, 0) # including NUL
if n_bytes == FPDF_WCHAR_size:
return ""
elif not n_bytes:
raise PdfiumError("Failed to get attachment subtype")
n_units = -(n_bytes // -FPDF_WCHAR_size) # ceildiv
buffer = (pdfium_c.FPDF_WCHAR * n_units)()
pdfium_c.FPDFAttachment_GetSubtype(self, buffer, n_bytes)
return decode(memoryview(buffer)[:n_units-1], "utf-16-le")
def get_desc(self):
"""
Returns:
str: The attachment's description, or an empty string if the attachment has no description.
"""
n_bytes = pdfium_c.FPDFAttachment_GetDescription(self, None, 0) # including NUL
if n_bytes == FPDF_WCHAR_size:
return ""
elif not n_bytes:
raise PdfiumError("Failed to get attachment description")
n_units = -(n_bytes // -FPDF_WCHAR_size) # ceildiv
buffer = (pdfium_c.FPDF_WCHAR * n_units)()
# NOTE The API unconditionally returns the same value as the previous call, and does not give feedback whether buffer has been actually modified or not.
pdfium_c.FPDFAttachment_GetDescription(self, buffer, n_bytes)
return decode(memoryview(buffer)[:n_units-1], "utf-16-le")
def set_desc(self, string):
"""
Parameters:
string (str): Set the attachment description to this value.
.. versionadded:: 5.14
:meth:`.get_subtype`, :meth:`.get_desc`, :meth:`.set_desc`
"""
enc_string = (string+"\x00").encode("utf-16-le")
enc_string_ptr = ctypes.cast(enc_string, pdfium_c.FPDF_WIDESTRING)
ok = pdfium_c.FPDFAttachment_SetDescription(self, enc_string_ptr)
if not ok:
raise PdfiumError("Failed to set attachment description")
@@ -0,0 +1,417 @@
# SPDX-FileCopyrightText: 2026 geisserml <geisserml@gmail.com>
# SPDX-License-Identifier: Apache-2.0 OR BSD-3-Clause
__all__ = ("PdfBitmap", "PdfPosConv")
import ctypes
import logging
import pypdfium2.raw as pdfium_c
import pypdfium2.internal as pdfium_i
from pypdfium2._helpers.misc import PdfiumError
from pypdfium2._lazy import Lazy
logger = logging.getLogger(__name__)
class PdfBitmap (pdfium_i.AutoCloseable):
"""
Bitmap helper class.
Note:
There are two types of bitmaps, "native" (python or caller-side) and "foreign" (pdfium-internal). When bitmap construction is controlled by the embedder, using the native type is recommended.
Important:
Closing/finalization behavior differs between native and foreign bitmaps.\n
Closing a native bitmap releases the :attr:`.raw` ``FPDF_BITMAP`` shell but does not affect the buffer, and the finalizer is attached to the :class:`.PdfBitmap` wrapper directly.\n
**However, closing a foreign bitmap also frees (invalidates) the buffer, which is a potentially unsafe operation, in that it's down to the caller to ensure the memory represented by** :attr:`.buffer` **is not used after free**, whether directly or indirectly through wrapper objects (such as a numpy array or PIL image derived from the bitmap). In this case, the finalizer is attached to the buffer, so by default the underlying memory remains valid as long as the buffer object is held.
.. versionchanged:: 3.14
``FPDFBitmap_Destroy()`` is now unconditionally called on closing/finalization, including on native bitmaps, to release the ``FPDF_BITMAP`` shell itself. In prior versions, native bitmaps were not finalized and calling :meth:`.close` on a native bitmap was a no-op. This may have caused a small leak.
.. _PIL Modes: https://pillow.readthedocs.io/en/stable/handbook/concepts.html#concept-modes
Attributes:
raw (FPDF_BITMAP):
The underlying PDFium bitmap handle.
buffer (~ctypes.Array[~ctypes.c_ubyte]):
A ctypes array representation of the pixel data (each item is an unsigned byte, i. e. a number ranging from 0 to 255).
width (int):
Width of the bitmap (horizontal size).
height (int):
Height of the bitmap (vertical size).
stride (int):
Number of bytes per line in the bitmap buffer.
Depending on how the bitmap was created, there may be a padding of unused bytes at the end of each line, so this value can be greater than ``width * n_channels``.
format (int):
PDFium bitmap format constant (:attr:`FPDFBitmap_*`)
rev_byteorder (bool):
Whether the bitmap is using reverse byte order.
n_channels (int):
Number of channels per pixel.
mode (str):
The bitmap format as string (see `PIL Modes`_).
warn_on_close (bool):
Whether to warn on explicit closing about being a potentially unsafe operation.
Defaults to True on foreign bitmaps. Set this to False if you are sure your usage of :meth:`.close` is safe. Or set to True to warn regardless of bitmap type.\n
.. versionadded:: 5.14
"""
def __init__(self, raw, buffer, width, height, stride, format, rev_byteorder, is_foreign):
self.raw = raw
self.buffer = buffer
self.width = width
self.height = height
self.stride = stride
self.format = format
self.rev_byteorder = rev_byteorder
self.n_channels = pdfium_i.BitmapTypeToNChannels[self.format]
self.mode = (
pdfium_i.BitmapTypeToStrReverse if self.rev_byteorder else \
pdfium_i.BitmapTypeToStr
)[self.format]
self._is_foreign = is_foreign
self.warn_on_close = is_foreign
# slot to store arguments for PdfPosConv, set on page rendering
self._render_args = None
# NB: With foreign (pdfium-internal) buffers freed by FPDFBitmap_Destroy(), the finalizer ought to be attached to the buffer object itself.
# With native (pdfium-external) buffers unaffected by FPDFBitmap_Destroy(), it's fine to couple the FPDF_BITMAP's scope with the PdfBitmap wrapper directly, as only the shell is released (not the buffer).
super().__init__(pdfium_c.FPDFBitmap_Destroy, obj=(self.buffer if is_foreign else None), tracked=False)
def close(self, *args, **kwargs):
"""
Explicitly close the bitmap, and *potentially* free its buffer, depending on the bitmap type: Closing a foreign bitmap invalidates the buffer, whereas a native bitmap buffer survives.
Confer the top-level :class:`.PdfBitmap` documentation for details.
Warning:
Only call this method if you are fully aware of the potential memory safety implications, and are sure your use is safe and appropriate.\n
**Tip:** Where possible, consider ensuring the use of native bitmaps only.
.. versionchanged:: 5.14
Calling this method on a foreign bitmap now logs a warning by default, to help prevent callers from creating a possible use-after-free situation. See :attr:`.warn_on_close`.
"""
if self.warn_on_close:
logger.warning(f"Explicitly closing {self!r}. This is a potentially unsafe operation!")
super().close(*args, **kwargs)
def __repr__(self):
status = "foreign" if self._is_foreign else "native"
return f"{super().__repr__()[:-1]} @ {status}>"
@property
def parent(self): # AutoCloseable hook
return None
# NOTE To test all bitmap creation strategies through the CLI:
# MAKERS=(native foreign foreign_packed foreign_simple)
# DOCPATH="..." # ideally use a short one or pass e.g. --pages "1-3"
# for MAKER in ${MAKERS[@]}; do echo "$MAKER"; mkdir -p out/$MAKER; pypdfium2 render "$DOCPATH" -o out/$MAKER --bitmap-maker $MAKER; done
# To test .from_raw():
# pypdfium2 extract-images "$DOCPATH" -o out/ --use-bitmap
@staticmethod
def _get_buffer(raw, stride, height):
buffer_ptr = pdfium_c.FPDFBitmap_GetBuffer(raw)
if not buffer_ptr:
raise PdfiumError("Failed to get bitmap buffer (null pointer returned)")
buffer_ptr = ctypes.cast(buffer_ptr, ctypes.POINTER(ctypes.c_ubyte))
return pdfium_i.get_buffer(buffer_ptr, stride*height)
@classmethod
def from_raw(cls, raw, rev_byteorder=False, ex_buffer=None):
"""
Construct a :class:`.PdfBitmap` wrapper around a raw PDFium bitmap handle.
Note:
This method is primarily meant for bitmaps provided by pdfium (as in :meth:`.PdfImage.get_bitmap`).
For bitmaps created on our side, the parameters are already known, so the :class:`.PdfBitmap` can be constructed directly.
Parameters:
raw (FPDF_BITMAP):
PDFium bitmap handle.
rev_byteorder (bool):
Whether the bitmap uses reverse byte order.
ex_buffer (~ctypes.Array[~ctypes.c_ubyte] | None):
If the bitmap was created from a buffer allocated by Python/ctypes, pass in the ctypes array to keep it referenced.
"""
width = pdfium_c.FPDFBitmap_GetWidth(raw)
height = pdfium_c.FPDFBitmap_GetHeight(raw)
stride = pdfium_c.FPDFBitmap_GetStride(raw)
format = pdfium_c.FPDFBitmap_GetFormat(raw)
if ex_buffer is None:
buffer = cls._get_buffer(raw, stride, height)
is_foreign = True
else:
buffer = ex_buffer
is_foreign = False
return cls(raw, buffer, width, height, stride, format, rev_byteorder, is_foreign)
@classmethod
def new_native(cls, width, height, format, rev_byteorder=False, buffer=None, stride=None):
"""
Create a new bitmap using :func:`FPDFBitmap_CreateEx`, with a buffer allocated by Python/ctypes, or provided by the caller.
* If buffer and stride are None, a packed buffer is created.
* If a custom buffer is given but no stride, the buffer is assumed to be packed.
* If a custom stride is given but no buffer, a stride-agnostic buffer is created.
* If both custom buffer and stride are given, they are used as-is.
Caller-provided buffer/stride are subject to a logical validation.
"""
bpc = pdfium_i.BitmapTypeToNChannels[format]
if stride is None:
stride = width * bpc
else:
assert stride >= width * bpc
if buffer is None:
buffer = (ctypes.c_ubyte * (stride * height))()
else:
assert len(buffer) >= stride * height
raw = pdfium_c.FPDFBitmap_CreateEx(width, height, format, buffer, stride)
return cls(raw, buffer, width, height, stride, format, rev_byteorder, is_foreign=False)
# Alternatively, we could do:
# return cls.from_raw(raw, rev_byteorder, buffer)
# This implies some (technically unnecessary) API calls. Note, for a short time, there was a bug in pdfium where retrieving the params of a caller-created bitmap through the FPDFBitmap_Get*() APIs didn't work correctly, so better avoid doing this if we can help it.
@classmethod
def new_foreign(cls, width, height, format, rev_byteorder=False, force_packed=False):
"""
Create a new bitmap using :func:`FPDFBitmap_CreateEx`, with a buffer allocated by PDFium.
There may be a padding of unused bytes at line end, unless *force_packed=True* is given.
Note, the recommended default bitmap creation strategy is :meth:`.new_native`.
"""
stride = width * pdfium_i.BitmapTypeToNChannels[format] if force_packed else 0
raw = pdfium_c.FPDFBitmap_CreateEx(width, height, format, None, stride)
# Retrieve stride set by pdfium, if we passed in 0. Otherwise, trust in pdfium to use the requested stride.
if not force_packed: # stride == 0
stride = pdfium_c.FPDFBitmap_GetStride(raw)
buffer = cls._get_buffer(raw, stride, height)
return cls(raw, buffer, width, height, stride, format, rev_byteorder, is_foreign=True)
@classmethod
def new_foreign_simple(cls, width, height, use_alpha, rev_byteorder=False):
"""
Create a new bitmap using :func:`FPDFBitmap_Create`. The buffer is allocated by PDFium.
PDFium docs specify that each line uses width * 4 bytes, with no gap between adjacent lines, i.e. the resulting buffer should be packed.
Contrary to the other ``PdfBitmap.new_*()`` APIs, this method does not take a format constant, but a *use_alpha* boolean. If True, the format will be :attr:`FPDFBitmap_BGRA`, :attr:`FPFBitmap_BGRx` otherwise. Other bitmap formats cannot be used with this method.
Note, the recommended default bitmap creation strategy is :meth:`.new_native`.
"""
raw = pdfium_c.FPDFBitmap_Create(width, height, use_alpha)
stride = width * 4 # see above
buffer = cls._get_buffer(raw, stride, height)
format = pdfium_c.FPDFBitmap_BGRA if use_alpha else pdfium_c.FPDFBitmap_BGRx
return cls(raw, buffer, width, height, stride, format, rev_byteorder, is_foreign=True)
def fill_rect(self, color, left, top, width, height):
"""
Fill a rectangle on the bitmap with the given color.
The coordinate system's origin is the top left corner of the image.
Note:
This function replaces the color values in the given rectangle. It does not perform alpha compositing.
Parameters:
color (tuple[int, int, int, int]):
RGBA fill color (a tuple of 4 integers ranging from 0 to 255).
"""
c_color = pdfium_i.color_tohex(color, self.rev_byteorder)
ok = pdfium_c.FPDFBitmap_FillRect(self, left, top, width, height, c_color)
if not ok:
raise PdfiumError("Failed to fill bitmap rectangle.")
# IMPORTANT: When a wrapper is constructed around a foreign bitmap without copying (i.e. as a view of the same memory), we rely on the assumption that the wrapper holds a reference to the input buffer object itself while the represented memory is used.
# This appears to be the case with Pillow and NumPy, as of 2026. When adding a new adapter, it needs to be carefully tested to fulfill this requirement.
# Why not attach a buffer keep-alive finalizer to wrapper objects?, you might ask. That's a good question, and we could consider doing that, but there are issues: Suppose the adapter made a copy after all, we'd unnecessarily delay releasing memory. Copying is kind of an implementation detail of the adapter's (consider Pillow, where it is format dependent; consider things like copy-on-write). Or suppose the buffer is transferred to another object, we still face the original problem. So this isn't necessarily helpful, is it?
def to_numpy(self):
"""
Get a :mod:`numpy` array view of the bitmap.
The array contains as many rows as the bitmap is high.
Each row contains as many pixels as the bitmap is wide.
Each pixel will be an array holding the channel values, or just a value if there is only one channel (see :attr:`.n_channels` and :attr:`.format`).
The resulting array is supposed to share memory with the original bitmap buffer,
so changes to the buffer should be reflected in the array, and vice versa.
Returns:
numpy.ndarray: NumPy array (representation of the bitmap buffer).
"""
# https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray
array = Lazy.numpy.ndarray(
# layout: row major
shape = (self.height, self.width, self.n_channels) if self.n_channels > 1 else (self.height, self.width),
dtype = ctypes.c_ubyte,
buffer = self.buffer,
# number of bytes per item for each nesting level (outer->inner: row, pixel, value - or row, value for a single-channel bitmap)
strides = (self.stride, self.n_channels, 1) if self.n_channels > 1 else (self.stride, 1),
)
return array
def to_pil(self):
"""
Get a :mod:`PIL` image of the bitmap, using :func:`PIL.Image.frombuffer`.
For ``RGBA``, ``RGBX`` and ``L`` bitmaps, PIL is supposed to share memory with
the original buffer, so changes to the buffer should be reflected in the image, and vice versa.
Otherwise, PIL will make a copy of the data.
Returns:
PIL.Image.Image: PIL image (representation or copy of the bitmap buffer).
"""
# https://pillow.readthedocs.io/en/stable/reference/Image.html#PIL.Image.frombuffer
# https://pillow.readthedocs.io/en/stable/handbook/writing-your-own-image-plugin.html#the-raw-decoder
dest_mode = pdfium_i.BitmapTypeToStrReverse[self.format]
image = Lazy.PIL_Image.frombuffer(
dest_mode, # target color format
(self.width, self.height), # size
self.buffer, # buffer
"raw", # decoder
self.mode, # input color format
self.stride, # bytes per line
1, # orientation (top->bottom)
)
# set `readonly = False` so changes to the image are reflected in the buffer, if the original buffer is used
image.readonly = False
return image
@classmethod
def from_pil(cls, pil_image):
"""
Convert a :mod:`PIL` image to a PDFium bitmap.
Due to the limited number of color formats and bit depths supported by :attr:`FPDF_BITMAP`, this may be a lossy operation.
Bitmaps returned by this function should be treated as immutable.
Parameters:
pil_image (PIL.Image.Image):
The image.
Returns:
PdfBitmap: PDFium bitmap (with a copy of the PIL image's data).
"""
# FIXME possibility to get mutable buffer from PIL image?
if pil_image.mode in pdfium_i.BitmapStrToConst:
# PIL always seems to represent BGR(A/X) input as RGB(A/X), so this code passage would only be reached for L
format = pdfium_i.BitmapStrToConst[pil_image.mode]
else:
pil_image = _pil_convert_for_pdfium(pil_image)
format = pdfium_i.BitmapStrReverseToConst[pil_image.mode]
w, h = pil_image.size
return cls.new_native(w, h, format, rev_byteorder=False, buffer=pil_image.tobytes())
def get_posconv(self, page):
"""
Acquire a :class:`.PdfPosConv` object to translate between coordinates on the bitmap and the page it was rendered from.
This method requires passing in the page explicitly, to avoid holding a strong reference, so that bitmap and page can be independently freed by finalizer.
"""
# make sure *page* isn't None because that's what the weakref may resolve to if the referenced object is not alive anymore
assert page, "Page must be non-null"
if not self._render_args:
raise RuntimeError("This bitmap does not belong to a page.")
page_wref, pos_args = self._render_args
if page_wref() is not page:
raise RuntimeError("This bitmap does not belong to the given page.")
return PdfPosConv(page, pos_args)
def _pil_convert_for_pdfium(pil_image):
if pil_image.mode == "1":
pil_image = pil_image.convert("L")
elif pil_image.mode.startswith("RGB"):
pass
elif "A" in pil_image.mode:
pil_image = pil_image.convert("RGBA")
else:
pil_image = pil_image.convert("RGB")
# convert RGB(A/X) to BGR(A) for PDFium
if pil_image.mode == "RGB":
r, g, b = pil_image.split()
pil_image = Lazy.PIL_Image.merge("RGB", (b, g, r))
elif pil_image.mode == "RGBA":
r, g, b, a = pil_image.split()
pil_image = Lazy.PIL_Image.merge("RGBA", (b, g, r, a))
elif pil_image.mode == "RGBX":
# technically the x channel may be unnecessary, but preserve what the caller passes in
r, g, b, x = pil_image.split()
pil_image = Lazy.PIL_Image.merge("RGBX", (b, g, r, x))
return pil_image
class PdfPosConv:
"""
Pdf coordinate translator.
Hint:
You may want to use :meth:`.PdfBitmap.get_posconv` to obtain an instance of this class.
Parameters:
page (PdfPage):
Handle to the page.
pos_args (tuple[int*5]):
pdfium canvas args (start_x, start_y, size_x, size_y, rotate), as in ``FPDF_RenderPageBitmap()`` etc.
"""
# FIXME do we have to do overflow checking against too large sizes?
def __init__(self, page, pos_args):
self.page = page
self.pos_args = pos_args
def __repr__(self):
return f"{PdfPosConv.__name__}({self.page}, {self.pos_args})"
def to_page(self, bitmap_x, bitmap_y):
"""
Translate coordinates from bitmap to page.
"""
page_x, page_y = ctypes.c_double(), ctypes.c_double()
ok = pdfium_c.FPDF_DeviceToPage(self.page, *self.pos_args, bitmap_x, bitmap_y, page_x, page_y)
if not ok:
raise PdfiumError("Failed to translate to page coordinates.")
return (page_x.value, page_y.value)
def to_bitmap(self, page_x, page_y):
"""
Translate coordinates from page to bitmap.
"""
bitmap_x, bitmap_y = ctypes.c_int(), ctypes.c_int()
ok = pdfium_c.FPDF_PageToDevice(self.page, *self.pos_args, page_x, page_y, bitmap_x, bitmap_y)
if not ok:
raise PdfiumError("Failed to translate to bitmap coordinates.")
return (bitmap_x.value, bitmap_y.value)
@@ -0,0 +1,787 @@
# SPDX-FileCopyrightText: 2026 geisserml <geisserml@gmail.com>
# SPDX-License-Identifier: Apache-2.0 OR BSD-3-Clause
__all__ = ("PdfDocument", "PdfFormEnv", "PdfXObject", "PdfBookmark", "PdfBookmarkStyle", "PdfDest")
import sys
import enum
import ctypes
import logging
import warnings
from pathlib import Path
from codecs import decode
import pypdfium2.raw as pdfium_c
import pypdfium2.internal as pdfium_i
from pypdfium2.version import PDFIUM_INFO
from pypdfium2._helpers.misc import PdfiumError, PdfiumWarning
from pypdfium2._helpers.page import PdfPage
from pypdfium2._helpers.pageobjects import PdfObject
from pypdfium2._helpers.attachment import PdfAttachment
logger = logging.getLogger(__name__)
class PdfDocument (pdfium_i.AutoCloseable):
"""
Document helper class.
Parameters:
input (str | pathlib.Path | bytes | ctypes.Array | typing.BinaryIO | FPDF_DOCUMENT):
The input PDF given as file path, bytes, ctypes array, readable byte stream, or raw PDFium document handle.
A readable byte stream is considered an object that implements ``seek() tell() read() readinto()`` in line with the usual :mod:`io` protocols.
If input is file-based (as opposed to in-memory), the backing file must (obviously) remain intact and not be modified while the document handle is used. This goes for both file paths and streams.
password (str | None):
A password to unlock the PDF, if encrypted. Otherwise, None or an empty string may be passed.
If a password is given but the PDF is not encrypted, it will be ignored (as of PDFium 5418).
autoclose (bool):
Whether byte stream input should be automatically closed on finalization.
Raises:
PdfiumError: Raised if the document failed to load. The exception is annotated with the reason reported by PDFium (via message and :attr:`~.PdfiumError.err_code`).
FileNotFoundError: Raised if an invalid or non-existent file path was given.
Hint:
* Documents may be used in a ``with``-block, closing the document on context manager exit.
This is recommended when *input_data* is a file path, to safely and immediately release the bound file handle.
* :func:`len` may be called to get a document's number of pages.
* Pages may be loaded using list index access.
* Looping over a document will yield its pages from beginning to end.
* The ``del`` keyword and list index access may be used to delete pages.
Attributes:
raw (FPDF_DOCUMENT):
The underlying PDFium document handle.
"""
def __init__(self, input, password=None, autoclose=False):
if isinstance(input, str):
input = Path(input)
if isinstance(input, Path):
input = input.expanduser().resolve()
if not input.is_file():
raise FileNotFoundError(input)
self._input = input
self._password = password
self._autoclose = autoclose
self._data_holder = []
self._data_closer = []
self._formenv_holder = _ObjectHolder(None)
if isinstance(self._input, pdfium_c.FPDF_DOCUMENT):
self.raw = self._input
else:
self.raw, to_hold, to_close = _open_pdf(self._input, self._password, self._autoclose)
self._data_holder += to_hold
self._data_closer += to_close
super().__init__(PdfDocument._close_impl, self._formenv_holder, self._data_holder, self._data_closer, tracked=False)
# Support using PdfDocument in a with-block
# Note that pdfium objects should be closed in hierarchial order, but this is managed by our parents/kids system, so callers don't need to mind that.
def __enter__(self):
return self
def __exit__(self, *_):
self.close()
def __repr__(self):
if isinstance(self._input, Path):
input_r = repr( str(self._input) )
elif isinstance(self._input, bytes):
input_r = f"<bytes object at {hex(id(self._input))}>"
elif isinstance(self._input, pdfium_c.FPDF_DOCUMENT):
input_r = f"<FPDF_DOCUMENT at {hex(id(self._input))}>"
else:
input_r = repr(self._input)
return f"{super().__repr__()[:-1]} from {input_r}>"
@property
def parent(self): # AutoCloseable hook
return None
@staticmethod
def _close_impl(raw, formenv_holder, data_holder, data_closer):
formenv = formenv_holder.obj
if formenv:
_formenv_close_impl(formenv, caller_info="auto, within_parent")
formenv_holder.obj = None
pdfium_c.FPDF_CloseDocument(raw)
for data in data_holder:
id(data)
for data in data_closer:
data.close()
data_holder.clear()
data_closer.clear()
def __len__(self):
return pdfium_c.FPDF_GetPageCount(self)
def __iter__(self):
for i in range( len(self) ):
yield self[i]
def __getitem__(self, i):
return self.get_page(i)
def __delitem__(self, i):
self.del_page(i)
@classmethod
def new(cls):
"""
Returns:
PdfDocument: A new, empty document.
"""
new_pdf = pdfium_c.FPDF_CreateNewDocument()
return cls(new_pdf)
@property
def formenv(self):
"""
PdfFormEnv | None: Form env, if the document has forms and :meth:`.init_forms` was called.
"""
return self._formenv_holder.obj
@formenv.setter
def formenv(self, value):
self._formenv_holder.obj = value
def init_forms(self, config=None):
"""
Initialize a form env, if the document has forms.
If already initialized, nothing will be done. See the :attr:`formenv` property.
If PDFium was built with XFA support and the PDF has XFA forms, it will be attempted to load these as well.
Attention:
If form rendering is desired, this method shall be called right after document construction, before getting document length or page handles.
Parameters:
config (FPDF_FORMFILLINFO | None):
Custom form config interface to use (optional).
Raises:
PdfiumWarning: When an attempt to load XFA forms was made and it failed, a warning will be issued using :func:`warnings.warn`, with :attr:`~.PdfiumWarning.err_code` information (:attr:`FPDF_ERR_XFA*`).
"""
formtype = self.get_formtype()
if formtype == pdfium_c.FORMTYPE_NONE or self.formenv:
return False
if not config:
if "XFA" in PDFIUM_INFO.flags: # pragma: no cover
js_platform = pdfium_c.IPDF_JSPLATFORM(version=3)
config = pdfium_c.FPDF_FORMFILLINFO(version=2, xfa_disabled=False, m_pJsPlatform=ctypes.pointer(js_platform))
else:
config = pdfium_c.FPDF_FORMFILLINFO(version=2)
raw = pdfium_c.FPDFDOC_InitFormFillEnvironment(self, config)
if not raw:
raise PdfiumError(f"Initializing form env failed for document {self}.")
self.formenv = PdfFormEnv(raw, config)
if formtype in (pdfium_c.FORMTYPE_XFA_FULL, pdfium_c.FORMTYPE_XFA_FOREGROUND):
if "XFA" in PDFIUM_INFO.flags: # pragma: no cover
ok = pdfium_c.FPDF_LoadXFA(self)
if not ok:
err = pdfium_c.FPDF_GetLastError()
warnings.warn(PdfiumWarning(f"FPDF_LoadXFA() failed with {pdfium_i.XFAErrorToStr.get(err)}", err))
else:
logger.warning(
"init_forms() called on XFA pdf, but this pdfium binary was compiled without XFA support.\n"
"Run `PDFIUM_PLATFORM=auto-v8 pip install -v pypdfium2 --no-binary pypdfium2` to get a build with XFA support."
)
return True
def close_forms(self, _caller_info="explicit"):
"""
Manually close the formenv, if initialized.
Formenvs that were not explicitly closed will be closed when their PDF is closed.
.. versionadded:: 5.10
"""
if not self.formenv:
return False
_formenv_close_impl(self.formenv, caller_info=_caller_info)
self.formenv = None
return True
def get_formtype(self):
"""
Returns:
int: PDFium form type that applies to the document (:attr:`FORMTYPE_*`).
:attr:`FORMTYPE_NONE` if the document has no forms.
"""
return pdfium_c.FPDF_GetFormType(self)
def get_pagemode(self):
"""
Returns:
int: Page displaying mode (:attr:`PAGEMODE_*`).
"""
return pdfium_c.FPDFDoc_GetPageMode(self)
def is_tagged(self):
"""
Returns:
bool: Whether the document is tagged (cf. PDF 1.7, 10.7 "Tagged PDF").
"""
return pdfium_c.FPDFCatalog_IsTagged(self) == 1
def save(self, dest, version=None, flags=0):
"""
Save the document at its current state.
Parameters:
dest (str | pathlib.Path | io.BytesIO):
File path or output byte stream the document shall be written to.
An output byte stream is considered an object that implements a ``write()`` method which acts like :meth:`io.BufferedIOBase.write`.
Implementation detail: The ``write()`` adapter is expected to have written out all bytes given, if it returned without raising an exception. The return value is not checked.
version (int | None):
The PDF version to use, given as an integer (14 for 1.4, 15 for 1.5, ...).
If None (the default), PDFium will set a version automatically.
flags (int):
PDFium saving flags (defaults to 0).
"""
if isinstance(dest, (str, Path)):
buffer, need_close = open(dest, "wb"), True
elif pdfium_i.is_stream(dest, "w"):
buffer, need_close = dest, False
else:
raise ValueError(f"Cannot save to '{dest}'")
try:
saveargs = (self, pdfium_i.get_bufwriter(buffer), flags)
ok = pdfium_c.FPDF_SaveAsCopy(*saveargs) if version is None else pdfium_c.FPDF_SaveWithVersion(*saveargs, version)
if not ok:
raise PdfiumError("Failed to save document.")
finally:
if need_close:
buffer.close()
def get_identifier(self, type=pdfium_c.FILEIDTYPE_PERMANENT):
"""
Parameters:
type (int):
The identifier type to retrieve (:attr:`FILEIDTYPE_*`), either permanent or changing.
If the file was updated incrementally, the permanent identifier stays the same,
while the changing identifier is re-calculated.
Returns:
bytes: Unique file identifier from the PDF's trailer dictionary, or an empty bytestring if it could not be determined. See PDF 1.7, Section 14.4 "File Identifiers".
"""
n_bytes = pdfium_c.FPDF_GetFileIdentifier(self, type, None, 0)
if not n_bytes:
return b""
buffer = (ctypes.c_char * n_bytes)()
pdfium_c.FPDF_GetFileIdentifier(self, type, buffer, n_bytes)
# TODO(apibreak) change return type to avoid copy
return memoryview(buffer)[:n_bytes-1].tobytes()
def get_version(self):
"""
Returns:
int | None: The PDF version of the document (14 for 1.4, 15 for 1.5, ...),
or None if the document is new or its version could not be determined.
"""
version = ctypes.c_int()
ok = pdfium_c.FPDF_GetFileVersion(self, version)
if not ok:
return None
return version.value
def get_metadata_value(self, key):
"""
Returns:
str: Value of the given key in the PDF's metadata dictionary.
If the key is not contained, an empty string will be returned.
"""
enc_key = (key + "\x00").encode("utf-8")
n_bytes = pdfium_c.FPDF_GetMetaText(self, enc_key, None, 0)
buffer = ctypes.create_string_buffer(n_bytes)
pdfium_c.FPDF_GetMetaText(self, enc_key, buffer, n_bytes)
return decode(memoryview(buffer)[:n_bytes-2], "utf-16-le")
METADATA_KEYS = ("Title", "Author", "Subject", "Keywords", "Creator", "Producer", "CreationDate", "ModDate")
def get_metadata_dict(self, skip_empty=False):
"""
Get the document's metadata as dictionary.
Parameters:
skip_empty (bool):
If True, skip items whose value is an empty string.
Returns:
dict: PDF metadata.
"""
metadata = {k: self.get_metadata_value(k) for k in self.METADATA_KEYS}
if skip_empty:
metadata = {k: v for k, v in metadata.items() if v}
return metadata
def count_attachments(self):
"""
Returns:
int: The number of embedded files in the document.
"""
return pdfium_c.FPDFDoc_GetAttachmentCount(self)
def get_attachment(self, index):
"""
Returns:
PdfAttachment: The attachment at given index (zero-based).
"""
raw_attachment = pdfium_c.FPDFDoc_GetAttachment(self, index)
if not raw_attachment:
raise PdfiumError(f"Failed to get attachment at index {index}.")
return PdfAttachment(raw_attachment, self)
def new_attachment(self, name):
"""
Add a new attachment to the document. It may appear at an arbitrary index (as of PDFium 5418).
Parameters:
name (str):
The name the attachment shall have. Usually a file name with extension.
Returns:
PdfAttachment: Handle to the new, empty attachment.
"""
enc_name = (name + "\x00").encode("utf-16-le")
enc_name_ptr = ctypes.cast(enc_name, pdfium_c.FPDF_WIDESTRING)
raw_attachment = pdfium_c.FPDFDoc_AddAttachment(self, enc_name_ptr)
if not raw_attachment:
raise PdfiumError(f"Failed to create new attachment '{name}'.")
return PdfAttachment(raw_attachment, self)
def del_attachment(self, index):
"""
Unlink the attachment at given index (zero-based).
It will be hidden from the viewer, but is still present in the file (as of PDFium 5418).
Following attachments shift one slot to the left in the array representation used by PDFium's API.
Handles to the attachment in question received from :meth:`.get_attachment`
must not be accessed anymore after this method has been called.
"""
ok = pdfium_c.FPDFDoc_DeleteAttachment(self, index)
if not ok:
raise PdfiumError(f"Failed to delete attachment at index {index}.")
def get_page(self, index):
"""
Returns:
PdfPage: The page at given index (zero-based).
Note:
This calls ``FORM_OnAfterLoadPage()`` if the document has an active form env.
In that case, note that closing the formenv would implicitly close the page.
"""
raw_page = pdfium_c.FPDF_LoadPage(self, index)
if not raw_page:
raise PdfiumError("Failed to load page.")
page = PdfPage(raw_page, self, self.formenv)
if self.formenv:
pdfium_c.FORM_OnAfterLoadPage(page, self.formenv)
self._add_kid(page)
return page
def new_page(self, width, height, index=None):
"""
Insert a new, empty page into the document.
Parameters:
width (float):
Target page width (horizontal size).
height (float):
Target page height (vertical size).
index (int | None):
Suggested zero-based index at which the page shall be inserted.
If None or larger that the document's current last index, the page will be appended to the end.
Returns:
PdfPage: The newly created page.
"""
if index is None:
index = len(self)
raw_page = pdfium_c.FPDFPage_New(self, index, width, height)
page = PdfPage(raw_page, self, None)
# not doing formenv calls for new pages
self._add_kid(page)
return page
def del_page(self, index):
"""
Remove the page at given index (zero-based).
It is recommended to close any open handles to the page before calling this method.
"""
# FIXME not sure how pdfium would behave if the caller tries to access a handle to a deleted page...
pdfium_c.FPDFPage_Delete(self, index)
def import_pages(self, pdf, pages=None, index=None):
"""
Import pages from a foreign document.
Parameters:
pdf (PdfDocument):
The document from which to import pages.
pages (list[int] | str | None):
The pages to include. It may either be a list of zero-based page indices, or a string of one-based page numbers and ranges.
If None, all pages will be included.
index (int):
Zero-based index at which to insert the given pages. If None, they are appended to the end of the document.
"""
if index is None:
index = len(self)
if isinstance(pages, str):
ok = pdfium_c.FPDF_ImportPages(self, pdf, pages.encode("ascii"), index)
else:
page_count = 0
c_pages = None
if pages:
page_count = len(pages)
c_pages = (ctypes.c_int * page_count)(*pages)
ok = pdfium_c.FPDF_ImportPagesByIndex(self, pdf, c_pages, page_count, index)
if not ok:
raise PdfiumError("Failed to import pages.")
def get_page_size(self, index):
"""
Returns:
(float, float): Width and height of the page at given index (zero-based), in PDF canvas units.
"""
size = pdfium_c.FS_SIZEF()
ok = pdfium_c.FPDF_GetPageSizeByIndexF(self, index, size)
if not ok:
raise PdfiumError("Failed to get page size by index.")
return (size.width, size.height)
def get_page_label(self, index):
"""
Returns:
str: Label of the page at given index (zero-based).
(A page label is essentially an alias that may be displayed instead of the page number.)
"""
n_bytes = pdfium_c.FPDF_GetPageLabel(self, index, None, 0)
buffer = ctypes.create_string_buffer(n_bytes)
pdfium_c.FPDF_GetPageLabel(self, index, buffer, n_bytes)
return decode(memoryview(buffer)[:n_bytes-2], "utf-16-le")
def page_as_xobject(self, index, dest_pdf):
"""
Capture a page as XObject and attach it to a document's resources.
Parameters:
index (int):
Zero-based index of the page.
dest_pdf (PdfDocument):
Target document to which the XObject shall be added.
Returns:
PdfXObject: The page as XObject.
"""
raw_xobject = pdfium_c.FPDF_NewXObjectFromPage(dest_pdf, self, index)
if not raw_xobject:
raise PdfiumError(f"Failed to capture page at index {index} as FPDF_XOBJECT.")
xobject = PdfXObject(raw=raw_xobject, pdf=dest_pdf)
dest_pdf._add_kid(xobject)
return xobject
def get_toc(
self,
max_depth = 15,
parent = None,
level = 0,
seen = None,
):
"""
Iterate through the bookmarks in the document's table of contents (TOC).
Parameters:
max_depth (int):
Maximum recursion depth to consider.
Yields:
:class:`.PdfBookmark`
"""
if seen is None:
seen = set()
bm_ptr = pdfium_c.FPDFBookmark_GetFirstChild(self, parent)
# NOTE We need bool(ptr) here to handle null pointers (where accessing .contents would raise an exception). Don't use ptr != None, it's always true.
while bm_ptr:
address = ctypes.addressof(bm_ptr.contents)
if address in seen:
logger.warning("A circular bookmark reference was detected while traversing the table of contents.")
break
else:
seen.add(address)
yield PdfBookmark(bm_ptr, self, level)
if level < max_depth-1:
yield from self.get_toc(max_depth=max_depth, parent=bm_ptr, level=level+1, seen=seen)
elif pdfium_c.FPDFBookmark_GetFirstChild(self, bm_ptr):
# Warn only if there actually is a subtree. If level == max_depth but the tree ends there, it's fine as no info is skipped.
logger.warning(f"Maximum recursion depth {max_depth} reached (subtree skipped).")
bm_ptr = pdfium_c.FPDFBookmark_GetNextSibling(self, bm_ptr)
_ENC_ERRHANDLER = "strict" if sys.platform.startswith("win32") else "surrogateescape"
def _open_pdf(input_data, password, autoclose):
to_hold, to_close = (), ()
if password is not None:
password = (password+"\x00").encode("utf-8")
if isinstance(input_data, Path):
pdf = pdfium_c.FPDF_LoadDocument((str(input_data)+"\x00").encode("utf-8", errors=_ENC_ERRHANDLER), password)
elif isinstance(input_data, (bytes, ctypes.Array)):
pdf = pdfium_c.FPDF_LoadMemDocument64(input_data, len(input_data), password)
to_hold = (input_data, )
elif pdfium_i.is_stream(input_data, "r"):
bufaccess, to_hold = pdfium_i.get_bufreader(input_data)
if autoclose:
to_close = (input_data, )
pdf = pdfium_c.FPDF_LoadCustomDocument(bufaccess, password)
else:
raise TypeError(f"Invalid input type '{type(input_data).__name__}'")
if pdfium_c.FPDF_GetPageCount(pdf) < 1:
err_code = pdfium_c.FPDF_GetLastError()
raise PdfiumError(f"Failed to load document (PDFium: {pdfium_i.ErrorToStr.get(err_code)}).", err_code=err_code)
return pdf, to_hold, to_close
class _ObjectHolder:
__slots__ = ("obj", )
def __init__(self, obj):
self.obj = obj
class PdfFormEnv (pdfium_i.AutoCastable):
"""
Form environment helper class.
.. versionchanged:: 5.10
The ``pdf`` attribute and ``parent`` alias had to be removed to fix possible trouble with finalization due to an indirect self-reference.
Formenv lifetime is now managed through the parent :class:`.PdfDocument` itself to break a reference circle.
Attributes:
raw (FPDF_FORMHANDLE):
The underlying PDFium form env handle.
config (FPDF_FORMFILLINFO):
Accompanying form configuration interface, to be kept alive.
"""
def __init__(self, raw, config):
self.raw = raw
self.config = config
def close(self):
"""
.. deprecated:: 5.10
This method is now a no-op. Please use :meth:`.PdfDocument.close_forms` instead.
"""
# Explicit closing should clean up the .formenv attribute from the parent document, so it cannot be implemented here.
warnings.warn("PdfFormEnv.close() is deprecated and now a no-op. Please use PdfDocument.close_forms() instead.", category=DeprecationWarning)
def _formenv_close_impl(formenv, caller_info=""):
if not formenv.raw:
return False
pdfium_i._debug_close(f"Close ({caller_info}) {formenv}")
pdfium_c.FPDFDOC_ExitFormFillEnvironment(formenv.raw)
formenv.raw = None
id(formenv.config)
return True
class PdfXObject (pdfium_i.AutoCloseable):
"""
XObject helper class.
Attributes:
raw (FPDF_XOBJECT): The underlying PDFium XObject handle.
pdf (PdfDocument): Reference to the document this XObject belongs to.
"""
def __init__(self, raw, pdf):
self.raw = raw
self.pdf = pdf
super().__init__(pdfium_c.FPDF_CloseXObject)
@property
def parent(self): # AutoCloseable hook
return self.pdf
def as_pageobject(self):
"""
Returns:
PdfObject: An independent pageobject representation of the XObject.
If multiple pageobjects are created from an XObject, they share resources.
Returned pageobjects remain valid after the XObject is closed.
"""
raw_pageobj = pdfium_c.FPDF_NewFormObjectFromXObject(self)
# not a child object (see above)
return PdfObject(raw=raw_pageobj, pdf=self.pdf) # tracked=False
_flag_kws = dict()
if sys.version_info >= (3, 11):
_flag_kws["boundary"] = enum.KEEP
class PdfBookmarkStyle (enum.Flag, **_flag_kws):
ITALIC = 0b01
BOLD = 0b10
class PdfBookmark (pdfium_i.AutoCastable):
"""
Bookmark helper class.
Attributes:
raw (FPDF_BOOKMARK):
The underlying PDFium bookmark handle.
pdf (PdfDocument):
Reference to the document this bookmark belongs to.
level (int):
The bookmark's nesting level in the TOC tree (zero-based). Corresponds to the number of parent bookmarks.
"""
def __init__(self, raw, pdf, level):
self.raw = raw
self.pdf = pdf
self.level = level
def get_title(self):
"""
Returns:
str: The bookmark's title string.
"""
n_bytes = pdfium_c.FPDFBookmark_GetTitle(self, None, 0)
buffer = ctypes.create_string_buffer(n_bytes)
pdfium_c.FPDFBookmark_GetTitle(self, buffer, n_bytes)
return decode(memoryview(buffer)[:n_bytes-2], "utf-16-le")
def get_count(self):
"""
Returns:
int: Signed number of child bookmarks that would be visible if the bookmark were open (i.e. recursively counting children of open children).
The bookmark's initial state is open (expanded) if the number is positive, closed (collapsed) if negative.
Zero if the bookmark has no descendants.
"""
return pdfium_c.FPDFBookmark_GetCount(self)
def get_color(self):
"""
Returns:
tuple[float,float,float] | None: The bookmark's RGB color as float values between 0 and 1, or None if the bookmark does not define a (valid) color.
.. versionadded:: 5.11
"""
# requires pdfium > 7912
r, g, b = ctypes.c_float(), ctypes.c_float(), ctypes.c_float()
ok = pdfium_c.FPDFBookmark_GetColor(self, r, g, b)
if not ok:
return None
return r.value, g.value, b.value
def get_style(self):
"""
Returns:
PdfBookmarkStyle: The bookmark's text style (none, bold, italic, or both) as :class:`enum.Flag`.
Note:
In Python >= 3.11, unhandled values are treated gracefully via :class:`enum.FlagBoundary.KEEP`.
.. versionadded:: 5.14
"""
style_int = pdfium_c.FPDFBookmark_GetStyle(self)
return PdfBookmarkStyle(style_int)
def get_dest(self):
"""
Returns:
PdfDest | None: The bookmark's destination (an object providing page index and viewport), or None on failure.
"""
raw_dest = pdfium_c.FPDFBookmark_GetDest(self.pdf, self)
if not raw_dest:
return None
return PdfDest(raw_dest, pdf=self.pdf)
class PdfDest (pdfium_i.AutoCastable):
"""
Destination helper class.
Attributes:
raw (FPDF_DEST): The underlying PDFium destination handle.
pdf (PdfDocument): Reference to the document this dest belongs to.
"""
def __init__(self, raw, pdf):
self.raw = raw
self.pdf = pdf
def get_index(self):
"""
Returns:
int | None: Zero-based index of the page the dest points to, or None on failure.
"""
val = pdfium_c.FPDFDest_GetDestPageIndex(self.pdf, self)
return val if val >= 0 else None
# TODO(apibreak) change seqtype default to tuple, or unconditionally return tuple?
def get_view(self, seqtype=list):
"""
Returns:
(int, list[float]): A tuple of (view_mode, view_pos).
*view_mode* is a constant (one of :data:`PDFDEST_VIEW_*`) defining how *view_pos* shall be interpreted.
*view_pos* is the target position on the page the dest points to.
It may contain between 0 to 4 float coordinates, depending on the view mode.
"""
n_params = ctypes.c_ulong()
pos = (pdfium_c.FS_FLOAT * 4)()
mode = pdfium_c.FPDFDest_GetView(self, n_params, pos)
pos = seqtype(pos)[:n_params.value]
return mode, pos
@@ -0,0 +1,180 @@
# SPDX-FileCopyrightText: 2026 geisserml <geisserml@gmail.com>
# SPDX-License-Identifier: Apache-2.0 OR BSD-3-Clause
__all__ = ("PdfMatrix", )
import math
import ctypes
import pypdfium2.raw as pdfium_c
# Note, the code below was written by a non-mathematician - might contain mistakes!
# In the future, we may want to consider adding a PdfRectangle support model to calculate size and corner points.
class PdfMatrix:
"""
PDF transformation matrix helper class.
See the PDF 1.7 specification, Section 8.3.3 ("Common Transformations").
Note:
* The PDF format uses row vectors.
* Transformations operate from the origin of the coordinate system
(PDF coordinates: commonly bottom left, but can be any corner in principle. Device coordinates: top left).
* Matrix calculations are implemented independently in Python.
* Matrix objects are immutable, so transforming methods return a new matrix.
* Matrix objects implement ctypes auto-conversion to ``FS_MATRIX`` for easy use as C function parameter.
Attributes:
a (float): Matrix value [0][0].
b (float): Matrix value [0][1].
c (float): Matrix value [1][0].
d (float): Matrix value [1][1].
e (float): Matrix value [2][0] (X translation).
f (float): Matrix value [2][1] (Y translation).
"""
# See also pdfium/core/fxcrt/fx_coordinates.{h,cpp} (unfortunately, pdfium's matrix implementation is non-public)
def __init__(self, a=1, b=0, c=0, d=1, e=0, f=0):
self.a, self.b, self.c, self.d, self.e, self.f = a, b, c, d, e, f
def __repr__(self):
return f"PdfMatrix{self.get()}"
def __eq__(self, other):
if type(self) is not type(other):
return False
return self.get() == other.get()
@property
def _as_parameter_(self):
return ctypes.byref( self.to_raw() )
def get(self):
"""
Get the matrix as tuple of the form (a, b, c, d, e, f).
"""
return (self.a, self.b, self.c, self.d, self.e, self.f)
@classmethod
def from_raw(cls, raw):
"""
Load a :class:`.PdfMatrix` from a raw :class:`FS_MATRIX` object.
"""
return cls(raw.a, raw.b, raw.c, raw.d, raw.e, raw.f)
def to_raw(self):
"""
Convert the matrix to a raw :class:`FS_MATRIX` object.
"""
return pdfium_c.FS_MATRIX(*self.get())
def multiply(self, other):
"""
Multiply this matrix by another :class:`.PdfMatrix`, to concatenate transformations.
"""
# M1 x M2 (self x other)
# (a1, b1, 0) (a2, b2, 0) (a1a2+b1c2, a1b2+b1d2, 0)
# (c1, d1, 0) x (c2, d2, 0) = (c1a2+d1c2, c1b2+d1d2, 0)
# (e1, f1, 1) (e2, f2, 1) (e1a2+f1c2+e2, e1b2+f1d2+f2, 1)
return PdfMatrix(
a = self.a*other.a + self.b*other.c,
b = self.a*other.b + self.b*other.d,
c = self.c*other.a + self.d*other.c,
d = self.c*other.b + self.d*other.d,
# corresponds to: e, f = other.on_point(self.e, self.f) - transforms X/Y translation
e = self.e*other.a + self.f*other.c + other.e,
f = self.e*other.b + self.f*other.d + other.f,
)
def translate(self, x, y):
"""
Parameters:
x (float): Horizontal shift (<0: left, >0: right).
y (float): Vertical shift.
"""
# same as return PdfMatrix(self.a, self.b, self.c, self.d, self.e+x, self.f+y)
return self.multiply( PdfMatrix(1, 0, 0, 1, x, y) )
def scale(self, x, y):
"""
Parameters:
x (float): A factor to scale the X axis (<1: compress, >1: stretch).
y (float): A factor to scale the Y axis.
"""
# same as return PdfMatrix(self.a*x, self.b*y, self.c*x, self.d*y, self.e*x, self.f*y)
return self.multiply( PdfMatrix(x, 0, 0, y) )
def rotate(self, angle, ccw=False, rad=False):
"""
Parameters:
angle (float): Angle by which to rotate the matrix.
ccw (bool): If True, rotate counter-clockwise.
rad (bool): If True, interpret the angle as radians.
"""
if not rad:
angle = math.radians(angle)
c, s = math.cos(angle), math.sin(angle)
return self.multiply( PdfMatrix(c, s, -s, c) if ccw else PdfMatrix(c, -s, s, c) )
def mirror(self, invert_x, invert_y):
"""
Parameters:
invert_x (bool): If True, invert X coordinates (horizontal transform). Corresponds to flipping around the Y axis.
invert_y (bool): If True, invert Y coordinates (vertical transform). Corresponds to flipping around the X axis.
Note:
Flipping around a vertical axis leads to a horizontal transform, and vice versa.
"""
return self.scale(x=(-1 if invert_x else 1), y=(-1 if invert_y else 1))
def skew(self, x_angle, y_angle, rad=False):
"""
Parameters:
x_angle (float): Inner angle to skew the X axis.
y_angle (float): Inner angle to skew the Y axis.
rad (bool): If True, interpret the angles as radians.
"""
if not rad:
x_angle = math.radians(x_angle)
y_angle = math.radians(y_angle)
return self.multiply( PdfMatrix(1, math.tan(x_angle), math.tan(y_angle), 1) )
def on_point(self, x, y):
"""
Returns:
(float, float): Transformed point.
"""
# (x, y) -> (ax+cy+e, bx+dy+f)
return ( # new point
self.a*x + self.c*y + self.e, # x
self.b*x + self.d*y + self.f, # y
)
def on_rect(self, left, bottom, right, top):
"""
Returns:
(float, float, float, float): Transformed rectangle.
"""
points = (
self.on_point(left, top),
self.on_point(left, bottom),
self.on_point(right, top),
self.on_point(right, bottom),
)
return ( # new rect
min(p[0] for p in points), # left
min(p[1] for p in points), # bottom
max(p[0] for p in points), # right
max(p[1] for p in points), # top
)
@@ -0,0 +1,40 @@
# SPDX-FileCopyrightText: 2026 geisserml <geisserml@gmail.com>
# SPDX-License-Identifier: Apache-2.0 OR BSD-3-Clause
__all__ = ("PdfiumError", "PdfiumWarning")
class PdfiumError (RuntimeError):
"""
An error from the (Py)PDFium library.
When a PDFium API indicates failure (as detected by function return code), this exception will be raised.
Attributes:
err_code (int | None):
PDFium error code, for programmatic handling of error subtypes, if provided by the API in question.
Currently, only document loading distinguishes between different errors, whereas most APIs just return error or success, in which case this field will be None.
"""
def __init__(self, msg, err_code=None):
super().__init__(msg)
self.err_code = err_code
class PdfiumWarning (Warning):
"""
A warning from the (Py)PDFium library.
This is intended for error conditions that do not strictly necessitate raising an exception, but should still be exposed programmatically.
Make sure you have configured the right warning level – otherwise, warnings might be hidden.
Attributes:
err_code (int | None):
PDFium error code, for programmatic handling of error subtypes, if provided by the API in question. None otherwise.
Currently, only XFA forms load failure provides this extra information.
"""
def __init__(self, msg, err_code=None):
super().__init__(msg)
self.err_code = err_code
@@ -0,0 +1,593 @@
# SPDX-FileCopyrightText: 2026 geisserml <geisserml@gmail.com>
# SPDX-License-Identifier: Apache-2.0 OR BSD-3-Clause
__all__ = ("PdfPage", "PdfColorScheme")
import math
import ctypes
import logging
import weakref
import pypdfium2.raw as pdfium_c
import pypdfium2.internal as pdfium_i
from pypdfium2._helpers.misc import PdfiumError
from pypdfium2._helpers.bitmap import PdfBitmap
from pypdfium2._helpers.textpage import PdfTextPage
from pypdfium2._helpers.pageobjects import PdfObject
c_float = ctypes.c_float
logger = logging.getLogger(__name__)
class PdfPage (pdfium_i.AutoCloseable):
"""
Page helper class.
Attributes:
raw (FPDF_PAGE):
The underlying PDFium page handle.
pdf (PdfDocument):
Reference to the document this page belongs to.
formenv (PdfFormEnv | None):
Formenv handle, if the parent pdf had an active formenv at the time of page retrieval. None otherwise.
"""
def __init__(self, raw, pdf, formenv):
self.raw = raw
self.pdf = pdf
self.formenv = formenv
super().__init__(PdfPage._close_impl, self.formenv)
@staticmethod
def _close_impl(raw, formenv):
if formenv:
pdfium_c.FORM_OnBeforeClosePage(raw, formenv)
pdfium_c.FPDF_ClosePage(raw)
@property
def parent(self): # AutoCloseable hook
return self.pdf
def get_width(self):
"""
Returns:
float: Page width (horizontal size), in PDF canvas units.
"""
return pdfium_c.FPDF_GetPageWidthF(self)
def get_height(self):
"""
Returns:
float: Page height (vertical size), in PDF canvas units.
"""
return pdfium_c.FPDF_GetPageHeightF(self)
def get_size(self):
"""
Returns:
(float, float): Page width and height, in PDF canvas units.
"""
return (self.get_width(), self.get_height())
# {get,set}_rotation() deliberately fail with dict access error in case of invalid values
def get_rotation(self):
"""
Returns:
int: Clockwise page rotation in degrees.
"""
raw_rotation = pdfium_c.FPDFPage_GetRotation(self)
if raw_rotation == -1:
raise PdfiumError("Failed to get page rotation.")
return pdfium_i.RotationToDegrees[raw_rotation]
def set_rotation(self, rotation):
"""
Define the absolute, clockwise page rotation (0, 90, 180, or 270 degrees).
"""
pdfium_c.FPDFPage_SetRotation(self, pdfium_i.RotationToConst[rotation])
def _get_box(self, box_func, fallback_func, fallback_ok):
left, bottom, right, top = c_float(), c_float(), c_float(), c_float()
ok = box_func(self, left, bottom, right, top)
if not ok:
return (fallback_func() if fallback_ok else None)
return (left.value, bottom.value, right.value, top.value)
# NOTE in case further arguments are needed (besides fallback_ok), then use *args, **kwargs in callers
def get_mediabox(self, fallback_ok=True):
"""
Returns:
(float, float, float, float) | None:
The page MediaBox in PDF canvas units, consisting of four coordinates (usually x0, y0, x1, y1).
If MediaBox is not defined, returns ANSI A (0, 0, 612, 792) if ``fallback_ok=True``, None otherwise.
.. admonition:: Known issue\n
Due to quirks in PDFium, all ``get_*box()`` functions except :meth:`.get_bbox` do not inherit from parent nodes in the page tree (as of PDFium 5418).
"""
# https://crbug.com/pdfium/1786
return self._get_box(pdfium_c.FPDFPage_GetMediaBox, lambda: (0, 0, 612, 792), fallback_ok)
def set_mediabox(self, l, b, r, t):
"""
Set the page's MediaBox by passing four :class:`float` coordinates (usually x0, y0, x1, y1).
"""
pdfium_c.FPDFPage_SetMediaBox(self, l, b, r, t)
def get_cropbox(self, fallback_ok=True):
"""
Returns:
The page's CropBox (If not defined, falls back to MediaBox).
"""
return self._get_box(pdfium_c.FPDFPage_GetCropBox, self.get_mediabox, fallback_ok)
def set_cropbox(self, l, b, r, t):
"""
Set the page's CropBox.
"""
pdfium_c.FPDFPage_SetCropBox(self, l, b, r, t)
def get_bleedbox(self, fallback_ok=True):
"""
Returns:
The page's BleedBox (If not defined, falls back to CropBox).
"""
return self._get_box(pdfium_c.FPDFPage_GetBleedBox, self.get_cropbox, fallback_ok)
def set_bleedbox(self, l, b, r, t):
"""
Set the page's BleedBox.
"""
pdfium_c.FPDFPage_SetBleedBox(self, l, b, r, t)
def get_trimbox(self, fallback_ok=True):
"""
Returns:
The page's TrimBox (If not defined, falls back to CropBox).
"""
return self._get_box(pdfium_c.FPDFPage_GetTrimBox, self.get_cropbox, fallback_ok)
def set_trimbox(self, l, b, r, t):
"""
Set the page's TrimBox.
"""
pdfium_c.FPDFPage_SetTrimBox(self, l, b, r, t)
def get_artbox(self, fallback_ok=True):
"""
Returns:
The page's ArtBox (If not defined, falls back to CropBox).
"""
return self._get_box(pdfium_c.FPDFPage_GetArtBox, self.get_cropbox, fallback_ok)
def set_artbox(self, l, b, r, t):
"""
Set the page's ArtBox.
"""
pdfium_c.FPDFPage_SetArtBox(self, l, b, r, t)
def get_bbox(self):
"""
Returns:
The bounding box of the page (the intersection between its media box and crop box).
"""
rect = pdfium_c.FS_RECTF()
ok = pdfium_c.FPDF_GetPageBoundingBox(self, rect)
if not ok:
raise PdfiumError("Failed to get page bounding box.")
return (rect.left, rect.bottom, rect.right, rect.top)
# TODO add bindings to FPDFPage_TransFormWithClip()
def get_textpage(self):
"""
Returns:
PdfTextPage: A new text page handle for this page.
"""
raw_textpage = pdfium_c.FPDFText_LoadPage(self)
if not raw_textpage:
raise PdfiumError("Failed to load text page.")
textpage = PdfTextPage(raw_textpage, self)
self._add_kid(textpage)
return textpage
def insert_obj(self, pageobj):
"""
Insert a pageobject into the page.
The pageobject must not belong to a page yet. If it belongs to a PDF, the target page must be part of that PDF.
Position and form are defined by the object's matrix.
If it is the identity matrix, the object will appear as-is on the bottom left corner of the page.
Parameters:
pageobj (PdfObject): The pageobject to insert.
"""
if pageobj.page:
raise ValueError("The pageobject you attempted to insert already belongs to a page.")
if pageobj.pdf and (pageobj.pdf is not self.pdf):
raise ValueError("The pageobject you attempted to insert belongs to a different PDF.")
ok = pdfium_c.FPDFPage_InsertObject(self, pageobj)
if not ok:
raise PdfiumError("Failed to insert object.")
pageobj._detach_finalizer()
pageobj.page = self
pageobj.pdf = self.pdf
def remove_obj(self, pageobj):
"""
Remove a pageobject from the page.
As of PDFium 5692, detached pageobjects may be only re-inserted into existing pages of the same document.
If the pageobject is not re-inserted into a page, its ``close()`` method may be called.
Note:
If the object's :attr:`~.PdfObject.type` is :data:`FPDF_PAGEOBJ_TEXT`, any :class:`.PdfTextPage` handles to the page should be closed before removing the object.
Parameters:
pageobj (PdfObject): The pageobject to remove.
"""
# note https://pdfium-review.googlesource.com/c/pdfium/+/118914
if pageobj.page is not self:
raise ValueError("The pageobject you attempted to remove is not part of this page.")
if pageobj.level > 0:
assert pageobj.container is not None
ok = pdfium_c.FPDFFormObj_RemoveObject(pageobj.container, pageobj)
pageobj.level, pageobj.container = 0, None
else:
assert pageobj.container is None
ok = pdfium_c.FPDFPage_RemoveObject(self, pageobj)
if not ok:
raise PdfiumError("Failed to remove pageobject.")
pageobj.page = None
pageobj._attach_finalizer()
def gen_content(self):
"""
Generate page content to apply additions, removals or modifications of pageobjects.
If page content was changed, this function should be called once before saving the document or re-loading the page.
"""
ok = pdfium_c.FPDFPage_GenerateContent(self)
if not ok:
raise PdfiumError("Failed to generate page content.")
def get_objects(self, filter=None, max_depth=15, form=None, level=0, textpage=None):
"""
Iterate through the pageobjects on this page.
Parameters:
filter (list[int] | None):
An optional list of pageobject types to filter (:attr:`FPDF_PAGEOBJ_*`).
Any objects whose type is not contained will be skipped.
If None or empty, all objects will be provided, regardless of their type.
max_depth (int):
Maximum recursion depth to consider when descending into Form XObjects.
textpage (PdfTextPage | None):
Text page to pass through to any :class:`.PdfTextObj` instances.
Yields:
:class:`.PdfObject`: A pageobject.
"""
if form:
count_objects = pdfium_c.FPDFFormObj_CountObjects
get_object = pdfium_c.FPDFFormObj_GetObject
parent = form
else:
count_objects = pdfium_c.FPDFPage_CountObjects
get_object = pdfium_c.FPDFPage_GetObject
parent = self
if textpage and textpage.page is not self:
raise ValueError("The given textpage does not belong to this page.")
n_objects = count_objects(parent)
if n_objects < 0:
raise PdfiumError("Failed to get number of pageobjects.")
for i in range(n_objects):
raw_obj = get_object(parent, i)
if not raw_obj:
raise PdfiumError("Failed to get pageobject.")
# Don't register as child object, because the lifetime of pageobjects that are part of a page is managed by pdfium. The parent page should remain alive while a pageobject is used, but it seems unjustified to store countless of weakrefs just to lock pageobjects when the parent page is closed.
helper_obj = PdfObject(raw_obj, page=self, pdf=self.pdf, container=form, level=level, textpage=textpage) # tracked=False
if not filter or helper_obj.type in filter:
yield helper_obj
if helper_obj.type == pdfium_c.FPDF_PAGEOBJ_FORM and level < max_depth-1:
yield from self.get_objects(
filter = filter,
max_depth = max_depth,
form = helper_obj,
level = level + 1,
textpage = textpage,
)
def flatten(self, flag=pdfium_c.FLAT_NORMALDISPLAY):
"""
Flatten form fields and annotations into page contents.
Attention:
* :meth:`~.PdfDocument.init_forms` must have been called on the parent pdf, before the page was retrieved, for this method to work. In other words, :attr:`.PdfPage.formenv` must be non-null.
* Flattening may invalidate existing handles to the page, so you'll want to re-initialize these afterwards.
Parameters:
flag (int): PDFium flattening target (:attr:`FLAT_*`)
Returns:
int: PDFium flattening status (:attr:`FLATTEN_*`). :attr:`FLATTEN_FAIL` is handled internally.
"""
if not self.formenv:
raise RuntimeError("page.flatten() requires prior pdf.init_forms(), before page retrieval.")
rc = pdfium_c.FPDFPage_Flatten(self, flag)
if rc == pdfium_c.FLATTEN_FAIL:
raise PdfiumError("Failed to flatten annotations / form fields.")
return rc
# TODO
# - add helpers for matrix-based and interruptible rendering
# - add lower-level renderer that takes a caller-provided bitmap
# e.g. render(), render_ex(), render_matrix(), render_matrix_ex()
def render(
self,
scale = 1,
rotation = 0,
crop = (0, 0, 0, 0),
may_draw_forms = True,
bitmap_maker = PdfBitmap.new_native,
color_scheme = None,
fill_to_stroke = False,
**kwargs
):
"""
Rasterize the page to a :class:`.PdfBitmap`.
Parameters:
scale (float):
A factor scaling the number of pixels per PDF canvas unit. This defines the resolution of the image.
To convert a DPI value to a scale factor, multiply it by the size of 1 canvas unit in inches (usually 1/72in). [#user_unit]_
rotation (int):
Additional rotation in degrees (0, 90, 180, or 270).
crop (tuple[float, float, float, float]):
Amount to cut off from view (left, bottom, right, top), in PDF canvas units.
Rendering crop applies on bitmap level (i.e. after rotation), unlike changing the page cropbox using :meth:`.set_cropbox`.
Negative crop is not supported (though no exception will be raised). It may produce a larger canvas but not actually expand the rendering area, as of PDFium 7825.
may_draw_forms (bool):
If True, render form fields (provided the document has forms and :meth:`~.PdfDocument.init_forms` was called).
bitmap_maker (typing.Callable):
Callback function used to create the :class:`.PdfBitmap`.
fill_color (tuple[int, int, int, int]):
Color the bitmap will be filled with before rendering. This uses RGBA syntax regardless of the pixel format used, with values from 0 to 255.
If the fill color is not opaque (i.e. has transparency), ``{BGR,RGB}A`` will be used.
grayscale (bool):
If True, render in grayscale mode.
optimize_mode (None | str):
Page rendering optimization mode (None, "lcd", "print").
draw_annots (bool):
If True, render page annotations.
no_smoothtext (bool):
If True, disable text anti-aliasing. Overrides ``optimize_mode="lcd"``.
no_smoothimage (bool):
If True, disable image anti-aliasing.
no_smoothpath (bool):
If True, disable path anti-aliasing.
force_halftone (bool):
If True, always use halftone for image stretching.
limit_image_cache (bool):
If True, limit image cache size.
rev_byteorder (bool):
If True, render with reverse byte order, leading to ``RGB{A/x}`` output rather than ``BGR{A/x}``.
Other pixel formats are not affected.
prefer_bgrx (bool):
If True, use 4-byte ``{BGR/RGB}x`` rather than 3-byte ``{BGR/RGB}`` (i.e. add an unused byte).
Other pixel formats are not affected.
maybe_alpha (bool):
If True, use a pixel format with alpha channel (i.e. ``{BGR/RGB}A``) if page content has transparency.
This is recommended for performance in these cases, but as page-dependent format selection can be unexpected, it is not enabled by default.
force_bitmap_format (int | None):
If given, override automatic pixel format selection and enforce use of the given format (one of the :attr:`FPDFBitmap_*` constants). In this case, you should not pass any other format selection options, except potentially *rev_byteorder*.
extra_flags (int):
Additional PDFium rendering flags. May be combined with bitwise OR (``|`` operator).
color_scheme (PdfColorScheme | None):
A custom pdfium color scheme. Note that this may flatten different colors into one, so the usability of this is limited.
fill_to_stroke (bool):
If a *color_scheme* is given, whether to only draw borders around fill areas using the `path_stroke` color, instead of filling with the `path_fill` color.
Returns:
PdfBitmap: Bitmap of the rendered page.
.. admonition:: Format selection
This is the format selection hierarchy used by :meth:`.render`, from lowest to highest priority:
* default: ``BGR``
* ``prefer_bgrx=True``: ``BGRx``
* ``grayscale=True``: ``L``
* ``maybe_alpha=True``: ``BGRA`` if the page has transparency, else the format selected otherwise
* ``fill_color[3] < 255``: ``BGRA`` (background color with transparency)
* ``force_bitmap_format=...`` -> any supported by pdfium
Additionally, ``rev_byteorder=True`` will swap ``BGR{A/x}`` to ``RGB{A/x}`` if applicable.
.. [#user_unit] Since PDF 1.6, pages may define an additional user unit factor. In this case, 1 canvas unit is equivalent to ``user_unit * (1/72)`` inches. PDFium does not currently provide an API to get the user unit, so this is not taken into account.
"""
src_width = math.ceil(self.get_width() * scale)
src_height = math.ceil(self.get_height() * scale)
if rotation in (90, 270):
src_width, src_height = src_height, src_width
crop = [math.ceil(c*scale) for c in crop]
width = src_width - crop[0] - crop[2]
height = src_height - crop[1] - crop[3]
if any(d < 1 for d in (width, height)):
raise ValueError("Crop exceeds page dimensions")
cl_format, rev_byteorder, fill_color, flags = _parse_renderopts(self, **kwargs)
if (color_scheme is not None) and fill_to_stroke:
flags |= pdfium_c.FPDF_CONVERT_FILL_TO_STROKE
bitmap = bitmap_maker(width, height, format=cl_format, rev_byteorder=rev_byteorder)
bitmap.fill_rect(fill_color, 0, 0, width, height)
pos_args = (-crop[0], -crop[3], src_width, src_height, pdfium_i.RotationToConst[rotation])
render_args = (bitmap, self, *pos_args, flags)
if color_scheme is None:
pdfium_c.FPDF_RenderPageBitmap(*render_args)
else:
pause = pdfium_c.IFSDK_PAUSE(version=1)
pdfium_i.set_callback(pause, "NeedToPauseNow", _pause_noop)
fpdf_cs = color_scheme.convert(rev_byteorder)
status = pdfium_c.FPDF_RenderPageBitmapWithColorScheme_Start(*render_args, fpdf_cs, pause)
assert status != pdfium_c.FPDF_RENDER_FAILED, "Progressive render return code indicates failure"
pdfium_c.FPDF_RenderPage_Close(self)
if may_draw_forms and self.formenv:
pdfium_c.FPDF_FFLDraw(self.formenv, *render_args)
bitmap._render_args = (weakref.ref(self), pos_args)
return bitmap
def _auto_bitmap_format(page, fill_color, grayscale, prefer_bgrx, maybe_alpha):
# regarding maybe_alpha, see
# https://chromium.googlesource.com/chromium/src/+/21e456b92bfadc625c947c718a6c4c5bf0c4c61b
if fill_color[3] < 255 or (maybe_alpha and pdfium_c.FPDFPage_HasTransparency(page)):
return pdfium_c.FPDFBitmap_BGRA
elif grayscale:
return pdfium_c.FPDFBitmap_Gray
elif prefer_bgrx:
return pdfium_c.FPDFBitmap_BGRx
else:
return pdfium_c.FPDFBitmap_BGR
def _parse_renderopts(
page,
fill_color = (255, 255, 255, 255),
grayscale = False,
optimize_mode = None,
draw_annots = True,
no_smoothtext = False,
no_smoothimage = False,
no_smoothpath = False,
force_halftone = False,
limit_image_cache = False,
rev_byteorder = False,
prefer_bgrx = False,
maybe_alpha = False,
force_bitmap_format = None,
extra_flags = 0,
):
if force_bitmap_format is None:
cl_format = _auto_bitmap_format(page, fill_color, grayscale, prefer_bgrx, maybe_alpha)
else:
cl_format = force_bitmap_format
if cl_format == pdfium_c.FPDFBitmap_Gray:
rev_byteorder = False
flags = extra_flags
if grayscale:
flags |= pdfium_c.FPDF_GRAYSCALE
if draw_annots:
flags |= pdfium_c.FPDF_ANNOT
if no_smoothtext:
flags |= pdfium_c.FPDF_RENDER_NO_SMOOTHTEXT
if no_smoothimage:
flags |= pdfium_c.FPDF_RENDER_NO_SMOOTHIMAGE
if no_smoothpath:
flags |= pdfium_c.FPDF_RENDER_NO_SMOOTHPATH
if force_halftone:
flags |= pdfium_c.FPDF_RENDER_FORCEHALFTONE
if limit_image_cache:
flags |= pdfium_c.FPDF_RENDER_LIMITEDIMAGECACHE
if rev_byteorder:
flags |= pdfium_c.FPDF_REVERSE_BYTE_ORDER
if optimize_mode:
optimize_mode = optimize_mode.lower()
if optimize_mode == "lcd":
flags |= pdfium_c.FPDF_LCD_TEXT
elif optimize_mode == "print":
flags |= pdfium_c.FPDF_PRINTING
else:
raise ValueError(f"Invalid optimize_mode {optimize_mode}")
# TODO consider using a namedtuple or something
return cl_format, rev_byteorder, fill_color, flags
class PdfColorScheme:
"""
Rendering color scheme.
Each color shall be provided as a list of values for red, green, blue and alpha, ranging from 0 to 255.
"""
def __init__(self, path_fill, path_stroke, text_fill, text_stroke):
self.colors = dict(
path_fill_color=path_fill, path_stroke_color=path_stroke,
text_fill_color=text_fill, text_stroke_color=text_stroke,
)
def __repr__(self):
return f"{type(self).__name__}(**{self.colors})"
def convert(self, rev_byteorder):
"""
Returns:
The color scheme as :class:`FPDF_COLORSCHEME` object.
"""
fpdf_cs = pdfium_c.FPDF_COLORSCHEME()
for key, value in self.colors.items():
setattr(fpdf_cs, key, pdfium_i.color_tohex(value, rev_byteorder))
return fpdf_cs
def _pause_noop(arg):
return False
@@ -0,0 +1,656 @@
# SPDX-FileCopyrightText: 2026 geisserml <geisserml@gmail.com>
# SPDX-License-Identifier: Apache-2.0 OR BSD-3-Clause
__all__ = ("PdfObject", "PdfImage", "PdfTextObj", "PdfFont")
import ctypes
from ctypes import c_uint, c_float
import logging
from pathlib import Path
from codecs import decode
from collections import namedtuple
import pypdfium2.raw as pdfium_c
import pypdfium2.internal as pdfium_i
from pypdfium2.internal import FPDF_WCHAR_size
from pypdfium2._helpers.misc import PdfiumError
from pypdfium2._helpers.matrix import PdfMatrix
from pypdfium2._helpers.bitmap import PdfBitmap
from pypdfium2._lazy import Lazy
from pypdfium2_cfg.stl import cached_property
logger = logging.getLogger(__name__)
class PdfObject (pdfium_i.AutoCloseable):
"""
Pageobject helper class.
When constructing a :class:`.PdfObject`, an instance of a more specific subclass may be returned instead, depending on the object's :attr:`.type` (e.g. :class:`.PdfImage`, :class:`.PdfTextObj`).
Note:
:meth:`.PdfObject.close` only takes effect on loose pageobjects.
It is a no-op otherwise, because pageobjects that are part of a page are owned by pdfium, not the caller.
Attributes:
raw (FPDF_PAGEOBJECT):
The underlying PDFium pageobject handle.
type (int):
The object's type (:data:`FPDF_PAGEOBJ_*`).
page (PdfPage):
Reference to the page this pageobject belongs to. May be None if not part of a page (e.g. new or detached object).
pdf (PdfDocument):
Reference to the document this pageobject belongs to. May be None if the object does not belong to a document yet.
This attribute is always set if :attr:`.page` is set.
container (PdfObject | None):
PdfObject handle to parent Form XObject, if the pageobject is nested in a Form XObject, None otherwise.
level (int):
Nesting level signifying the number of parent Form XObjects, at the time of construction.
Zero if the object is not nested in a Form XObject.
"""
def __new__(cls, raw, *args, **kwargs):
assert raw, "The `raw` parameter must be non-null."
raw_type = pdfium_c.FPDFPageObj_GetType(raw)
if raw_type == pdfium_c.FPDF_PAGEOBJ_UNKNOWN:
raise PdfiumError("Failed to determine pageobject type, did you pass in a valid FPDF_PAGEOBJECT handle?")
py_type = {
pdfium_c.FPDF_PAGEOBJ_IMAGE: PdfImage,
pdfium_c.FPDF_PAGEOBJ_TEXT: PdfTextObj,
}.get(raw_type, cls)
instance = super().__new__(py_type)
instance.type = raw_type
return instance
# textpage is only picked up by the PdfTextObj subclass, but included here so get_object() can just unconditionally pass the textpage without need for type if-checks
def __init__(self, raw, page=None, pdf=None, container=None, level=0, textpage=None, tracked=False):
self.raw = raw
self.page = page
self.pdf = pdf
self.container = container
self.level = level
if page is not None:
if self.pdf is None:
self.pdf = page.pdf
elif self.pdf is not page.pdf:
raise ValueError("*page* must belong to *pdf* when constructing a pageobject.")
# TODO if page is not None, hold it in the finalizer, unless the pageobject is detached from the page
super().__init__(pdfium_c.FPDFPageObj_Destroy, needs_free=(page is None), tracked=tracked)
@property
def parent(self): # AutoCloseable hook
# Not actually used by the autoclose machinery. PdfObjects are not tracked, and if they are part of a page we don't have ownership anyway.
return self.pdf if self.page is None else self.page # May be None (loose pageobject)
def get_bounds(self):
"""
Get the bounds of the object on the page.
Returns:
tuple[float * 4]: Left, bottom, right and top, in PDF page coordinates.
"""
if self.page is None:
raise RuntimeError("Must not call get_bounds() on a loose pageobject.")
l, b, r, t = c_float(), c_float(), c_float(), c_float()
ok = pdfium_c.FPDFPageObj_GetBounds(self, l, b, r, t)
if not ok:
raise PdfiumError("Failed to locate pageobject.")
return (l.value, b.value, r.value, t.value)
def get_quad_points(self):
"""
Get the object's quadriliteral points (i.e. the positions of its corners).
For transformed objects, this may provide tighter bounds than a rectangle (e.g. rotation by a non-multiple of 90°, shear).
Note:
This function only supports image and text objects.
Returns:
tuple[tuple[float*2] * 4]: Corner positions as (x, y) tuples, counter-clockwise from origin, i.e. bottom-left, bottom-right, top-right, top-left, in PDF page coordinates.
"""
if not isinstance(self, (PdfImage, PdfTextObj)): # as of pdfium 5921
raise RuntimeError("Quad points only supported for image and text objects.")
q = pdfium_c.FS_QUADPOINTSF()
ok = pdfium_c.FPDFPageObj_GetRotatedBounds(self, q)
if not ok:
raise PdfiumError("Failed to get quad points.")
return (q.x1, q.y1), (q.x2, q.y2), (q.x3, q.y3), (q.x4, q.y4)
def get_matrix(self):
"""
Returns:
PdfMatrix: The pageobject's current transform matrix.
"""
fs_matrix = pdfium_c.FS_MATRIX()
ok = pdfium_c.FPDFPageObj_GetMatrix(self, fs_matrix)
if not ok:
raise PdfiumError("Failed to get matrix of pageobject.")
return PdfMatrix.from_raw(fs_matrix)
def set_matrix(self, matrix):
"""
Parameters:
matrix (PdfMatrix): Set this matrix as the pageobject's transform matrix.
"""
ok = pdfium_c.FPDFPageObj_SetMatrix(self, matrix)
if not ok:
raise PdfiumError("Failed to set matrix of pageobject.")
def transform(self, matrix):
"""
Parameters:
matrix (PdfMatrix): Multiply the pageobject's current transform matrix by this matrix.
"""
ok = pdfium_c.FPDFPageObj_TransformF(self, matrix)
if not ok:
raise PdfiumError("Failed to transform pageobject with matrix.")
class PdfTextObj (PdfObject):
"""
Textobject helper class.
You may want to call :meth:`.PdfPage.get_objects` or :meth:`.PdfTextPage.get_textobj` to obtain an instance of this class.
Attributes:
textpage (PdfTextPage | None):
The parent textpage, or None if not set.
"""
# TODO hold parent object in finalizer
def __init__(self, *args, textpage=None, **kwargs):
if textpage is not None:
kwargs.update(page=textpage.page, pdf=textpage.page.pdf)
super().__init__(*args, **kwargs)
self.textpage = textpage
def extract(self):
"""
Returns:
str: The objects's text content.
Note:
This method requires the :attr:`.textpage` attribute to be set.
For textobjects obtained through :meth:`.PdfPage.get_objects`, use the ``textpage`` passthrough parameter.
"""
if not self.textpage:
raise RuntimeError("PdfTextObj.extract() requires textpage to be set.")
n_bytes = pdfium_c.FPDFTextObj_GetText(self, self.textpage, None, 0)
if not n_bytes:
raise PdfiumError("Failed to get text from textobject.")
n_units = -(n_bytes // -FPDF_WCHAR_size) # ceildiv
buffer = (pdfium_c.FPDF_WCHAR * n_units)()
pdfium_c.FPDFTextObj_GetText(self, self.textpage, buffer, n_bytes)
return decode(memoryview(buffer)[:n_units-1], "utf-16-le")
def get_font(self):
"""
Returns:
PdfFont: Handle to the object's font. Provides name and weight info.
"""
# The font object is _not_ owned by the caller, and the PdfTextObj must remain alive while the font object lives.
raw_font = pdfium_c.FPDFTextObj_GetFont(self)
return PdfFont(raw_font, self, needs_free=False)
def get_font_size(self):
"""
Returns:
float: Font size used by the object's text, in PDF canvas units (typically 1/72in).
"""
r_size = ctypes.c_float()
ok = pdfium_c.FPDFTextObj_GetFontSize(self, r_size)
if not ok:
raise PdfiumError("Failed to get font size.")
return r_size.value
class PdfFont (pdfium_i.AutoCloseable):
"""
Font helper class.
"""
# TODO hold parent in finalizer
def __init__(self, raw, parent=None, needs_free=False):
self.raw = raw
self.parent = parent
super().__init__(pdfium_c.FPDFFont_Close, needs_free=needs_free, tracked=needs_free)
@cached_property
def is_embedded(self):
"""
bool: The font's embedding status. True if it is embedded (bundled) in the PDF, False otherwise.
This is a cached property.
"""
rc = pdfium_c.FPDFFont_GetIsEmbedded(self)
if rc == -1:
raise PdfiumError("Failed to determine font embedding status.")
return rc == 1
def _get_name(self, api, which, errors):
bufsize = api(self, None, 0)
if not bufsize:
raise PdfiumError(f"Failed to get font {which} name.")
buffer = ctypes.create_string_buffer(bufsize)
api(self, buffer, bufsize)
return decode(memoryview(buffer)[:bufsize-1], "utf-8", errors=errors)
def get_base_name(self, errors="replace"):
"""
Returns:
str: The base font name.
"""
return self._get_name(pdfium_c.FPDFFont_GetBaseFontName, "base", errors)
def get_family_name(self, errors="replace"):
"""
Returns:
str: The font family name.
"""
return self._get_name(pdfium_c.FPDFFont_GetFamilyName, "family", errors)
def get_weight(self):
"""
Returns:
int: The font's weight. Typical values are 400 (normal) and 700 (bold).
"""
weight = pdfium_c.FPDFFont_GetWeight(self)
if weight == -1:
raise PdfiumError("Failed to get font weight.")
return weight
STANDARD_FONTS = ("Times-Roman", "Times-Bold", "Times-Italic", "Times-BoldItalic", "Helvetica", "Helvetica-Bold", "Helvetica-Oblique", "Helvetica-BoldOblique", "Courier", "Courier-Bold", "Courier-Oblique", "Courier-BoldOblique", "Symbol", "ZapfDingbats")
"""
Standard 14 fonts (Type 1, PostScript names) according to PDF32000_2008, section 9.6.2.2.
These fonts or suitable substitutes should be available to all PDF engines,
so PDFs that uses them without embedding can still be expected to display correctly.
"""
@classmethod
def load_standard(cls, pdf, name):
"""
Load one of the Standard 14 fonts defined above into a PDF.
If the font is not available in the system, a substitute may be used.
Checking :meth:`.get_family_name` should give a clue about internal substitution (e.g. "Chrom Sans OTF", "Chrom Serif OTF").
For system substitution, consider intercepting what goes through the :class:`.PdfSysfontBase` callbacks.
Parameters:
pdf (PdfDocument):
The document to which the font shall be loaded.
name (str):
The font name. Must be one of :attr:`.STANDARD_FONTS`.
"""
assert name in cls.STANDARD_FONTS
raw_font = pdfium_c.FPDFText_LoadStandardFont(pdf, name.encode("utf-8"))
if not raw_font:
raise PdfiumError(f"Failed to load standard font {name!r}.")
helper = cls(raw_font, parent=pdf, needs_free=True)
pdf._add_kid(helper)
return helper
class PdfImage (PdfObject):
"""
Image object helper class (specific kind of pageobject).
"""
# cf. https://crbug.com/pdfium/1203
#: Filters applied by :func:`FPDFImageObj_GetImageDataDecoded`, referred to as "simple filters". Other filters are considered "complex filters".
SIMPLE_FILTERS = ("ASCIIHexDecode", "ASCII85Decode", "RunLengthDecode", "FlateDecode", "LZWDecode")
@classmethod
def new(cls, pdf):
"""
Parameters:
pdf (PdfDocument): The document to which the new image object shall be added.
Returns:
PdfImage: Handle to a new, empty image.
Note that position and size of the image are defined by its matrix, which defaults to the identity matrix.
This means that new images will appear as a tiny square of 1x1 canvas units on the bottom left corner of the page.
Use :class:`.PdfMatrix` and :meth:`.set_matrix` to adjust size and position.
"""
raw_img = pdfium_c.FPDFPageObj_NewImageObj(pdf)
return cls(raw_img, page=None, pdf=pdf)
def get_metadata(self):
"""
Retrieve image metadata including DPI, bits per pixel, color space, and size.
If the image does not belong to a page yet, bits per pixel and color space will be unset (0).
Note:
* The DPI values signify the resolution of the image on the PDF page, not the DPI metadata embedded in the image file.
* Due to issues in pdfium, this function might be slow on some kinds of images. If you only need size, prefer :meth:`.get_px_size` instead.
Returns:
FPDF_IMAGEOBJ_METADATA: Image metadata structure
"""
# https://crbug.com/pdfium/1928
metadata = pdfium_c.FPDF_IMAGEOBJ_METADATA()
ok = pdfium_c.FPDFImageObj_GetImageMetadata(self, self.page, metadata)
if not ok:
raise PdfiumError("Failed to get image metadata.")
return metadata
def get_px_size(self):
"""
Returns:
(int, int): Image dimension in pixels as a tuple of (width, height).
"""
# https://pdfium-review.googlesource.com/c/pdfium/+/106290
w, h = c_uint(), c_uint()
ok = pdfium_c.FPDFImageObj_GetImagePixelSize(self, w, h)
if not ok:
raise PdfiumError("Failed to get image size.")
return w.value, h.value
def load_jpeg(self, source, pages=None, inline=False, autoclose=True):
"""
Set a JPEG as the image object's content.
Parameters:
source (str | pathlib.Path | typing.BinaryIO):
Input JPEG, given as file path or readable byte stream.
pages (list[PdfPage] | None):
If replacing an image, pass in a list of loaded pages that might contain it, to update their cache.
(The same image may be shown multiple times in different transforms across a PDF.)
May be None or an empty sequence if the image is not shared.
inline (bool):
Whether to load the image content into memory. If True, the buffer may be closed after this function call.
Otherwise, the buffer needs to remain open until the PDF is closed.
autoclose (bool):
If the input is a buffer, whether it should be automatically closed once not needed by the PDF anymore.
"""
if isinstance(source, (str, Path)):
buffer = open(source, "rb")
autoclose = True
elif pdfium_i.is_stream(source, "r"):
buffer = source
else:
raise ValueError(f"Cannot load JPEG from {source} - not a file path or byte stream.")
bufaccess, to_hold = pdfium_i.get_bufreader(buffer)
loader = pdfium_c.FPDFImageObj_LoadJpegFileInline if inline else \
pdfium_c.FPDFImageObj_LoadJpegFile
c_pages, page_count = pdfium_i.pages_c_array(pages)
ok = loader(c_pages, page_count, self, bufaccess)
if not ok:
raise PdfiumError("Failed to load JPEG into image object.")
if inline:
for data in to_hold:
id(data)
if autoclose:
buffer.close()
else:
self.pdf._data_holder += to_hold
if autoclose:
self.pdf._data_closer.append(buffer)
def set_bitmap(self, bitmap, pages=None):
"""
Set a bitmap as the image object's content.
The pixel data will be flate compressed (as of PDFium 5418).
Parameters:
bitmap (PdfBitmap):
The bitmap to inject into the image object.
pages (list[PdfPage] | None):
A list of loaded pages that might contain the image object. See :meth:`.load_jpeg`.
"""
c_pages, page_count = pdfium_i.pages_c_array(pages)
ok = pdfium_c.FPDFImageObj_SetBitmap(c_pages, page_count, self, bitmap)
if not ok:
raise PdfiumError("Failed to set image to bitmap.")
def _get_rendered_bitmap(self, scale_to_original):
""" This is a private implementation function. Do not use externally. """
if self.pdf is None:
raise RuntimeError("Cannot get rendered bitmap of loose pageobject.")
if scale_to_original:
# Suggested by pdfium dev Lei Zhang in https://groups.google.com/g/pdfium/c/2czGFBcWHHQ/m/g0wzOJR-BAAJ
px_w, px_h = self.get_px_size()
l, b, r, t = self.get_bounds()
content_w, content_h = abs(r-l), abs(t-b)
# align pixel and content width/height relation if swapped due to rotation (e.g. 90°, 270°)
swap = (px_w < px_h) != (content_w < content_h)
if swap:
px_w, px_h = px_h, px_w
# if the image is squashed/stretched, prefer partial upscaling over partial downscaling (not using separate x/y scaling, so the image will look as in the PDF)
scale_factor = max(px_w/content_w, px_h/content_h)
orig_mat = self.get_matrix()
scaled_mat = orig_mat.scale(scale_factor, scale_factor)
self.set_matrix(scaled_mat)
# logger.debug(
# f"Pixel size: {px_w}, {px_h} (did swap? {swap})\n"
# f"Size in page coords: {content_w}, {content_h}\n"
# f"Scale: {scale_factor}\n"
# f"Current matrix: {orig_mat}\n"
# f"Scaled matrix: {scaled_mat}"
# )
try:
raw_bitmap = pdfium_c.FPDFImageObj_GetRenderedBitmap(self.pdf, self.page, self)
finally:
if scale_to_original:
self.set_matrix(orig_mat)
return raw_bitmap
def get_bitmap(self, render=False, scale_to_original=True):
"""
Get a bitmap rasterization of the image.
Parameters:
render (bool):
Whether the image should be rendered, thereby applying possible transform matrices and alpha masks.
scale_to_original (bool):
If *render* is True, whether to temporarily scale the image to its native resolution, or close to that (defaults to True). This should improve output quality. Ignored if *render* is False.
Returns:
PdfBitmap: Image bitmap (with a buffer allocated by PDFium).
"""
if render:
raw_bitmap = self._get_rendered_bitmap(scale_to_original)
else:
raw_bitmap = pdfium_c.FPDFImageObj_GetBitmap(self)
if not raw_bitmap:
raise PdfiumError(f"Failed to get bitmap of image {self}.")
bitmap = PdfBitmap.from_raw(raw_bitmap)
if render and scale_to_original:
logger.debug(f"Extracted size: {bitmap.width}, {bitmap.height}")
return bitmap
def get_data(self, decode_simple=False):
"""
Parameters:
decode_simple (bool):
If True, decode simple filters (see :attr:`.SIMPLE_FILTERS`), so only complex filters will remain, if any. If there are no complex filters, this provides the decoded pixel data.
If False, the raw stream data will be returned instead.
Returns:
ctypes.Array: The data of the image stream (as :class:`~ctypes.c_ubyte` array).
"""
func = pdfium_c.FPDFImageObj_GetImageDataDecoded if decode_simple else \
pdfium_c.FPDFImageObj_GetImageDataRaw
n_bytes = func(self, None, 0)
buffer = (ctypes.c_ubyte * n_bytes)()
func(self, buffer, n_bytes)
return buffer
def get_filters(self, skip_simple=False):
"""
Parameters:
skip_simple (bool):
If True, exclude simple filters.
Returns:
list[str]: A list of image filters, to be applied in order (from lowest to highest index).
"""
filters = []
count = pdfium_c.FPDFImageObj_GetImageFilterCount(self)
for i in range(count):
length = pdfium_c.FPDFImageObj_GetImageFilter(self, i, None, 0)
buffer = ctypes.create_string_buffer(length)
pdfium_c.FPDFImageObj_GetImageFilter(self, i, buffer, length)
f = decode(memoryview(buffer)[:length-1], "utf-8")
filters.append(f)
if skip_simple:
filters = [f for f in filters if f not in self.SIMPLE_FILTERS]
return filters
def extract(self, dest, *args, **kwargs):
"""
Extract the image into an independently usable file or byte stream, attempting to avoid re-encoding or quality loss, as far as pdfium's limited API permits.
This method can only extract DCTDecode (JPEG) and JPXDecode (JPEG 2000) images directly.
Otherwise, the pixel data is decoded and re-encoded using :mod:`PIL`, which is slower and loses the original encoding.
For images with simple filters only, ``get_data(decode_simple=True)`` is used to preserve higher bit depth or special color formats not supported by ``FPDF_BITMAP``.
For images with complex filters other than those extracted directly, we have to resort to :meth:`.get_bitmap`.
Note, this method is not able to account for alpha masks, and potentially other data stored separately of the main image stream, which might lead to incorrect representation of the image.
Tip:
The ``pikepdf`` library is capable of preserving the original encoding in many cases where this method is not.
Parameters:
dest (str | pathlib.Path | io.BytesIO):
File path prefix or byte stream to which the image shall be written.
fb_format (str):
The image format to use in case it is necessary to (re-)encode the data.
"""
# https://crbug.com/pdfium/1930
extraction_gen = _extract_smart(self, *args, **kwargs)
format = next(extraction_gen)
if isinstance(dest, (str, Path)):
with open(f"{dest}.{format}", "wb") as buf:
extraction_gen.send(buf)
elif pdfium_i.is_stream(dest, "w"):
extraction_gen.send(dest)
else:
raise ValueError(f"Cannot extract to '{dest}'")
_ImageInfo = namedtuple("_ImageInfo", ("format", "mode", "metadata"))
class _ImageExtractionError (Exception):
pass
def _get_pil_mode(cs, bpp):
# As of Jan 2025, pdfium does not provide access to the palette, so we cannot handle indexed (palettized) color space.
# TODO handle ICC-based color spaces (pdfium now provides access to the ICC profile via FPDFImageObj_GetIccProfileDataDecoded(), see commit edd7c5cf)
if cs == pdfium_c.FPDF_COLORSPACE_DEVICEGRAY:
return "1" if bpp == 1 else "L"
elif cs == pdfium_c.FPDF_COLORSPACE_DEVICERGB:
return "RGB"
elif cs == pdfium_c.FPDF_COLORSPACE_DEVICECMYK:
return "CMYK"
else:
return None
def _extract_smart(image_obj, fb_format=None):
try:
# TODO can we change PdfImage.get_data() to take an mmap, so the data could be written directly into a file rather than an in-memory array?
data, info = _extract_direct(image_obj)
except _ImageExtractionError as e:
logger.debug(str(e))
pil_image = image_obj.get_bitmap(render=False).to_pil()
else:
pil_image = None
format = info.format
if format == "raw":
metadata = info.metadata
pil_image = Lazy.PIL_Image.frombuffer(
info.mode,
(metadata.width, metadata.height),
image_obj.get_data(decode_simple=True),
"raw", info.mode, 0, 1,
)
if pil_image:
format = fb_format
if not format:
format = "tiff" if pil_image.mode == "CMYK" else "png"
buffer = yield format
if pil_image:
pil_image.save(buffer, format=format)
else:
buffer.write(data)
yield # breakpoint preventing StopIteration on .send()
def _extract_direct(image_obj):
all_filters = image_obj.get_filters()
complex_filters = tuple(f for f in all_filters if f not in PdfImage.SIMPLE_FILTERS)
metadata = image_obj.get_metadata()
mode = _get_pil_mode(metadata.colorspace, metadata.bits_per_pixel)
if not complex_filters:
if mode:
out_data = image_obj.get_data(decode_simple=True)
out_format = "raw"
else:
raise _ImageExtractionError(f"Unhandled color space {pdfium_i.ColorspaceToStr.get(metadata.colorspace)} - don't know how to treat data.")
elif len(complex_filters) == 1:
f, = complex_filters
if f == "DCTDecode":
out_data = image_obj.get_data(decode_simple=True)
out_format = "jpg"
elif f == "JPXDecode":
out_data = image_obj.get_data(decode_simple=True)
out_format = "jp2"
else:
raise _ImageExtractionError(f"Unhandled complex filter {f}.")
else:
raise _ImageExtractionError(f"Cannot handle multiple complex filters {complex_filters}.")
return out_data, _ImageInfo(out_format, mode, metadata)
@@ -0,0 +1,264 @@
# SPDX-FileCopyrightText: 2026 geisserml <geisserml@gmail.com>
# SPDX-License-Identifier: Apache-2.0 OR BSD-3-Clause
__all__ = ("PdfSysfontBase", "PdfDefaultTTFMap")
import sys
import ctypes
import atexit
import logging
import pypdfium2.raw as pdfium_c
import pypdfium2.internal as pdfium_i
from pypdfium2._helpers.misc import PdfiumError
from pypdfium2_cfg.stl import cached_property
logger = logging.getLogger(__name__)
class _DefaultSysfontInfoClass (pdfium_i.AutoCastable):
def __init__(self):
self._is_loaded = False
@cached_property
def raw(self):
logger.debug("Load default sysfont info")
default_ptr = pdfium_c.FPDF_GetDefaultSystemFontInfo()
if not default_ptr:
raise PdfiumError(f"No default FPDF_SYSFONTINFO available on this platform ({sys.platform!r}), cannot use {type(self).__name__}.")
self._is_loaded = True
# trust in python to invoke exit handlers in reverse order to creation
# this goes before any PdfSysfontBase atexit.register(), so it should only ever be closed after the sysfontinfo which relies on this default to remain valid
atexit.register(self._close_impl)
pdfium_i.ObjectTracker[None].add(self._wref_to_self)
return default_ptr.contents
def _close_impl(self):
if not self._is_loaded:
return
pdfium_i._debug_close("Free default sysfont info")
pdfium_c.FPDF_FreeDefaultSystemFontInfo(self.raw)
del self.raw
pdfium_i.ObjectTracker[None].remove(self._wref_to_self)
self._is_loaded = False
def close(self):
atexit.unregister(self._close_impl)
self._close_impl()
_DefaultSysfontInfo = _DefaultSysfontInfoClass()
class _DefaultTTFMapClass:
@cached_property
def value(self):
# logger.debug("Retrieving default TT Font map...")
count = pdfium_c.FPDF_GetDefaultTTFMapCount()
map = {}
for i in range(count):
entry = pdfium_c.FPDF_GetDefaultTTFMapEntry(i).contents
map[entry.charset] = ctypes.cast(entry.fontname, ctypes.c_char_p).value # TODO decode
return map
def get(self, key, default=None):
out = self.value.get(key, default)
self.get = self.value.get # optimize away layer of indirection
return out
# FIXME sphinx docs don't support singleton pattern properly?
PdfDefaultTTFMap = _DefaultTTFMapClass()
"""
This object exposes the default TT Font map used by pdfium.\n
Access the ``.value`` cached property to obtain the map, or call ``.get(charset)``.
Note:
There is no guarantee as to whether a default font is installed or not.
If not installed, a system or internal substitute may be chosen by pdfium. |br|
``DEBUG_SYSFONTS=1 pypdfium2 default-fonts`` should give you some idea about substitution.
"""
_CallbackNames = ("Release", "EnumFonts", "MapFont", "GetFont", "GetFontData", "GetFaceName", "GetFontCharset", "DeleteFont")
class PdfSysfontBase (pdfium_i.AutoCastable):
"""
Base helper class to create a ``FPDF_SYSFONTINFO`` callback system.
Callbacks can be implemented by subclassing (see `fpdf_sysfontinfo.h` for available callouts and documentation).
This constructor merely creates the underlying ``FPDF_SYSFONTINFO`` instance.
Call :meth:`.setup` to actually register it with pdfium.
System font handlers may wrap another implementation, by default the root implementation provided by pdfium.
When a callback is not implemented, it will be automatically delegated to the default handler.
See the example below for how to invoke the default handler in a callback:
.. code-block:: python
class MySysfontImpl (PdfSysfontBase):
# substitute CallbackName accordingly
def CallbackName(self, _, arg1, arg2, ...)
print("Wrap before")
# Important: Do not pass the _ argument here, that's a pointer to self.raw.
# Pass self.default instead. The C callback expects its own struct, not the wrapper.
out = self.default.CallbackName(self.default, arg1, arg2, ...)
print("Wrap after")
return out
Alternatively, if using subclassing, you may want\n
.. code-block:: python\n
out = super().CallbackName(_, arg1, arg2, ...)\n
when the next class in the MRO has an implementation that you want to call.
Parameters:
default (None | FPDF_SYSFONTINFO | PdfSysfontBase):
The sysfont handler to be wrapped. If None (the default), pdfium's root implementation will be used.
Otherwise, this can be either a raw ``FPDF_SYSFONTINFO`` or another :class:`.PdfSysfontBase` instance.
Note:
When another :class:`.PdfSysfontBase` is being wrapped, some tricks are applied to avoid overhead:\n
- Where wrapper and child share the same callback, the child method will be forwarded to the wrapper (so, as a side effect, even stacking instances of the same class would result in only one call).
- Also, only in the actual ``FPDF_SYSFONTINFO`` object are callbacks ever enclosed in their :func:`~ctypes.CFUNCTYPE`, whereas wrappers call the original function directly.
Attributes:
raw (FPDF_SYSFONTINFO):
The underlying ``FPDF_SYSFONTINFO`` interface struct implemented by this class. May wrap :attr:`.default`.
default (FPDF_SYSFONTINFO | PdfSysfontBase):
The sysfont handler being wrapped. Wrapper callbacks typically delegate the actual work to the default implementation.
version (int):
The ``FPDF_SYSFONTINFO`` struct version used. Matches :attr:`.default.version` and :attr:`.raw.version`.
This is provided for interface compatibility with ``FPDF_SYSFONTINFO``, so that :attr:`.default` can be either a raw struct or :class:`.PdfSysfontBase`.
"""
#: PdfSysfontBase | None: Currently registered sysfont handler, or None if no sysfont handler is installed. This is a class-level attribute.
SINGLETON = None
def __init__(self, default=None):
self._is_installed = False
self._reusable = None
self._destroyed = False
self._child = None
if default is None:
self.default = _DefaultSysfontInfo.raw
else:
self.default = default
if isinstance(self.default, PdfSysfontBase):
self._child = self.default
self._forward_default_callbacks()
self.version = self.default.version
self.raw = pdfium_c.FPDF_SYSFONTINFO()
self.raw.version = self.version
callbacks = {n: getattr(self, n) for n in _CallbackNames}
if self.version != 1: # as per docs
del callbacks["EnumFonts"]
pdfium_i.set_callbacks(self.raw, **callbacks)
def _forward_default_callbacks(self):
# for any callbacks that were not re-implemented, we forward from default to avoid needless python function calls
reference_class = type(self) # or really just PdfSysfontBase?
for cb_name in _CallbackNames:
candidate = getattr(self.default, cb_name)
if getattr(reference_class, cb_name) is candidate.__func__:
setattr(self, cb_name, candidate)
def _iterkids(self):
child = self._child
while child:
yield child
child = child._child
def setup(self, reusable=False):
"""
Install (activate) the sysfont handler.
Note:\n
Once this method has been called, the instance is (by default) kept alive until the end of session, through an exit handler.
To stop the sysfont handler earlier, call :meth:`.close`.\n
Sysfont handlers are singleton, i.e. only one handler can be active at a time.
When a new handler is installed, the previous handler (if any) is implicitly closed.
"""
if PdfSysfontBase.SINGLETON is not None:
logger.info(f"Installing a new {type(self).__name__} instance implicitly closes previous sysfont handler instance {PdfSysfontBase.SINGLETON}")
PdfSysfontBase.SINGLETON.close(reusable=True)
if any(h._destroyed for h in (self, *self._iterkids())):
raise PdfiumError("You cannot register a sysfontinfo that has been destroyed, whether directly or indirectly. Pass `reusable=True` on setup or closing of handlers as necessary. Singleton replacement can do this implicitly.")
# trust in python to keep any object members (self.raw, self.default) alive while the object itself is referenced
# note that the object may still be needed after it was closed if reusable=True has been set and it is being wrapped by another sysfont handler
pdfium_c.FPDF_SetSystemFontInfo(self.raw)
PdfSysfontBase.SINGLETON = self
self._is_installed = True
self._reusable = reusable
atexit.register(self._close_impl)
pdfium_i.ObjectTracker[None].add(self._wref_to_self)
def _close_impl(self):
if not self._is_installed:
return
pdfium_i._debug_close(f"Close sysfontinfo")
# propagate parent state across all children, direct or indirect
for child in self._iterkids():
child._reusable = self._reusable
pdfium_c.FPDF_SetSystemFontInfo(None)
if self._destroyed:
# Assuming pdfium's default impl was used. In the unlikely event that it was not used, this is a no-op.
_DefaultSysfontInfo.close()
PdfSysfontBase.SINGLETON = None
pdfium_i.ObjectTracker[None].remove(self._wref_to_self)
def close(self, reusable=None): # manual
"""
Manually close the sysfont handler.
This unregisters the exit handler and releases the sysfont handler immediately.
See the note above for how sysfont handler lifetime is managed by default.
Parameters:
reusable (bool):
If False (the default), closing will destroy pdfium's default handler, rendering any direct or indirect wrappers thereof unusable.
If True, however, the default handler will not be harmed, so the object can be reused, like re-installing it some time after closing, wrapping it in another object, or just preserving the default handler for a new :class:`.PdfSysfontBase` instance.
This is automatically set to True on singleton replacement, when the previous handler is implicitly closed (i.e. ownership of the default instance is transferred to the new handler).
"""
if reusable is not None:
self._reusable = reusable
atexit.unregister(self._close_impl)
self._close_impl()
def Release(self, _):
if self._reusable:
pdfium_i._debug_close(f"fontinfo::Release: skip because it is reusable")
return
pdfium_i._debug_close(f"fontinfo::Release: actually release (wrapped={self._child})")
self._destroyed = True
return self.default.Release(self.default)
def EnumFonts(self, _, pMapper):
return self.default.EnumFonts(self.default, pMapper)
def MapFont(self, _, weight, bItalic, charset, pitch_family, face, _ignored):
return self.default.MapFont(self.default, weight, bItalic, charset, pitch_family, face, _ignored)
def GetFont(self, _, face):
return self.default.GetFont(self.default, face)
def GetFontData(self, _, hFont, table, buffer, buf_size):
return self.default.GetFontData(self.default, hFont, table, buffer, buf_size)
def GetFaceName(self, _, hFont, buffer, buf_size):
return self.default.GetFaceName(self.default, hFont, buffer, buf_size)
def GetFontCharset(self, _, hFont):
return self.default.GetFontCharset(self.default, hFont)
def DeleteFont(self, _, hFont):
return self.default.DeleteFont(self.default, hFont)
@@ -0,0 +1,334 @@
# SPDX-FileCopyrightText: 2026 geisserml <geisserml@gmail.com>
# SPDX-License-Identifier: Apache-2.0 OR BSD-3-Clause
__all__ = ("PdfTextPage", "PdfTextSearcher")
import ctypes
import logging
from codecs import decode
import pypdfium2.raw as pdfium_c
import pypdfium2.internal as pdfium_i
from pypdfium2._helpers.misc import PdfiumError
from pypdfium2._helpers.pageobjects import PdfTextObj
from pypdfium2_cfg.stl import cached_property
c_double = ctypes.c_double
logger = logging.getLogger(__name__)
class PdfTextPage (pdfium_i.AutoCloseable):
"""
Text page helper class.
Note:
PDFium's text APIs generally output CRLF (``\\r\\n``) style line breaks.
This may be undesirable or confusing in some situations, e.g. when processing the output with an (unaware) parser on the command line.
If this is an issue, replace ``\\r\\n`` with just ``\\n``.
Hint:
(py)pdfium itself does not implement layout analysis, such as detecting words/lines/paragraphs.
However, there may be third-party extensions for this job, e.g.: https://github.com/VikParuchuri/pdftext
Attributes:
raw (FPDF_TEXTPAGE):
The underlying PDFium textpage handle.
page (PdfPage):
Reference to the page this textpage belongs to.
"""
def __init__(self, raw, page):
self.raw = raw
self.page = page
super().__init__(pdfium_c.FPDFText_ClosePage)
@property
def parent(self): # AutoCloseable hook
return self.page
@cached_property
def _page_bbox(self):
return self.page.get_bbox()
def get_text_bounded(self, left=None, bottom=None, right=None, top=None, errors="ignore"):
"""
Extract text from given boundaries, in PDF canvas units.
If a boundary value is None, it defaults to the corresponding value of :meth:`.PdfPage.get_bbox`.
.. versionchanged:: 5.7.1
The page bbox is now managed as a cached property, so it will only be retrieved if needed.
This helps avoid overhead when :meth:`.get_text_bounded` is called many times with given rectangles.
In the event that you changed the page bbox, manually ``del textpage._page_bbox`` (if loaded) or re-initialize the textpage.
Parameters:
errors (str): Error treatment when decoding the data (see :func:`codecs.decode`).
Returns:
str: The text on the page area in question, or an empty string if no text was found.
"""
if left is None:
left = self._page_bbox[0]
if bottom is None:
bottom = self._page_bbox[1]
if right is None:
right = self._page_bbox[2]
if top is None:
top = self._page_bbox[3]
args = (self, left, top, right, bottom)
n_chars = pdfium_c.FPDFText_GetBoundedText(*args, None, 0)
if n_chars <= 0:
return ""
buffer = (ctypes.c_ushort * n_chars)()
pdfium_c.FPDFText_GetBoundedText(*args, buffer, n_chars)
return decode(buffer, "utf-16-le", errors=errors)
def _get_active_text_range(self, c_start, c_end, l_passive=0, r_passive=0):
if c_start > c_end:
return 0 # no active chars in range
t_start = pdfium_c.FPDFText_GetTextIndexFromCharIndex(self, c_start)
if t_start == -1:
return self._get_active_text_range(c_start+1, c_end, l_passive+1, r_passive)
t_end = pdfium_c.FPDFText_GetTextIndexFromCharIndex(self, c_end)
if t_end == -1:
return self._get_active_text_range(c_start, c_end-1, l_passive, r_passive+1)
return t_start, t_end, l_passive, r_passive
def get_text_range(self, index=0, count=-1, errors="ignore"):
"""
Extract text from a given range.
Parameters:
index (int): Index of the first char to include.
count (int): Number of chars to cover, relative to the internal char list. Defaults to -1 for all remaining chars after *index*.
errors (str): Error treatment when decoding the data (see :func:`codecs.decode`).
Returns:
str: The text in the range in question, or an empty string if no text was found.
Warning:
This method is limited to UCS-2, whereas :meth:`.get_text_bounded` provides full Unicode support.
Note:
* The returned text's length does not have to match *count*, even if it will for most PDFs.
This is because the underlying API may exclude/insert chars compared to the internal list, although rare in practice.
This means, if the char at ``i`` is excluded, ``get_text_range(i, 2)[1]`` will raise an index error.
Pdfium provides raw APIs ``FPDFText_GetTextIndexFromCharIndex()`` / ``FPDFText_GetCharIndexFromTextIndex()`` to translate between the two views and identify excluded/inserted chars.
* In case of leading/trailing excluded characters, pypdfium2 modifies *index* and *count* accordingly to prevent pdfium from unexpectedly reading beyond ``range(index, index+count)``.
"""
if count == -1:
count = self.count_chars() - index
# https://github.com/pypdfium2-team/pypdfium2/issues/261
# https://crbug.com/pdfium/2079
active_range = self._get_active_text_range(index, index+count-1)
if not active_range:
return ""
# NOTE since we have converted indices from char to text, they will shift accordingly for inserted/excluded chars, so this will calculate the exact output count
t_start, t_end, l_passive, r_passive = active_range
index += l_passive
count -= l_passive + r_passive
in_count = t_end+2 - t_start # including NUL terminator
buffer = (ctypes.c_ushort * in_count)()
out_count = pdfium_c.FPDFText_GetText(self, index, count, buffer)
assert in_count >= out_count, f"Buffer too small: {in_count} vs {out_count}"
# memoryview preserves element size
return decode(memoryview(buffer)[:out_count-1], "utf-16-le", errors=errors)
def count_chars(self):
"""
Returns:
int: The number of characters on the text page.
"""
n_chars = pdfium_c.FPDFText_CountChars(self)
if n_chars == -1:
raise PdfiumError("Failed to get character count.")
return n_chars
def count_rects(self, index=0, count=-1):
"""
Parameters:
index (int): Start character index.
count (int): Character count to consider (defaults to -1 for all remaining).
Returns:
int: The number of text rectangles in the given character range.
"""
n_rects = pdfium_c.FPDFText_CountRects(self, index, count)
if n_rects == -1:
raise PdfiumError("Failed to count rectangles.")
return n_rects
def get_index(self, x, y, x_tol, y_tol):
"""
Get the index of a character by position.
Parameters:
x (float): Horizontal position (in PDF canvas units).
y (float): Vertical position.
x_tol (float): Horizontal tolerance.
y_tol (float): Vertical tolerance.
Returns:
int | None: The index of the character at or nearby the point (x, y).
May be None if there is no character. If an internal error occurred, an exception will be raised.
"""
index = pdfium_c.FPDFText_GetCharIndexAtPos(self, x, y, x_tol, y_tol)
if index == -1:
return None
elif index == -3:
raise PdfiumError("An error occurred on attempt to get char index by pos.")
assert index >= 0, "Negative return is not permitted (unhandled error code?)"
return index
def get_charbox(self, index, loose=False):
"""
Get the bounding box of a single character.
Parameters:
index (int):
Index of the character to work with, in the page's character array.
loose (bool):
Get a more comprehensive box covering the entire font bounds, as opposed to the default tight box specific to the one character.
Returns:
float: Values for left, bottom, right and top in PDF canvas units.
"""
if loose:
rect = pdfium_c.FS_RECTF()
ok = pdfium_c.FPDFText_GetLooseCharBox(self, index, rect)
l, b, r, t = rect.left, rect.bottom, rect.right, rect.top
else:
l, b, r, t = c_double(), c_double(), c_double(), c_double()
ok = pdfium_c.FPDFText_GetCharBox(self, index, l, r, b, t) # yes, lrbt!
l, b, r, t = l.value, b.value, r.value, t.value
if not ok:
raise PdfiumError("Failed to get charbox.")
return l, b, r, t
def get_rect(self, index):
"""
Get the bounding box of a text rectangle at the given index.
Attention:
:meth:`.count_rects` must be called once with default params before subsequent :meth:`.get_rect` calls for this function to work.
Returns:
float: Values for left, bottom, right and top in PDF canvas units.
"""
l, b, r, t = c_double(), c_double(), c_double(), c_double()
ok = pdfium_c.FPDFText_GetRect(self, index, l, t, r, b) # yes, ltrb!
if not ok:
raise PdfiumError("Failed to get rectangle. (Make sure count_rects() was called with default params once before subsequent get_rect() calls.)")
return (l.value, b.value, r.value, t.value)
def get_textobj(self, index):
"""
Returns:
PdfTextObj | None: A handle to the textobject that includes the char at *index*, or None if it could not be resolved (e.g. escape character).
Tip:
Textobjects can also be obtained through :meth:`.PdfPage.get_objects`.
"""
raw_obj = pdfium_c.FPDFText_GetTextObject(self, index)
if not raw_obj:
return None
# The raw_obj is _not_ owned by the caller, and the textpage must remain alive while the textobject lives.
return PdfTextObj(raw_obj, textpage=self)
def search(self, text, index=0, match_case=False, match_whole_word=False, consecutive=False, flags=0):
"""
Locate text on the page.
Parameters:
text (str):
The string to search for.
index (int):
Character index at which to start searching.
match_case (bool):
If True, the search will be case-specific (upper and lower letters treated as different characters).
match_whole_word (bool):
If True, substring occurrences will be ignored (e.g. `cat` would not match `category`).
consecutive (bool):
If False (the default), :meth:`.search` will skip past the current match to look for the next match.
If True, parts of the previous match may be caught again (e.g. searching for `aa` in `aaaa` would match 3 rather than 2 times).
flags (int):
Passthrough of raw pdfium searching flags. Note that you may want to use the boolean options instead.
Returns:
PdfTextSearcher: A helper object to search text.
"""
if not text:
raise ValueError("Text length must be greater than 0.")
if match_case:
flags |= pdfium_c.FPDF_MATCHCASE
if match_whole_word:
flags |= pdfium_c.FPDF_MATCHWHOLEWORD
if consecutive:
flags |= pdfium_c.FPDF_CONSECUTIVE
enc_text = (text + "\x00").encode("utf-16-le")
enc_text_ptr = ctypes.cast(enc_text, ctypes.POINTER(ctypes.c_ushort))
raw_searcher = pdfium_c.FPDFText_FindStart(self, enc_text_ptr, flags, index)
searcher = PdfTextSearcher(raw_searcher, self)
self._add_kid(searcher)
return searcher
class PdfTextSearcher (pdfium_i.AutoCloseable):
"""
Text searcher helper class.
Attributes:
raw (FPDF_SCHHANDLE): The underlying PDFium searcher handle.
textpage (PdfTextPage): Reference to the textpage this searcher belongs to.
"""
def __init__(self, raw, textpage):
self.raw = raw
self.textpage = textpage
super().__init__(pdfium_c.FPDFText_FindClose)
@property
def parent(self): # AutoCloseable hook
return self.textpage
def _get_occurrence(self, find_func):
ok = find_func(self)
if not ok:
return None
index = pdfium_c.FPDFText_GetSchResultIndex(self)
count = pdfium_c.FPDFText_GetSchCount(self)
return index, count
def get_next(self):
"""
Returns:
(int, int) | None: Start character index and count of the next occurrence, or None if the last occurrence was passed.
"""
return self._get_occurrence(pdfium_c.FPDFText_FindNext)
def get_prev(self):
"""
Returns:
(int, int) | None: Start character index and count of the previous occurrence (i. e. the one before the last valid occurrence), or None if the last occurrence was passed.
"""
return self._get_occurrence(pdfium_c.FPDFText_FindPrev)
@@ -0,0 +1,69 @@
# SPDX-FileCopyrightText: 2026 geisserml <geisserml@gmail.com>
# SPDX-License-Identifier: Apache-2.0 OR BSD-3-Clause
__all__ = ("PdfUnspHandler", )
import atexit
import logging
import pypdfium2.raw as pdfium_c
import pypdfium2.internal as pdfium_i
from pypdfium2._helpers.misc import PdfiumError
lib_logger = logging.getLogger("pypdfium2")
class PdfUnspHandler (pdfium_i.AutoCastable):
"""
Unsupported feature handler helper class.
Attributes:
raw (UNSUPPORT_INFO):
The underlying pdfium ``UNSUPPORT_INFO`` struct.
handlers (dict[str, typing.Callable]):
A dictionary of named handler functions to be called with an unsupported code (:attr:`FPDF_UNSP_*`) when PDFium detects an unsupported feature.
"""
SINGLETON = None
def __init__(self):
self.handlers = {}
self.raw = pdfium_c.UNSUPPORT_INFO(version=1)
def __call__(self, _, type):
for handler in self.handlers.values():
handler(type)
@staticmethod
def _default(type):
lib_logger.warning(f"Unsupported PDF feature: {pdfium_i.UnsupportedInfoToStr.get(type)}")
def _keep(self):
id(self.handlers)
id(self.raw)
def setup(self, add_default=True):
"""
Register the handler with PDFium, and install an exit function that will keep the object alive until the end of session.
Once set up, a :class:`.PdfUnspHandler` cannot be removed. It stands and falls with the library.
Thus, this function can only be called once in a session.
However, you may change the wrapped :attr:`.handlers` callbacks.
Call ``.handlers.clear()`` to remove all handlers, thereby effectively disabling the instance.
Parameters:
add_default (bool):
If True, add a default callback that will log unsupported features as warning.
"""
if PdfUnspHandler.SINGLETON:
raise RuntimeError("Only one PdfUnspHandler instance can be registered for a session.")
pdfium_i.set_callback(self.raw, "FSDK_UnSupport_Handler", self)
ok = pdfium_c.FSDK_SetUnSpObjProcessHandler(self.raw)
if not ok:
raise PdfiumError("Failed to register PdfUnspHandler object.")
PdfUnspHandler.SINGLETON = self
# TODO might want to have this unregistered in destroy_lib() after library destruction
atexit.register(self._keep)
if add_default:
self.handlers["default"] = PdfUnspHandler._default
@@ -0,0 +1,28 @@
# SPDX-FileCopyrightText: 2026 geisserml <geisserml@gmail.com>
# SPDX-License-Identifier: Apache-2.0 OR BSD-3-Clause
# see https://gist.github.com/mara004/6915e904797916b961e9c53b4fc874ec for alternative approaches to deferred imports
import logging
from pypdfium2_cfg.stl import cached_property
logger = logging.getLogger(__name__)
class _LazyClass:
@cached_property
def PIL_Image(self):
logger.debug("Evaluating lazy import 'PIL.Image' ...")
import PIL.Image; return PIL.Image
@cached_property
def numpy(self):
logger.debug("Evaluating lazy import 'numpy' ...")
import numpy; return numpy
@cached_property
def tabulate(self):
# logger.debug("Evaluating lazy import 'tabulate' ...")
from tabulate import tabulate; return tabulate
Lazy = _LazyClass()
@@ -0,0 +1,65 @@
# SPDX-FileCopyrightText: 2026 geisserml <geisserml@gmail.com>
# SPDX-License-Identifier: Apache-2.0 OR BSD-3-Clause
import atexit
import logging
import pypdfium2.raw as pdfium_c
import pypdfium2.internal as pdfium_i
from pypdfium2_cfg import DEBUG_AUTOCLOSE
logger = logging.getLogger("pypdfium2")
def init_lib():
assert not pdfium_i.LIBRARY_AVAILABLE
if DEBUG_AUTOCLOSE: # pragma: no cover
logger.debug("Initialize PDFium")
# PDFium init API may change in the future: https://crbug.com/pdfium/1446
# NOTE Technically, FPDF_InitLibrary() would be sufficient for our purposes, but pdfium docs say "This will be deprecated in the future", so don't use it to be on the safe side. Also, avoid experimental config versions that might not be promoted to stable.
config = pdfium_c.FPDF_LIBRARY_CONFIG(
version = 2,
m_pUserFontPaths = None,
m_pIsolate = None,
m_v8EmbedderSlot = 0,
# m_pPlatform = None, # v3
# m_RendererType = pdfium_c.FPDF_RENDERERTYPE_AGG, # v4
)
pdfium_c.FPDF_InitLibraryWithConfig(config)
pdfium_i.LIBRARY_AVAILABLE.value = True
def _close_objects():
need_close = []
for cls, obj_wrefs in pdfium_i.ObjectTracker.items():
# pdfium_i._debug_close(f"{cls and cls.__name__}: {obj_wrefs}")
for wref in obj_wrefs:
obj = wref()
if obj is None:
pdfium_i._warn_close(f"Weakref {wref} was not cleaned up from ObjectTracker.")
else:
# outsource actual closing to avoid "RuntimeError: Set changed size during iteration" (because closing removes the object from the set of weakrefs)
need_close.append(obj)
if need_close:
pdfium_i._warn_close(f"The following objects are still open and will now be closed: {need_close}")
for obj in need_close:
obj.close()
def destroy_lib(): # pragma: no cover
assert pdfium_i.LIBRARY_AVAILABLE
try:
_close_objects()
finally:
pdfium_i._debug_close("Destroy PDFium")
pdfium_c.FPDF_DestroyLibrary()
pdfium_i.LIBRARY_AVAILABLE.value = False
# Load pdfium
init_lib()
# Register an exit handler that will free pdfium
atexit.register(destroy_lib)
@@ -0,0 +1,6 @@
# SPDX-FileCopyrightText: 2026 geisserml <geisserml@gmail.com>
# SPDX-License-Identifier: Apache-2.0 OR BSD-3-Clause
from pypdfium2.internal.bases import *
from pypdfium2.internal.consts import *
from pypdfium2.internal.utils import *
@@ -0,0 +1,186 @@
# SPDX-FileCopyrightText: 2026 geisserml <geisserml@gmail.com>
# SPDX-License-Identifier: Apache-2.0 OR BSD-3-Clause
__all__ = ("AutoCastable", "AutoCloseable", "ObjectTracker", "LIBRARY_AVAILABLE", "DEBUG_AUTOCLOSE", "_debug_close", "_warn_close")
import os
import sys
import enum
import uuid
import weakref
import logging
from collections import defaultdict
import pypdfium2_cfg
from pypdfium2_cfg import DEBUG_AUTOCLOSE # bw compat
from pypdfium2_cfg.stl import cached_property
logger = logging.getLogger(__name__)
LIBRARY_AVAILABLE = pypdfium2_cfg._Mutable(False) # set to true on library init
ObjectTracker = defaultdict(set)
def _debug_close(msg, prio=logging.DEBUG): # pragma: no cover
# try to use os.write() rather than print() or logger.whatever() to avoid "reentrant call" or "I/O operation on closed file" exceptions on shutdown (see https://stackoverflow.com/q/75367828/15547292)
if prio < DEBUG_AUTOCLOSE.value:
return
try:
os.write(sys.stderr.fileno(), (msg+"\n").encode())
except Exception: # e.g. io.UnsupportedOperation
print(msg, file=sys.stderr)
def _warn_close(msg):
_debug_close(msg, logging.WARNING)
class _STATE (enum.Enum):
INVALID = -1
AUTO = 0
EXPLICIT = 1
BYPARENT = 2
# class _Dataclass:
#
# def _iter_fields(self):
# for slot in self.__slots__:
# yield getattr(self, slot)
#
# def __repr__(self):
# return f"{type(self).__name__}{tuple(self._iter_fields())}"
class _FinalizerInfo: # (_Dataclass)
__slots__ = ("close_func", "args", "kwargs", "tracked", "state")
def __init__(self, close_func, args, kwargs, tracked):
self.close_func = close_func
self.args, self.kwargs = args, kwargs
self.tracked = tracked
self.state = _STATE.AUTO
class _FinalizerOwner: # (_Dataclass)
__slots__ = ("raw", "parent", "wref", "type", "repr")
def __init__(self, raw, parent, wref, type, repr):
self.raw, self.parent = raw, parent
self.wref, self.type, self.repr = wref, type, repr
def _close_template(info, owner):
# This function must not pull in a reference to the object being finalized!
# https://docs.python.org/3/library/weakref.html#weakref.finalize
# > It is important to ensure that func, args and kwargs do not own any references to obj, either directly or indirectly, since otherwise obj will never be garbage collected. In particular, func should not be a bound method of obj.
_debug_close(f"Close ({info.state.name.lower()}) {owner.repr}")
if not LIBRARY_AVAILABLE: # pragma: no cover
_warn_close(f"-> Cannot close {owner.repr}; pdfium library is destroyed. This may cause a memory leak.")
return
assert info.state != _STATE.INVALID
parent = owner.parent
if parent is not None:
assert not parent._tree_closed()
if info.tracked:
assert owner.wref in parent._kids, f"{owner.repr} {owner.wref}, {parent} {parent._kids}"
parent._kids.remove(owner.wref)
info.close_func(owner.raw, *info.args, **info.kwargs)
ObjectTracker[owner.type].remove(owner.wref)
class AutoCastable:
@property
def _as_parameter_(self):
# trust in the caller not to invoke APIs on an object after .close()
# if not self.raw:
# raise RuntimeError("bool(obj.raw) must evaluate to True for use as C function parameter")
return self.raw
@cached_property
def _wref_to_self(self):
return weakref.ref(self)
class AutoCloseable (AutoCastable):
def __init__(self, close_func, *args, obj=None, needs_free=True, tracked=True, **kwargs):
# proactively prevent accidental double initialization
assert not hasattr(self, "_finalizer")
self._fin_info = _FinalizerInfo(close_func, args, kwargs, tracked)
self._fin_obj = obj
self._finalizer = None
if needs_free:
self._attach_finalizer()
@cached_property
def _kids(self):
return set()
@cached_property
def _uuid(self):
return uuid.uuid4() if DEBUG_AUTOCLOSE.value < logging.WARNING else None
def __repr__(self):
identifier = hex(id(self)) if self._uuid is None else self._uuid.hex[:14]
return f"<{type(self).__name__} {identifier}>"
def _attach_finalizer(self):
assert self._finalizer is None
# note, this captures the object's parent, repr and so on at finalizer installation time
# in case they ever change, we'd have to store the owner in an attribute and update it
owner = _FinalizerOwner(self.raw, self.parent, self._wref_to_self, type(self), repr(self))
obj = self if self._fin_obj is None else self._fin_obj
self._finalizer = weakref.finalize(obj, _close_template, self._fin_info, owner)
ObjectTracker[type(self)].add(self._wref_to_self)
def _detach_finalizer(self):
self._finalizer.detach()
self._finalizer = None
ObjectTracker[type(self)].remove(self._wref_to_self)
def _tree_closed(self):
if self.raw is None:
return True
if self.parent is not None:
return self.parent._tree_closed()
return False
def _add_kid(self, kid):
# assuming kid is also AutoCloseable
self._kids.add( kid._wref_to_self )
def close(self, _by_parent=False):
if not self.raw:
return False
# a finalizer's __bool__ still evaluates to true when .alive is False
if not self._finalizer or not self._finalizer.alive:
self.raw = None
return False
# only need to check this in manual closing, with finalizers the API contract promises the order of invocation
need_close = []
for k_wref in self._kids:
k = k_wref()
if k and k.raw:
# closing a child will remove it from the parent's kids set, so again outsource the actual closing to avoid "RuntimeError: Set changed size during iteration"
need_close.append(k)
for k in need_close:
k.close(_by_parent=True)
if self._kids:
logger.warning(f"Some kids weakrefs have not been cleaned up: {self._kids}")
self._kids.clear()
self._fin_info.state = _STATE.BYPARENT if _by_parent else _STATE.EXPLICIT
self._finalizer()
self._fin_info.state = _STATE.INVALID
self.raw = None
self._finalizer = None
return True
@@ -0,0 +1,186 @@
# SPDX-FileCopyrightText: 2026 geisserml <geisserml@gmail.com>
# SPDX-License-Identifier: Apache-2.0 OR BSD-3-Clause
import pypdfium2.raw as pdfium_c
from pypdfium2.version import PDFIUM_INFO
class _fallback_dict (dict):
def get(self, key, default_prefix="Unhandled constant"):
return dict.get(self, key, f"{default_prefix} {key}")
def copy(self):
return _fallback_dict(self) # dict constructor copies
#: Convert a rotation value in degrees to a PDFium constant.
RotationToConst = {
0: 0,
90: 1,
180: 2,
270: 3,
}
#: Convert a PDFium rotation constant to a value in degrees. Inversion of :data:`.RotationToConst`.
RotationToDegrees = {v: k for k, v in RotationToConst.items()}
#: Get the number of channels for a PDFium bitmap format. (:attr:`FPDFBitmap_Unknown` is deliberately not handled.)
BitmapTypeToNChannels = {
pdfium_c.FPDFBitmap_Gray: 1,
pdfium_c.FPDFBitmap_BGR: 3,
pdfium_c.FPDFBitmap_BGRx: 4,
pdfium_c.FPDFBitmap_BGRA: 4,
pdfium_c.FPDFBitmap_BGRA_Premul: 4,
}
#: Convert a PDFium bitmap format to string, assuming BGR byte order. (:attr:`FPDFBitmap_Unknown` is deliberately not handled.)
BitmapTypeToStr = {
pdfium_c.FPDFBitmap_Gray: "L",
pdfium_c.FPDFBitmap_BGR: "BGR",
pdfium_c.FPDFBitmap_BGRx: "BGRX",
pdfium_c.FPDFBitmap_BGRA: "BGRA",
pdfium_c.FPDFBitmap_BGRA_Premul: "BGRa"
}
#: Convert a PDFium bitmap format to string, assuming RGB byte order. (:attr:`FPDFBitmap_Unknown` is deliberately not handled.)
BitmapTypeToStrReverse = {
pdfium_c.FPDFBitmap_Gray: "L",
pdfium_c.FPDFBitmap_BGR: "RGB",
pdfium_c.FPDFBitmap_BGRx: "RGBX",
pdfium_c.FPDFBitmap_BGRA: "RGBA",
pdfium_c.FPDFBitmap_BGRA_Premul: "RGBa"
}
# TODO consider a bi-directional dict in the future?
#: Convert a string to PDFium bitmap format, assuming BGR byte order. Inversion of :data:`BitmapTypeToStr`.
BitmapStrToConst = {v: k for k, v in BitmapTypeToStr.items()}
#: Convert a string to PDFium bitmap format, assuming RGB byte order. Inversion of :data:`BitmapTypeToStrReverse`.
BitmapStrReverseToConst = {v: k for k, v in BitmapTypeToStrReverse.items()}
#: Convert a PDFium form type (:attr:`FORMTYPE_*`) to string.
FormTypeToStr = _fallback_dict({
pdfium_c.FORMTYPE_NONE: "None",
pdfium_c.FORMTYPE_ACRO_FORM: "AcroForm",
pdfium_c.FORMTYPE_XFA_FULL: "XFA",
pdfium_c.FORMTYPE_XFA_FOREGROUND: "XFAF",
})
#: Convert a PDFium color space constant (:attr:`FPDF_COLORSPACE_*`) to string.
ColorspaceToStr = _fallback_dict({
pdfium_c.FPDF_COLORSPACE_UNKNOWN: "?",
pdfium_c.FPDF_COLORSPACE_DEVICEGRAY: "DeviceGray",
pdfium_c.FPDF_COLORSPACE_DEVICERGB: "DeviceRGB",
pdfium_c.FPDF_COLORSPACE_DEVICECMYK: "DeviceCMYK",
pdfium_c.FPDF_COLORSPACE_CALGRAY: "CalGray",
pdfium_c.FPDF_COLORSPACE_CALRGB: "CalRGB",
pdfium_c.FPDF_COLORSPACE_LAB: "Lab",
pdfium_c.FPDF_COLORSPACE_ICCBASED: "ICCBased",
pdfium_c.FPDF_COLORSPACE_SEPARATION: "Separation",
pdfium_c.FPDF_COLORSPACE_DEVICEN: "DeviceN",
pdfium_c.FPDF_COLORSPACE_INDEXED: "Indexed", # i.e. palettized
pdfium_c.FPDF_COLORSPACE_PATTERN: "Pattern",
})
#: Convert a PDFium view mode constant (:attr:`PDFDEST_VIEW_*`) to string.
ViewmodeToStr = _fallback_dict({
pdfium_c.PDFDEST_VIEW_UNKNOWN_MODE: "?",
pdfium_c.PDFDEST_VIEW_XYZ: "XYZ",
pdfium_c.PDFDEST_VIEW_FIT: "Fit",
pdfium_c.PDFDEST_VIEW_FITH: "FitH",
pdfium_c.PDFDEST_VIEW_FITV: "FitV",
pdfium_c.PDFDEST_VIEW_FITR: "FitR",
pdfium_c.PDFDEST_VIEW_FITB: "FitB",
pdfium_c.PDFDEST_VIEW_FITBH: "FitBH",
pdfium_c.PDFDEST_VIEW_FITBV: "FitBV",
})
#: Convert a PDFium object type constant (:attr:`FPDF_PAGEOBJ_*`) to string.
ObjectTypeToStr = _fallback_dict({
pdfium_c.FPDF_PAGEOBJ_UNKNOWN: "?",
pdfium_c.FPDF_PAGEOBJ_TEXT: "text",
pdfium_c.FPDF_PAGEOBJ_PATH: "path",
pdfium_c.FPDF_PAGEOBJ_IMAGE: "image",
pdfium_c.FPDF_PAGEOBJ_SHADING: "shading",
pdfium_c.FPDF_PAGEOBJ_FORM: "form",
})
#: Convert an object type string to a PDFium constant. Inversion of :data:`.ObjectTypeToStr`.
ObjectTypeToConst = {v: k for k, v in ObjectTypeToStr.items()}
#: Convert a PDFium page mode constant (:attr:`PAGEMODE_*`) to string.
PageModeToStr = _fallback_dict({
pdfium_c.PAGEMODE_UNKNOWN: "?",
pdfium_c.PAGEMODE_USENONE: "None",
pdfium_c.PAGEMODE_USEOUTLINES: "Outline",
pdfium_c.PAGEMODE_USETHUMBS: "Thumbnails",
pdfium_c.PAGEMODE_FULLSCREEN: "Full-screen",
pdfium_c.PAGEMODE_USEOC: "Layers",
pdfium_c.PAGEMODE_USEATTACHMENTS: "Attachments",
})
#: Convert a PDFium error constant (:attr:`FPDF_ERR_*`) to string.
ErrorToStr = _fallback_dict({
pdfium_c.FPDF_ERR_SUCCESS: "Success",
pdfium_c.FPDF_ERR_UNKNOWN: "Unknown error",
pdfium_c.FPDF_ERR_FILE: "File access error",
pdfium_c.FPDF_ERR_FORMAT: "Data format error",
pdfium_c.FPDF_ERR_PASSWORD: "Incorrect password error",
pdfium_c.FPDF_ERR_SECURITY: "Unsupported security scheme error",
pdfium_c.FPDF_ERR_PAGE: "Page not found or content error",
})
if "XFA" in PDFIUM_INFO.flags: # pragma: no cover
#: [XFA builds only] Convert a PDFium XFA error constant (:attr:`FPDF_ERR_XFA*`) to string.
XFAErrorToStr = _fallback_dict({
pdfium_c.FPDF_ERR_XFALOAD: "Load error",
pdfium_c.FPDF_ERR_XFALAYOUT: "Layout error",
})
#: Convert a PDFium unsupported constant (:attr:`FPDF_UNSP_*`) to string.
UnsupportedInfoToStr = _fallback_dict({
pdfium_c.FPDF_UNSP_DOC_XFAFORM: "XFA form",
pdfium_c.FPDF_UNSP_DOC_PORTABLECOLLECTION: "Portable collection",
# https://crbug.com/pdfium/1945
pdfium_c.FPDF_UNSP_DOC_ATTACHMENT: "Attachment (incomplete support)",
pdfium_c.FPDF_UNSP_DOC_SECURITY: "Security",
pdfium_c.FPDF_UNSP_DOC_SHAREDREVIEW: "Shared review",
pdfium_c.FPDF_UNSP_DOC_SHAREDFORM_ACROBAT: "Shared form (acrobat)",
pdfium_c.FPDF_UNSP_DOC_SHAREDFORM_FILESYSTEM: "Shared form (filesystem)",
pdfium_c.FPDF_UNSP_DOC_SHAREDFORM_EMAIL: "Shared form (email)",
pdfium_c.FPDF_UNSP_ANNOT_3DANNOT: "3D annotation",
pdfium_c.FPDF_UNSP_ANNOT_MOVIE: "Movie annotation",
pdfium_c.FPDF_UNSP_ANNOT_SOUND: "Sound annotation",
pdfium_c.FPDF_UNSP_ANNOT_SCREEN_MEDIA: "Screen media annotation",
pdfium_c.FPDF_UNSP_ANNOT_SCREEN_RICHMEDIA: "Screen rich media annotation",
pdfium_c.FPDF_UNSP_ANNOT_ATTACHMENT: "Attachment annotation",
pdfium_c.FPDF_UNSP_ANNOT_SIG: "Signature annotation",
})
#: Convert a PDFium charset type constant (:attr:`FXFONT_*_CHARSET`) to string.
CharsetToStr = _fallback_dict({
pdfium_c.FXFONT_ANSI_CHARSET: "ANSI",
pdfium_c.FXFONT_DEFAULT_CHARSET: "Default",
pdfium_c.FXFONT_SYMBOL_CHARSET: "Symbol",
pdfium_c.FXFONT_SHIFTJIS_CHARSET: "ShiftJIS",
pdfium_c.FXFONT_HANGEUL_CHARSET: "Hangeul",
pdfium_c.FXFONT_GB2312_CHARSET: "GB2312",
pdfium_c.FXFONT_CHINESEBIG5_CHARSET: "ChineseBig5",
pdfium_c.FXFONT_GREEK_CHARSET: "Greek",
pdfium_c.FXFONT_VIETNAMESE_CHARSET: "Vietnamese",
pdfium_c.FXFONT_HEBREW_CHARSET: "Hebrew",
pdfium_c.FXFONT_ARABIC_CHARSET: "Arabic",
pdfium_c.FXFONT_CYRILLIC_CHARSET: "Cyrillic",
pdfium_c.FXFONT_THAI_CHARSET: "Thai",
pdfium_c.FXFONT_EASTERNEUROPEAN_CHARSET: "EasternEuropean",
})
RenderStatusToStr = _fallback_dict({
pdfium_c.FPDF_RENDER_READY: "ready",
pdfium_c.FPDF_RENDER_TOBECONTINUED: "to be continued",
pdfium_c.FPDF_RENDER_DONE: "done",
pdfium_c.FPDF_RENDER_FAILED: "failed",
})
@@ -0,0 +1,105 @@
# SPDX-FileCopyrightText: 2026 geisserml <geisserml@gmail.com>
# SPDX-License-Identifier: Apache-2.0 OR BSD-3-Clause
import os
import ctypes
import pypdfium2.raw as pdfium_c
def color_tohex(color, rev_byteorder):
if not all(0 <= c <= 255 for c in color):
raise ValueError("Color value exceeds boundaries.")
# different color interpretation with FPDF_REVERSE_BYTE_ORDER might be a bug? at least it's not documented.
r, g, b, a = color
channels = (a, b, g, r) if rev_byteorder else (a, r, g, b)
c_color = 0
shift = 24
for c in channels:
c_color |= c << shift
shift -= 8
return c_color
def set_callback(struct, fname, callback):
setattr(struct, fname, type(getattr(struct, fname))(callback))
def set_callbacks(struct, **kwargs):
for fname, callback in kwargs.items():
setattr(struct, fname, type(getattr(struct, fname))(callback))
def is_stream(buf, spec="r"):
methods = []
assert set(spec).issubset( set("rw") )
if "r" in spec:
methods += ("seek", "tell", "read", "readinto")
if "w" in spec:
methods.append("write")
return all(callable(getattr(buf, a, None)) for a in methods)
def get_buffer(ptr, size):
obj = ptr.contents
return (type(obj) * size).from_address( ctypes.addressof(obj) )
class _buffer_reader:
def __init__(self, py_buffer):
self.py_buffer = py_buffer
def __call__(self, _, position, p_buf_first, size):
c_buffer = get_buffer(p_buf_first, size)
self.py_buffer.seek(position)
# compare requested and read size to ensure we never pass on uninitialized memory without reporting error, in case readinto() might have failed to consume enough input
read_size = self.py_buffer.readinto(c_buffer)
return int(read_size == size)
class _buffer_writer:
def __init__(self, py_buffer):
self.py_buffer = py_buffer
def __call__(self, _, p_data_first, size):
# c_void_p has no .contents, need to cast
p_data_first = ctypes.cast(p_data_first, ctypes.POINTER(ctypes.c_ubyte))
c_buffer = get_buffer(p_data_first, size)
self.py_buffer.write(c_buffer)
return 1
def get_bufreader(buffer):
file_len = buffer.seek(0, os.SEEK_END)
buffer.seek(0)
reader = pdfium_c.FPDF_FILEACCESS()
reader.m_FileLen = file_len
set_callback(reader, "m_GetBlock", _buffer_reader(buffer))
reader.m_Param = None
to_hold = (reader.m_GetBlock, )
return reader, to_hold
def get_bufwriter(buffer):
writer = pdfium_c.FPDF_FILEWRITE(version=1)
set_callback(writer, "WriteBlock", _buffer_writer(buffer))
return writer
def pages_c_array(pages):
if not pages:
return None, 0
count = len(pages)
c_array = (pdfium_c.FPDF_PAGE * count)(*(p.raw for p in pages))
return c_array, count
FPDF_WCHAR_size = ctypes.sizeof(pdfium_c.FPDF_WCHAR)
@@ -0,0 +1,5 @@
# SPDX-FileCopyrightText: 2026 geisserml <geisserml@gmail.com>
# SPDX-License-Identifier: Apache-2.0 OR BSD-3-Clause
# platform files are managed in an own pypdfium2_raw module, cleanly separating raw bindings and helpers
from pypdfium2_raw.bindings import * # noqa
@@ -0,0 +1,11 @@
{
"major": 5,
"minor": 14,
"patch": 0,
"beta": null,
"n_commits": 0,
"hash": null,
"dirty": false,
"data_source": "git",
"is_editable": false
}
@@ -0,0 +1,72 @@
# SPDX-FileCopyrightText: 2026 geisserml <geisserml@gmail.com>
# SPDX-License-Identifier: Apache-2.0 OR BSD-3-Clause
__all__ = ("PYPDFIUM_INFO", "PDFIUM_INFO")
from pathlib import Path
from pypdfium2_raw.version import _version_class, PDFIUM_INFO
class _version_pypdfium2 (_version_class):
_FILE = Path(__file__).parent / "version.json"
_TAG_FIELDS = ("major", "minor", "patch")
def _hook(self):
self.tag = self._craft_tag()
if self.beta is not None:
self.tag += f"b{self.beta}"
suffixes = ["dirty"] if self.dirty else []
self.desc = self._craft_desc(*suffixes)
if self.data_source != "git":
self.desc += f":{self.data_source}"
if self.is_editable:
self.desc += "@editable"
PYPDFIUM_INFO = _version_pypdfium2()
"""
pypdfium2 helpers version.
It is suggesed to compare against *api_tag* and possibly also *beta* (see below).
Parameters:
version (str):
Joined tag and desc, forming the full version.
tag (str):
Version ciphers joined as str, including possible beta. Corresponds to the latest release tag at install time.
desc (str):
Non-cipher descriptors represented as str.
api_tag (tuple[int]):
Version ciphers joined as tuple, excluding possible beta.
major (int):
Major cipher.
minor (int):
Minor cipher.
patch (int):
Patch cipher.
beta (int | None):
Beta cipher, or None if not a beta version.
n_commits (int):
Number of commits after tag at install time. 0 for release.
hash (str | None):
Hash of head commit (prefixed with 'g') if n_commits > 0, None otherwise.
dirty (bool):
True if there were uncommitted changes at install time, False otherwise.
data_source (str):
Source of this version info. Possible values:\n
- ``git``: Parsed from git describe. Always used if available. Highest accuracy.
- ``given``: Pre-supplied version file (e.g. packaged with sdist, or else created by caller).
- ``record``: Parsed from autorelease record. Implies that possible changes after tag are unknown.
is_editable (bool | None):
True for editable install, False otherwise. None if unknown.\n
If True, the version info is the one captured at install time. An arbitrary number of forward or reverse changes may have happened since.
"""
# Freeze the base class after we have constructed the instance objects
def _frozen_setattr(self, name, value):
raise AttributeError(f"Version class is read-only - assignment '{name} = {value}' not allowed")
_version_class.__setattr__ = _frozen_setattr