Skip to content

Commit

Permalink
Inline utility methods
Browse files Browse the repository at this point in the history
  • Loading branch information
mara004 committed Oct 12, 2022
1 parent 613f10f commit c1b0261
Show file tree
Hide file tree
Showing 4 changed files with 63 additions and 71 deletions.
1 change: 1 addition & 0 deletions docs/devel/changelog_staging.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,4 @@
- Disruption: Two components of `PdfDocument` have been removed to clean up the code (without a major release, due to their insignificance):
- Removal of `update_rendering_input()`. Callers are expected to save and re-open the document on their if they wish that changes take effect with the multi-page renderer.
- The multipage renderer does not implicitly read byte buffers into memory anymore. Callers are expected to take an explicit decision by providing a different input in the first place.
- Docs: The changelog page now selectively includes an entry for the next release that may be shown on `latest` builds.
27 changes: 0 additions & 27 deletions src/pypdfium2/_helpers/_utils.py

This file was deleted.

76 changes: 38 additions & 38 deletions src/pypdfium2/_helpers/document.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,44 +35,6 @@
logger = logging.getLogger(__name__)


def _open_pdf(input_data, password=None):

if isinstance(password, str):
password = password.encode("utf-8")

ld_data = None
if isinstance(input_data, str):
pdf = pdfium.FPDF_LoadDocument(input_data.encode("utf-8"), password)
elif isinstance(input_data, bytes):
pdf = pdfium.FPDF_LoadMemDocument64(input_data, len(input_data), password)
ld_data = DataHolder(input_data)
elif is_input_buffer(input_data):
fileaccess, ld_data = get_fileaccess(input_data)
pdf = pdfium.FPDF_LoadCustomDocument(fileaccess, password)
else:
raise TypeError("Invalid input type '%s'" % type(input_data).__name__)

if pdfium.FPDF_GetPageCount(pdf) < 1:
err_code = pdfium.FPDF_GetLastError()
pdfium_msg = ErrorToStr.get(err_code, "Error code %s" % err_code)
raise PdfiumError("Loading the document failed (PDFium: %s)" % pdfium_msg)

return pdf, ld_data


class _writer_class:

def __init__(self, buffer):
self.buffer = buffer
if not callable( getattr(self.buffer, "write", None) ):
raise ValueError("Output buffer must implement the write() method.")

def __call__(self, _, data, size):
block = ctypes.cast(data, ctypes.POINTER(ctypes.c_ubyte * size))
self.buffer.write(block.contents)
return 1


class PdfDocument (BitmapConvAliases):
"""
Document helper class.
Expand Down Expand Up @@ -608,6 +570,44 @@ def render_to(
assert len(page_indices) == i


def _open_pdf(input_data, password=None):

if isinstance(password, str):
password = password.encode("utf-8")

ld_data = None
if isinstance(input_data, str):
pdf = pdfium.FPDF_LoadDocument(input_data.encode("utf-8"), password)
elif isinstance(input_data, bytes):
pdf = pdfium.FPDF_LoadMemDocument64(input_data, len(input_data), password)
ld_data = DataHolder(input_data)
elif is_input_buffer(input_data):
fileaccess, ld_data = get_fileaccess(input_data)
pdf = pdfium.FPDF_LoadCustomDocument(fileaccess, password)
else:
raise TypeError("Invalid input type '%s'" % type(input_data).__name__)

if pdfium.FPDF_GetPageCount(pdf) < 1:
err_code = pdfium.FPDF_GetLastError()
pdfium_msg = ErrorToStr.get(err_code, "Error code %s" % err_code)
raise PdfiumError("Loading the document failed (PDFium: %s)" % pdfium_msg)

return pdf, ld_data


class _writer_class:

def __init__(self, buffer):
self.buffer = buffer
if not callable( getattr(self.buffer, "write", None) ):
raise ValueError("Output buffer must implement the write() method.")

def __call__(self, _, data, size):
block = ctypes.cast(data, ctypes.POINTER(ctypes.c_ubyte * size))
self.buffer.write(block.contents)
return 1


class PdfXObject:
"""
XObject helper class.
Expand Down
30 changes: 24 additions & 6 deletions src/pypdfium2/_helpers/page.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,6 @@
import logging
from ctypes import c_float
import pypdfium2._pypdfium as pdfium
from pypdfium2._helpers._utils import (
validate_colours,
auto_bitmap_format,
)
from pypdfium2._helpers.misc import (
OptimiseMode,
PdfiumError,
Expand Down Expand Up @@ -488,10 +484,12 @@ def render_base(
Image size is given in pixels as a tuple of width and height.
"""

validate_colours(fill_colour, colour_scheme)
_validate_colours(fill_colour)
if colour_scheme is not None:
_validate_colours(*colour_scheme.colours.values())

if force_bitmap_format in (None, pdfium.FPDFBitmap_Unknown):
cl_pdfium = auto_bitmap_format(fill_colour, greyscale, prefer_bgrx)
cl_pdfium = _auto_bitmap_format(fill_colour, greyscale, prefer_bgrx)
else:
cl_pdfium = force_bitmap_format

Expand Down Expand Up @@ -589,6 +587,26 @@ def render_base(
return buffer, cl_string, (width, height)


def _validate_colours(*colours):
for col in colours:
if len(col) != 4:
raise ValueError("Colour must consist of exactly 4 values.")
if not all(0 <= c <= 255 for c in col):
raise ValueError("Colour value exceeds boundaries.")


def _auto_bitmap_format(fill_colour, greyscale, prefer_bgrx):
# no need to take alpha values of colour_scheme into account (drawings are additive)
if (fill_colour[3] < 255):
return pdfium.FPDFBitmap_BGRA
elif greyscale:
return pdfium.FPDFBitmap_Gray
elif prefer_bgrx:
return pdfium.FPDFBitmap_BGRx
else:
return pdfium.FPDFBitmap_BGR


class ColourScheme:
"""
Rendering colour scheme.
Expand Down

0 comments on commit c1b0261

Please sign in to comment.