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,2 @@
# SPDX-FileCopyrightText: 2026 geisserml <geisserml@gmail.com>
# SPDX-License-Identifier: Apache-2.0 OR BSD-3-Clause
@@ -0,0 +1,117 @@
# SPDX-FileCopyrightText: 2026 geisserml <geisserml@gmail.com>
# SPDX-License-Identifier: Apache-2.0 OR BSD-3-Clause
# Important: Do not import from the core `pypdfium2` module here, since it initializes the library, which shall be deferred until after setup_logging().
# Other modules can be imported as long as they don't import from `pypdfium2` in turn.
import sys
import argparse
from os.path import basename
from importlib import import_module
from pypdfium2_cli._setup import setup_logging
from pypdfium2_cfg.stl import (
cached_property,
keydefaultdict,
ArgparseCompatParser,
)
ModuleLoader = keydefaultdict(import_module)
class _LocalLazyClass:
@cached_property
def version_str(self):
from pypdfium2.version import PYPDFIUM_INFO, PDFIUM_INFO
from pypdfium2_raw.bindings import _libs
return f"pypdfium2 {PYPDFIUM_INFO}\npdfium {PDFIUM_INFO} at {_libs['pdfium']._name}"
LocalLazy = _LocalLazyClass()
SubCommands = {
"arrange": "Rearrange/merge documents",
"attachments": "List/extract/edit embedded files",
"extract-images": "Extract images",
"extract-text": "Extract text",
"imgtopdf": "Convert images to PDF",
"pageobjects": "Print info on pageobjects",
"pdfinfo": "Print info on document and pages",
"fonts": "List a document's fonts",
"default-fonts": "Dump info about default fonts",
"render": "Rasterize pages",
"tile": "Tile pages (N-up)",
"toc": "Print table of contents",
}
def get_parser(argv):
main_parser = ArgparseCompatParser(
prog = "pypdfium2",
formatter_class = argparse.RawTextHelpFormatter,
description = """\
pypdfium2 is a Python binding to PDFium, a PDF processing library.
This is the command-line interface. Invoke as `pypdfium2` or `%(py_exe)s -m pypdfium2_cli`.
pypdfium2's CLI mainly serves testing purposes, similar to pdfium_test upstream.
It is not meant as a feature-complete PDF toolkit for end users.
There are no API stability promises; backward incompatible changes may be made.
Environment variables:
- PYPDFIUM_LOGLEVEL {debug,info,warning,error,critical} = debug
Controls the logging level.
- DEBUG_AUTOCLOSE {-1,0,1} = 0
Whether to print info about (auto-)closing of PDFium objects.
Defaults to 0, which means warnings only. 1 enables debugging. -1 silences even warnings.
- DEBUG_UNSUPPORTED {0,1} = 1
Whether to enable or disable the unsupported feature handler.
- DEBUG_SYSFONTS {0,1} = 0
Whether to install a sysfont listener.\
""" % dict(py_exe=basename(sys.executable)),
)
main_parser.add_argument(
"-v", "--version",
action = "version",
version = LocalLazy.version_str,
)
subparsers = main_parser.add_subparsers(dest="subcommand")
mod = None
sc_name = (argv and argv[0]) or None
other_scs = SubCommands.copy()
if sc_name in SubCommands:
del other_scs[sc_name]
mod = ModuleLoader[f"pypdfium2_cli.{sc_name.replace('-', '_')}"]
help = SubCommands[sc_name]
desc = getattr(mod, "PARSER_DESC", None)
desc = (help + "\n\n" + desc) if desc else help
subparser = subparsers.add_parser(
sc_name, help=help, description=desc,
formatter_class=argparse.RawTextHelpFormatter,
)
mod.attach(subparser)
for name, help in other_scs.items():
subparsers.add_parser(name, help=help)
return main_parser, mod
def api_main(argv=sys.argv[1:]):
parser, mod = get_parser(argv)
args = parser.parse_args(argv)
if not args.subcommand:
parser.print_help()
return
mod.main(args)
def cli_main():
setup_logging()
api_main()
if __name__ == "__main__":
cli_main()
@@ -0,0 +1,116 @@
# SPDX-FileCopyrightText: 2026 geisserml <geisserml@gmail.com>
# SPDX-License-Identifier: Apache-2.0 OR BSD-3-Clause
from pathlib import Path
import pypdfium2 as pdfium
def parse_numtext(numtext):
if not numtext:
return None
indices = []
for num_or_range in numtext.split(","):
if "-" in num_or_range:
start, end = num_or_range.split("-")
start = int(start) - 1
end = int(end) - 1
if start < end:
indices.extend( [i for i in range(start, end+1)] )
else:
indices.extend( [i for i in range(start, end-1, -1)] )
else:
indices.append(int(num_or_range) - 1)
return indices
class _Range:
def __init__(self, start, stop):
self.start = start
self.stop = stop
def __repr__(self):
return f"{self.start}-{self.stop}"
def pagenums_ranger(pagenums):
# provided pagenums are 1-based. for 0-based, prev would have to be -2
prev = -1
range_start = None
out = []
for n in pagenums:
if prev+1 == n:
if not range_start:
range_start = out.pop() # prev
else:
if range_start:
out.append(_Range(range_start, prev))
range_start = None
out.append(n)
prev = n
if range_start:
out.append(_Range(range_start, prev))
return out
def round_list(lst, n_digits):
return type(lst)(round(v, n_digits) for v in lst)
def add_input(parser, pages=True):
# TODO add option to open file with buffer/bytes strategy
parser.add_argument(
"input",
type = Path,
help = "Input PDF document",
)
parser.add_argument(
"--password",
help = "A password to unlock the PDF, if encrypted",
)
if pages:
parser.add_argument(
"--pages",
default = None,
type = parse_numtext,
help = "Page numbers and ranges to include",
)
def add_n_digits(parser):
parser.add_argument(
"--n-digits",
type = int,
default = 4,
help = "Number of digits to which coordinates/sizes shall be rounded",
)
def get_input(args, init_forms=False, **kwargs):
pdf = pdfium.PdfDocument(args.input, password=args.password, **kwargs)
if init_forms:
pdf.init_forms()
if "pages" in args and not args.pages:
args.pages = [i for i in range(len(pdf))]
# TODO else validate pages, as seen in ./render.py
return pdf
# dummy more_itertools.peekable().__bool__ alternative
def _postpeek_generator(value, iterator):
yield value; yield from iterator
def iterator_hasvalue(iterator):
try:
first_value = next(iterator)
except StopIteration:
return False, None
else:
return True, _postpeek_generator(first_value, iterator)
@@ -0,0 +1,72 @@
# SPDX-FileCopyrightText: 2026 geisserml <geisserml@gmail.com>
# SPDX-License-Identifier: Apache-2.0 OR BSD-3-Clause
import os
import logging
import warnings
_LogLevelMap = {
'debug': logging.DEBUG,
'info': logging.INFO,
'warning': logging.WARNING,
'error': logging.ERROR,
'critical': logging.CRITICAL,
}
_DebugAutocloseMap = {
-1: logging.CRITICAL,
0: logging.WARNING,
1: logging.DEBUG,
}
def _readbool(string):
return bool(int(string))
def _do_cast(cast, value, exc_type, choices=None):
try:
return cast(value)
except exc_type as e:
if choices:
raise ValueError(f"{value!r} not in {tuple(choices)}") from e
else:
raise ValueError(f"{value!r} cannot be casted via {cast.__name__}") from e
def _env(key, default, cast=None, map=None):
value = os.environ.get(key)
if value is None:
return default
if cast:
value = _do_cast(cast, value, ValueError)
if map:
value = _do_cast(map.__getitem__, value, KeyError, choices=map)
return value
def setup_logging():
# Read these settings from environment variables
# (Could also consider using CLI flags, but this seemed easiest for now ...)
loglevel = _env("PYPDFIUM_LOGLEVEL", logging.DEBUG, cast=str.lower, map=_LogLevelMap)
debug_autoclose = _env("DEBUG_AUTOCLOSE", logging.WARNING, cast=int, map=_DebugAutocloseMap)
debug_unsupported = _env("DEBUG_UNSUPPORTED", 1, cast=_readbool)
debug_sysfonts = _env("DEBUG_SYSFONTS", 0, cast=_readbool)
loggers = [logging.getLogger("pypdfium2"+m) for m in ("", "_raw", "_cfg", "_cli")]
streamhandler = logging.StreamHandler()
for l in loggers:
l.addHandler(streamhandler)
l.setLevel(loglevel)
warnings.simplefilter("always")
# cli_logger = logging.getLogger("pypdfium2_cli")
# cli_logger.debug("Just set up logging")
import pypdfium2_cfg
pypdfium2_cfg.DEBUG_AUTOCLOSE.value = debug_autoclose
import pypdfium2 as pdfium
from pypdfium2_cli._sysfonts import PdfSysfontListener
if debug_unsupported:
pdfium.PdfUnspHandler().setup()
if debug_sysfonts:
PdfSysfontListener().setup()
@@ -0,0 +1,70 @@
# SPDX-FileCopyrightText: 2026 geisserml <geisserml@gmail.com>
# SPDX-License-Identifier: Apache-2.0 OR BSD-3-Clause
import enum
import ctypes
import logging
import pypdfium2 as pdfium
import pypdfium2.raw as pdfium_c
import pypdfium2.internal as pdfium_i
logger = logging.getLogger("pypdfium2_cli")
class FontPitchFamilyFlags (enum.Flag):
"Map PDFium font pitch and family flags to python :class:`enum.Flag`."
FIXEDPITCH = pdfium_c.FXFONT_FF_FIXEDPITCH
ROMAN = pdfium_c.FXFONT_FF_ROMAN
SCRIPT = pdfium_c.FXFONT_FF_SCRIPT
class PdfSysfontListener (pdfium.PdfSysfontBase):
def __init__(self, default=None):
logger.debug("Building sysfontinfo instance...")
super().__init__(default)
logger.debug(f"fontinfo default interface version is {self.version}")
def setup(self, *args, **kwargs):
logger.debug("Installing sysfontinfo...")
return super().setup(*args, **kwargs)
def MapFont(self, _, weight, bItalic, charset, pitch_family, face, _ignored):
face_bstr = ctypes.cast(face, ctypes.c_char_p).value
logger.debug(f"fontinfo::MapFont:in (weight={weight}, bItalic={bool(bItalic)}, charset={pdfium_i.CharsetToStr.get(charset)!r}, pitch_family={FontPitchFamilyFlags(pitch_family).name!r}, face={face_bstr!r})")
out = self.default.MapFont(self.default, weight, bItalic, charset, pitch_family, face, _ignored)
# For internal substitution, check the family names in `pypdfium2 fonts` CLI output.
# If you see names like "Chrom Sans OTF" or "Chrom Serif OTF" then you probably got internal substitution.
vis_out = out or f"{out} # unknown/internal"
logger.debug(f"fontinfo::MapFont:out {vis_out}")
return out
def GetFont(self, _, face):
face_bstr = ctypes.cast(face, ctypes.c_char_p).value
logger.debug(f"fontinfo::GetFont {face_bstr, }")
return self.default.GetFont(self.default, face)
def GetFaceName(self, _, hFont, buffer, buf_size):
logger.debug(f"fontinfo::GetFaceName {hFont, buffer, buf_size}")
out = self.default.GetFaceName(self.default, hFont, buffer, buf_size)
if buf_size > 0:
logger.debug(f"-> {pdfium_i.get_buffer(buffer, buf_size-1).raw}")
return out
def EnumFonts(self, _, pMapper):
logger.debug(f"fontinfo::EnumFonts {pMapper, }")
return self.default.EnumFonts(self.default, pMapper)
def GetFontData(self, _, hFont, table, buffer, buf_size):
logger.debug(f"fontinfo::GetFontData {hFont, table, buffer, buf_size}")
return self.default.GetFontData(self.default, hFont, table, buffer, buf_size)
def GetFontCharset(self, _, hFont):
# XXX haven't yet seen a sample that triggers GetFontCharset
logger.debug(f"fontinfo::GetFontCharset {hFont, }")
out = self.default.GetFontCharset(self.default, hFont)
logger.debug(f"-> charset: {pdfium_i.CharsetToStr.get(out)!r}")
return out
def DeleteFont(self, _, hFont):
logger.debug(f"fontinfo::DeleteFont {hFont, }")
return self.default.DeleteFont(self.default, hFont)
@@ -0,0 +1,48 @@
# SPDX-FileCopyrightText: 2026 geisserml <geisserml@gmail.com>
# SPDX-License-Identifier: Apache-2.0 OR BSD-3-Clause
import pypdfium2 as pdfium
from pypdfium2_cli._parsers import parse_numtext
def attach(parser):
parser.add_argument(
"inputs",
nargs = "+",
help = "Sequence of PDF files.",
)
parser.add_argument(
"--pages",
nargs = "+",
default = [],
help = "Sequence of page texts, definig the pages to include from each PDF. Use '_' as placeholder for all pages."
)
parser.add_argument(
"--passwords",
nargs = "+",
default = [],
help = "Passwords to unlock encrypted PDFs. Any placeholder may be used for non-encrypted documents.",
)
parser.add_argument(
"--output", "-o",
required = True,
help = "Target path for the output document",
)
def main(args):
args.pages = [None if p == "_" else parse_numtext(p) for p in args.pages]
for _ in range(len(args.inputs) - len(args.pages)):
args.pages.append(None)
for _ in range(len(args.inputs) - len(args.passwords)):
args.passwords.append(None)
dest_pdf = pdfium.PdfDocument.new()
for in_path, pages, password in zip(args.inputs, args.pages, args.passwords):
with pdfium.PdfDocument(in_path, password=password) as src_pdf:
dest_pdf.import_pages(src_pdf, pages=pages)
dest_pdf.save(args.output)
@@ -0,0 +1,102 @@
# SPDX-FileCopyrightText: 2026 geisserml <geisserml@gmail.com>
# SPDX-License-Identifier: Apache-2.0 OR BSD-3-Clause
from pathlib import Path
from pypdfium2_cli._parsers import (
add_input, get_input,
parse_numtext,
)
ACTION_LIST = "list"
ACTION_EXTRACT = "extract"
ACTION_EDIT = "edit"
# TODO would like to add action="extend", but conflicts with default being a tuple, and beware: it cannot be made a list here (perilous!)
NARGS_PLUS = dict(nargs="+", default=())
def attach(parser): # hook
add_input(parser, pages=False)
subparsers = parser.add_subparsers(dest="action") # required=True # >= 3.7
subparsers.add_parser(ACTION_LIST)
parser_extract = subparsers.add_parser(ACTION_EXTRACT)
parser_extract.add_argument(
"--nums",
type = parse_numtext,
)
parser_extract.add_argument(
"--output-dir", "-o",
type = Path,
required = True,
)
parser_edit = subparsers.add_parser(ACTION_EDIT)
parser_edit.add_argument(
"--set-desc",
**NARGS_PLUS,
help = f"Syntax: n=desc, where n is the attachment number, and desc the new description to be set. Example: '1=Hello world'. Use `pypdfium2 attachments list` to determine the attachment numbers.",
)
parser_edit.add_argument(
"--del-nums",
type = parse_numtext,
default = (),
)
# TODO need a way to set the name and description of new attachments
parser_edit.add_argument(
"--add-files",
**NARGS_PLUS,
metavar = "F",
type = Path,
)
parser_edit.add_argument(
"--output", "-o",
type = Path,
required = True,
)
def main(args):
pdf = get_input(args)
n_attachments = pdf.count_attachments()
if args.action == ACTION_LIST:
for i in range(n_attachments):
atm = pdf.get_attachment(i)
desc = atm.get_desc()
desc_str = f": {desc!r}" if desc else ""
print(f"[{i+1}] {atm.get_name()} ({atm.get_subtype()})" + desc_str)
elif args.action == ACTION_EXTRACT:
if not args.nums:
args.nums = range(n_attachments)
n_digits = len(str( max(args.nums) + 1 ))
for i in args.nums:
atm = pdf.get_attachment(i)
name = atm.get_name()
out_path = args.output_dir / ("%0*d_%s" % (n_digits, i+1, name))
out_path.write_bytes( atm.get_data() )
elif args.action == ACTION_EDIT:
for spec in args.set_desc:
num_str, desc = spec.split("=", maxsplit=1)
i = int(num_str) - 1
atm = pdf.get_attachment(i)
atm.set_desc(desc)
for i in sorted(args.del_nums, reverse=True):
pdf.del_attachment(i)
for fp in args.add_files:
atm = pdf.new_attachment(fp.name)
atm.set_data( fp.read_bytes() )
pdf.save(args.output)
else:
raise ValueError("No valid subcommand provided")
@@ -0,0 +1,47 @@
# SPDX-FileCopyrightText: 2026 geisserml <geisserml@gmail.com>
# SPDX-License-Identifier: Apache-2.0 OR BSD-3-Clause
import ctypes
import pypdfium2 as pdfium
import pypdfium2.internal as pdfium_i
from pypdfium2_cli.fonts import _show_table
def attach(parser):
pass
def _iterate_standard_fonts():
dummy_pdf = pdfium.PdfDocument.new()
for fontname in pdfium.PdfFont.STANDARD_FONTS:
fontobj = pdfium.PdfFont.load_standard(dummy_pdf, fontname)
yield fontobj.get_base_name(), fontobj.get_family_name()
def _map_default_fonts(sfh, ttfmap):
for charset, fontname in ttfmap.items():
font_handle = sfh.MapFont(None, weight=0, bItalic=False, charset=charset, pitch_family=0, face=fontname, _ignored=ctypes.byref(ctypes.c_int(0)))
if not font_handle:
continue
buf_size = sfh.GetFaceName(None, font_handle, None, 0)
if not (buf_size > 0):
continue
buf = (ctypes.c_char * buf_size)()
buf_ptr = ctypes.cast(buf, ctypes.POINTER(ctypes.c_char))
sfh.GetFaceName(None, font_handle, buf_ptr, buf_size)
def main(args):
print("# Standard fonts")
_show_table(("Base name", "Family name"), _iterate_standard_fonts(), None)
print("\n# Default TTF map")
print(f"All Charsets: {sorted(pdfium_i.CharsetToStr.values())}")
ttfmap = pdfium.PdfDefaultTTFMap.value
missing = set(pdfium_i.CharsetToStr.keys()).difference(ttfmap.keys())
missing = [pdfium_i.CharsetToStr[k] for k in missing]
print(f"Absent from map: {missing}")
str_ttfmap = {pdfium_i.CharsetToStr[k]: v for k, v in ttfmap.items()}
_show_table(("Charset", "Default font"), sorted(str_ttfmap.items()))
# requires initial EnumFonts triggered through standard fonts above
sfh = pdfium.PdfSysfontBase.SINGLETON
if sfh:
_map_default_fonts(sfh, ttfmap)
@@ -0,0 +1,87 @@
# SPDX-FileCopyrightText: 2026 geisserml <geisserml@gmail.com>
# SPDX-License-Identifier: Apache-2.0 OR BSD-3-Clause
# TODO test-cover use_bitmap, format and render
import logging
import traceback
from pathlib import Path
import pypdfium2 as pdfium
import pypdfium2.raw as pdfium_c
from pypdfium2_cli._parsers import add_input, get_input
from pypdfium2_cfg.stl import BooleanOptionalAction
logger = logging.getLogger(__name__)
def attach(parser):
add_input(parser, pages=True)
parser.add_argument(
"--output-dir", "-o",
required = True,
type = Path,
help = "Output directory to take the extracted images",
)
parser.add_argument(
"--max-depth",
type = int,
default = 15,
help = "Maximum recursion depth to consider when looking for pageobjects.",
)
parser.add_argument(
"--use-bitmap",
action = "store_true",
help = "Enforce the use of bitmaps rather than attempting a smart extraction of the image.",
)
parser.add_argument(
"--format",
help = "Image format to use when saving bitmaps. (Fallback if doing smart extraction.)",
)
parser.add_argument(
"--render",
action = "store_true",
help = "When --use-bitmap is given, whether to get rendered bitmaps, taking masks and transform matrices into account.",
)
parser.add_argument(
"--scale-to-original",
action = BooleanOptionalAction,
default = True,
help = "When --use-bitmap --render is given, whether to scale the image so it is rendered at its native resolution, or close to that. This should improve output quality. The default is True, but you may opt out.",
)
def main(args):
if not args.output_dir.is_dir():
raise NotADirectoryError(args.output_dir)
if args.use_bitmap and not args.format:
args.format = "png"
pdf = get_input(args)
n_pdigits = len(str( max(args.pages)+1 ))
for i in args.pages:
page = pdf[i]
images = page.get_objects(
filter = (pdfium_c.FPDF_PAGEOBJ_IMAGE, ),
max_depth = args.max_depth,
)
# not perfectly memory efficient, but we need image count for digit formatting
images = list(images)
n_idigits = len(str( len(images) ))
for j, image in enumerate(images):
tag = "%0*d_%0*d" % (n_pdigits, i+1, n_idigits, j+1)
prefix = args.output_dir / f"{args.input.stem}_{tag}"
# logger.debug("\n"+tag)
try:
if args.use_bitmap:
pil_image = image.get_bitmap(render=args.render, scale_to_original=args.scale_to_original).to_pil()
pil_image.save(f"{prefix}.{args.format}")
else:
image.extract(prefix, fb_format=args.format)
except pdfium.PdfiumError:
traceback.print_exc()
image.close()
@@ -0,0 +1,45 @@
# SPDX-FileCopyrightText: 2026 geisserml <geisserml@gmail.com>
# SPDX-License-Identifier: Apache-2.0 OR BSD-3-Clause
from pypdfium2_cli._parsers import add_input, get_input
EXTRACT_RANGE = "range"
EXTRACT_BOUNDED = "bounded"
# __main__.py hook
PARSER_DESC = """\
Note that PDFium outputs 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, run e.g. `dos2unix` on the output, or use the Python API.\
"""
def attach(parser):
add_input(parser, pages=True)
parser.add_argument(
"--strategy",
default = EXTRACT_RANGE,
choices = (EXTRACT_RANGE, EXTRACT_BOUNDED),
help = "PDFium text extraction strategy (range, bounded).",
)
def main(args):
pdf = get_input(args)
sep = ""
for i in args.pages:
page = pdf[i]
textpage = page.get_textpage()
# TODO let caller pass in possible range/boundary parameters
if args.strategy == EXTRACT_RANGE:
text = textpage.get_text_range()
elif args.strategy == EXTRACT_BOUNDED:
text = textpage.get_text_bounded()
else:
assert False
print(sep + f"# Page {i+1}\n" + text)
sep = "\n"
@@ -0,0 +1,77 @@
# SPDX-FileCopyrightText: 2026 geisserml <geisserml@gmail.com>
# SPDX-License-Identifier: Apache-2.0 OR BSD-3-Clause
import logging
from ctypes import addressof
from collections import namedtuple
from importlib.util import find_spec
import pypdfium2.raw as pdfium_c
from pypdfium2._lazy import Lazy
from pypdfium2_cli._parsers import (
add_input,
get_input,
pagenums_ranger,
)
logger = logging.getLogger("pypdfium2_cli")
HAVE_TABULATE = bool(find_spec("tabulate"))
FontHolder = namedtuple("FontHolder", ("obj", "pages"))
PARSER_DESC = """\
Font objects are compared by memory address, so the same font name may occur multiple times
in different configurations (e.g. differing weights, or even hidden differences like /Subtype).
This is intentional. Nameless fonts may also occur.\
"""
def attach(parser):
add_input(parser, pages=True)
def _iterate_fonts(all_fonts):
for fontholder in all_fonts.values():
fontobj = fontholder.obj
base_name = fontobj.get_base_name()
embedded = "yes" if fontobj.is_embedded else "no"
pages_str = ", ".join(str(p) for p in pagenums_ranger(sorted(fontholder.pages)))
yield base_name, fontobj.get_family_name(), fontobj.get_weight(), embedded, pages_str
if HAVE_TABULATE:
def _show_table(headers, table_iter, maxcolwidths=None):
table_list = list(table_iter)
if not table_list:
return
print(Lazy.tabulate(table_list, headers=headers, stralign="left", tablefmt="pretty", maxcolwidths=maxcolwidths))
else:
logger.info("You may want to install `tabulate` for prettier output.")
def _show_table(headers, table_iter, maxcolwidths=None):
print(headers)
for entry in table_iter:
print(entry)
def main(args):
pdf = get_input(args)
# depending on how long the PDF is, this is slow
# cf. https://issues.chromium.org/issues/460743388#comment5
# TODO use https://pdfium-review.googlesource.com/c/pdfium/+/138550 once it is available
logger.debug("Gathering fonts from pages...")
all_fonts = {}
for i in args.pages:
page = pdf[i]
for textobj in page.get_objects(filter=(pdfium_c.FPDF_PAGEOBJ_TEXT,)):
fontobj = textobj.get_font()
addr = addressof(fontobj.raw.contents)
if addr in all_fonts:
fontholder = all_fonts[addr]
else:
fontholder = FontHolder(fontobj, set())
all_fonts[addr] = fontholder
fontholder.pages.add(i+1)
headers = ("Base name", "Family name", "Weight", "Emb", "Pages")
maxcolwidths = [30, 30, None, None, 80]
fonts_iter = _iterate_fonts(all_fonts)
_show_table(headers, fonts_iter, maxcolwidths)
@@ -0,0 +1,62 @@
# SPDX-FileCopyrightText: 2026 geisserml <geisserml@gmail.com>
# SPDX-License-Identifier: Apache-2.0 OR BSD-3-Clause
# TODO test-cover converting non-jpeg format
from pathlib import Path
import pypdfium2 as pdfium
from pypdfium2._lazy import Lazy
def attach(parser):
parser.add_argument(
"images",
nargs = "+",
help = "Input images",
type = Path,
)
parser.add_argument(
"--output", "-o",
required = True,
type = Path,
help = "Target path for the new PDF"
)
parser.add_argument(
"--inline",
action = "store_true",
help = "If JPEG, whether to use PDFium's inline loading function."
)
def main(args):
# Rudimentary image to PDF conversion (testing / proof of concept)
# Due to limitations in PDFium's public API, this function may be inefficient/lossy for non-JPEG input.
# The technically best available open-source tool for image to PDF conversion is probably img2pdf (although its code style can be regarded as displeasing).
pdf = pdfium.PdfDocument.new()
for fp in args.images:
image_obj = pdfium.PdfImage.new(pdf)
# Simple check whether the file is a JPEG image - a better implementation could use mimetypes, python-magic, or PIL
if fp.suffix.lower() in (".jpg", ".jpeg"):
image_obj.load_jpeg(fp, inline=args.inline)
else:
pil_image = Lazy.PIL_Image.open(fp)
bitmap = pdfium.PdfBitmap.from_pil(pil_image)
pil_image.close()
image_obj.set_bitmap(bitmap)
bitmap.close()
w, h = image_obj.get_px_size()
image_obj.set_matrix( pdfium.PdfMatrix().scale(w, h) )
page = pdf.new_page(w, h)
page.insert_obj(image_obj)
page.gen_content()
image_obj.close() # no-op
page.close()
pdf.save(args.output)
pdf.close()
@@ -0,0 +1,123 @@
# SPDX-FileCopyrightText: 2026 geisserml <geisserml@gmail.com>
# SPDX-License-Identifier: Apache-2.0 OR BSD-3-Clause
# TODO test-confirm filter and info params
import pypdfium2 as pdfium
import pypdfium2.internal as pdfium_i
from pypdfium2_cli._parsers import (
add_input,
add_n_digits,
get_input,
round_list,
iterator_hasvalue,
)
PARAM_POS = "pos"
PARAM_IMGINFO = "imginfo"
PARAM_TEXT = "text"
INFO_PARAMS = (PARAM_POS, PARAM_IMGINFO, PARAM_TEXT)
def attach(parser):
add_input(parser, pages=True)
add_n_digits(parser)
# TODO think out strategy for choices (see https://github.com/python/cpython/issues/69247)
obj_types = list( pdfium_i.ObjectTypeToConst.keys() )
parser.add_argument(
"--filter",
nargs = "+",
metavar = "T",
choices = obj_types,
help = f"Object types to include. Choices: {obj_types}",
)
parser.add_argument(
"--max-depth",
type = int,
default = 2,
help = "Maximum recursion depth to consider when descending into Form XObjects.",
)
parser.add_argument(
"--info",
nargs = "+",
type = str.lower,
choices = INFO_PARAMS,
default = INFO_PARAMS,
help = "Object details to show.",
)
def print_img_metadata(m, n_digits, pad=""):
members = dict( # ordered
width = m.width,
height = m.height,
horizontal_dpi = round(m.horizontal_dpi, n_digits),
vertical_dpi = round(m.vertical_dpi, n_digits),
bits_per_pixel = m.bits_per_pixel,
colorspace = pdfium_i.ColorspaceToStr.get(m.colorspace),
)
if m.marked_content_id != -1:
members["marked_content_id"] = m.marked_content_id
for key, value in members.items():
print(pad + f"{key}: {value}")
def main(args):
pdf = get_input(args)
# if no filter is given, leave it at None (make a difference in case of unhandled object types)
if args.filter:
args.filter = [pdfium_i.ObjectTypeToConst[t] for t in args.filter]
show_pos = PARAM_POS in args.info
show_imginfo = PARAM_IMGINFO in args.info
show_text = PARAM_TEXT in args.info
assert any((show_pos, show_imginfo, show_text))
total_count = 0
for i in args.pages:
page = pdf[i]
textpage = page.get_textpage() if show_text else None
hasvalue, obj_searcher = iterator_hasvalue( page.get_objects(args.filter, max_depth=args.max_depth, textpage=textpage) )
if not hasvalue: continue
print(f"# Page {i+1}")
count = 0
for obj in obj_searcher:
pad_0 = " " * obj.level
pad_1 = pad_0 + " "
print(pad_0 + pdfium_i.ObjectTypeToStr.get(obj.type))
if show_pos:
bounds = round_list(obj.get_bounds(), args.n_digits)
print(pad_1 + f"Bounding Box: {bounds}")
if isinstance(obj, (pdfium.PdfImage, pdfium.PdfTextObj)):
quad_bounds = obj.get_quad_points()
print(pad_1 + f"Quad Points: {[round_list(p, args.n_digits) for p in quad_bounds]}")
if show_imginfo and isinstance(obj, pdfium.PdfImage):
print(pad_1 + f"Filters: {obj.get_filters()}")
metadata = obj.get_metadata()
assert (metadata.width, metadata.height) == obj.get_px_size()
print_img_metadata(metadata, args.n_digits, pad=pad_1)
elif show_text and isinstance(obj, pdfium.PdfTextObj):
print(pad_1 + repr(obj.extract()))
count += 1
if count > 0:
print(f"-> Count: {count}\n")
total_count += count
if total_count > 0:
print(f"-> Total count: {total_count}")
@@ -0,0 +1,58 @@
# SPDX-FileCopyrightText: 2026 geisserml <geisserml@gmail.com>
# SPDX-License-Identifier: Apache-2.0 OR BSD-3-Clause
import pypdfium2.raw as pdfium_c
import pypdfium2.internal as pdfium_i
from pypdfium2_cli._parsers import (
add_input,
add_n_digits,
get_input,
round_list,
)
def attach(parser):
add_input(parser)
add_n_digits(parser)
def main(args):
pdf = get_input(args)
print(f"Page Count: {len(pdf)}")
print(f"PDF Version: {pdf.get_version() / 10}")
id_permanent = pdf.get_identifier(pdfium_c.FILEIDTYPE_PERMANENT)
id_changing = pdf.get_identifier(pdfium_c.FILEIDTYPE_CHANGING)
print(f"ID (permanent): {id_permanent}")
print(f"ID (changing): {id_changing}")
print(f"ID match? - {id_permanent == id_changing}")
print(f"Tagged? - {pdf.is_tagged()}")
pagemode = pdf.get_pagemode()
if pagemode != pdfium_c.PAGEMODE_USENONE:
print(f"Page Mode: {pdfium_i.PageModeToStr.get(pagemode)}")
formtype = pdf.get_formtype()
if formtype != pdfium_c.FORMTYPE_NONE:
print(f"Form Type: {pdfium_i.FormTypeToStr.get(formtype)}")
metadata = pdf.get_metadata_dict(skip_empty=True)
if len(metadata) > 0:
print("Metadata:")
for key, value in metadata.items():
print(f" {key}: {value}")
for i in args.pages:
print(f"\n# Page {i+1}")
page = pdf[i]
print(f"Size: {round_list(page.get_size(), args.n_digits)}")
print(f"Rotation: {page.get_rotation()}")
print(f"Bounding Box: {round_list(page.get_bbox(), args.n_digits)}")
for box_name in ("media", "crop", "bleed", "trim", "art"):
box = getattr(page, f"get_{box_name.lower()}box")(fallback_ok=False)
if box:
print(f"{box_name.capitalize()}Box: {round_list(box, args.n_digits)}")
@@ -0,0 +1,524 @@
# SPDX-FileCopyrightText: 2026 geisserml <geisserml@gmail.com>
# SPDX-License-Identifier: Apache-2.0 OR BSD-3-Clause
import os
import math
import types
import logging
import colorsys
import functools
from pathlib import Path
import multiprocessing as mp
import concurrent.futures as ft
from importlib.util import find_spec
import pypdfium2 as pdfium
import pypdfium2.internal as pdfium_i
import pypdfium2.raw as pdfium_c
from pypdfium2_cli._setup import setup_logging
from pypdfium2_cli._parsers import (
add_input, get_input,
iterator_hasvalue,
)
from pypdfium2_cfg.stl import BooleanOptionalAction
have_pil = find_spec("PIL") is not None
have_cv2 = find_spec("cv2") is not None
logger = logging.getLogger(__name__)
def _bitmap_wrapper_foreign_simple(width, height, format, *args, **kwargs):
if format == pdfium_c.FPDFBitmap_BGRx:
use_alpha = False
elif format == pdfium_c.FPDFBitmap_BGRA:
use_alpha = True
else:
raise RuntimeError(f"Cannot create foreign_simple bitmap with bitmap type {pdfium_i.BitmapTypeToStr[format]}.")
return pdfium.PdfBitmap.new_foreign_simple(width, height, use_alpha, *args, **kwargs)
BitmapMakers = dict(
native = pdfium.PdfBitmap.new_native,
foreign = pdfium.PdfBitmap.new_foreign,
foreign_packed = functools.partial(pdfium.PdfBitmap.new_foreign, force_packed=True),
foreign_simple = _bitmap_wrapper_foreign_simple,
)
ColorSchemeFields = ("path_fill", "path_stroke", "text_fill", "text_stroke")
ColorOpts = dict(metavar="C", nargs=4, type=int)
SampleTheme = dict(
# TODO improve colors - currently it's just some random colors to distinguish the different drawings
path_fill = (170, 100, 0, 255), # dark orange
path_stroke = (0, 150, 255, 255), # sky blue
text_fill = (255, 255, 255, 255), # white
text_stroke = (150, 255, 0, 255), # green
)
def attach(parser):
add_input(parser, pages=True)
parser.add_argument(
"--output", "-o",
type = lambda p: Path(p).expanduser().resolve(),
required = True,
help = "Output directory where the serially numbered images shall be placed.",
)
parser.add_argument(
"--prefix",
help = "Custom prefix for the images. Defaults to the input filename's stem.",
)
parser.add_argument(
"--format", "-f",
type = str.lower,
help = "The image format to use (default: conditional).",
)
engines_map = {"pil": PILEngine, "numpy+pil": NumpyPILEngine, "numpy+cv2": NumpyCV2Engine}
parser.add_argument(
"--engine",
dest = "engine_cls",
type = lambda k: engines_map[k.lower()],
help = f"The saver engine to use {tuple(engines_map.keys())}",
)
parser.add_argument(
"--scale",
default = 1,
type = float,
help = "Define the resolution of the output images. By default, one PDF point (1/72in) is rendered to 1x1 pixel. This factor scales the number of pixels that represent one point.",
)
parser.add_argument(
"--rotation",
default = 0,
type = int,
choices = (0, 90, 180, 270),
help = "Rotate pages by 90, 180 or 270 degrees.",
)
parser.add_argument(
"--fill-color",
help = "Color the bitmap will be filled with before rendering. Shall be given in RGBA format as a sequence of integers ranging from 0 to 255. Defaults to white.",
**ColorOpts,
)
parser.add_argument(
"--optimize-mode",
choices = ("lcd", "print"),
help = "The rendering optimisation mode. None if not given.",
)
parser.add_argument(
"--crop",
metavar="C", nargs=4, type=float,
default = (0, 0, 0, 0),
help = "Amount to crop from (left, bottom, right, top).",
)
parser.add_argument(
"--draw-annots",
action = BooleanOptionalAction,
default = True,
help = "Whether annotations may be shown (default: true).",
)
parser.add_argument(
"--draw-forms",
action = BooleanOptionalAction,
default = True,
help = "Whether forms may be shown (default: true).",
)
parser.add_argument(
"--no-antialias",
nargs = "+",
default = [],
choices = ("text", "image", "path"),
type = str.lower,
help = "Item types that shall not be smoothed.",
)
parser.add_argument(
"--force-halftone",
action = "store_true",
help = "Always use halftone for image stretching.",
)
bitmap = parser.add_argument_group(
title = "Bitmap options",
description = "Bitmap config, including pixel format.",
)
bitmap.add_argument(
"--bitmap-maker",
choices = BitmapMakers.keys(),
default = "native",
help = "The bitmap maker to use.",
type = str.lower,
)
bitmap.add_argument(
"--grayscale",
action = "store_true",
help = "Whether to render in grayscale mode (no colors).",
)
bitmap.add_argument(
"--byteorder",
dest = "rev_byteorder",
type = lambda v: {"bgr": False, "rgb": True}[v.lower()],
help = "Whether to use BGR or RGB byteorder (default: conditional).",
)
bitmap.add_argument(
"--x-channel",
dest = "prefer_bgrx",
action = BooleanOptionalAction,
help = "Whether to prefer BGRx/RGBx over BGR/RGB (default: conditional).",
)
bitmap.add_argument(
"--maybe-alpha",
action = BooleanOptionalAction,
help = "Whether to use BGRA if page content has transparency. Note, this makes format selection page-dependent. As this behavior can be confusing, it is not currently the default, but recommended for performance in these cases.",
)
# TODO expose force_bitmap_format
parallel = parser.add_argument_group(
title = "Parallelization",
description = "Options for rendering with multiple processes.",
)
parallel.add_argument(
"--linear",
nargs = "?",
type = int,
const = math.inf,
help = "Render non-parallel if page count is less or equal to the specified value (default: 4). If this flag is given without a value, then render linear regardless of document length.",
)
parallel.add_argument(
"--processes",
default = os.cpu_count(),
type = int,
help = "The maximum number of parallel rendering processes. Defaults to the number of CPU cores.",
)
parallel.add_argument(
"--parallel-strategy",
choices = ("spawn", "forkserver", "fork"),
default = "spawn",
type = str.lower,
help = "The process start method to use. ('fork' is discouraged due to stability issues.)",
)
parallel.add_argument(
"--parallel-lib",
choices = ("mp", "ft"),
default = "mp",
type = str.lower,
help = "The parallelization module to use (mp = multiprocessing, ft = concurrent.futures).",
)
parallel.add_argument(
"--parallel-map",
type = str.lower,
help = "The map function to use (backend specific, the default is an iterative map)."
)
color_scheme = parser.add_argument_group(
title = "Flat color scheme",
description = "Options for using pdfium's color scheme renderer. Note that this may flatten different colors into one, so the usability of this is limited. Alternatively, consider post-processing with lightness inversion (see below).",
)
color_scheme.add_argument(
"--sample-theme",
action = "store_true",
help = "Use a dark background sample theme as base. Explicit color params override selectively."
)
color_scheme.add_argument("--path-fill", **ColorOpts)
color_scheme.add_argument("--path-stroke", **ColorOpts)
color_scheme.add_argument("--text-fill", **ColorOpts)
color_scheme.add_argument("--text-stroke", **ColorOpts)
color_scheme.add_argument(
"--fill-to-stroke",
action = "store_true",
help = "When rendering with custom color scheme, only draw borders around fill areas using the `path_stroke` color, instead of filling with the `path_fill` color. This is actually recommended, since with a single fill color for paths the boundaries of adjacent fill paths are less visible.",
)
postproc = parser.add_argument_group(
title = "Post processing",
description = "Options to post-process rendered images. Note, this may have a strongly negative impact on performance.",
)
postproc.add_argument(
"--invert-lightness",
action = "store_true",
help = "Invert lightness using the HLS color space (e.g. white<->black, dark_blue<->light_blue). The intent is to achieve a dark theme for documents with light background, while providing better visual results than classical color inversion or a flat pdfium color scheme. However, note that --optimize-mode lcd is not recommendable when inverting lightness.",
)
postproc.add_argument(
"--exclude-images",
action = "store_true",
help = "Whether to exclude PDF images from lightness inversion.",
)
class SavingEngine:
def __init__(self, saver_args, postproc_kwargs):
self.args = saver_args
self.postproc_kwargs = postproc_kwargs
def _get_path(self, i, ext):
args = self.args
return args.output_dir / f"{args.prefix}{i+1:0{args.n_digits}d}.{ext}"
def __call__(self, i, bitmap, page):
if self.args.maybe_alpha and self.args.format in ("jpg", "jpeg") and pdfium_c.FPDFPage_HasTransparency(page):
# alternatively, we could perhaps convert to RGB
logger.info("Page has transparency - overriding output format to PNG.")
ext = "png"
else:
ext = self.args.format
out_path = self._get_path(i, ext)
self._saving_hook(out_path, bitmap, page, self.postproc_kwargs)
logger.info(f"Wrote page {i+1} as {out_path.name}")
class PILEngine (SavingEngine):
def do_imports(self):
if not self.postproc_kwargs["invert_lightness"]:
return
logger.debug("PIL engine imports for post-processing")
global PIL
import PIL.Image
import PIL.ImageOps
import PIL.ImageFilter
import PIL.ImageDraw
_to_pil_hook = staticmethod(pdfium.PdfBitmap.to_pil)
def _saving_hook(self, out_path, bitmap, page, postproc_kwargs):
posconv = bitmap.get_posconv(page)
pil_image = self._to_pil_hook(bitmap)
pil_image = self.postprocess(pil_image, page, posconv, **postproc_kwargs)
pil_image.save(out_path)
@staticmethod
def _invert_px_lightness(r, g, b):
h, l, s = colorsys.rgb_to_hls(r, g, b)
l = 1 - l
return colorsys.hls_to_rgb(h, l, s)
LINV_LUT_SIZE = 17
@classmethod
@functools.lru_cache(maxsize=1)
def _get_linv_lut(cls):
return PIL.ImageFilter.Color3DLUT.generate(cls.LINV_LUT_SIZE, cls._invert_px_lightness)
@classmethod
def postprocess(cls, src_image, page, posconv, invert_lightness, exclude_images):
dst_image = src_image
if invert_lightness:
if src_image.mode == "L":
dst_image = PIL.ImageOps.invert(src_image)
else:
dst_image = dst_image.filter(cls._get_linv_lut())
if exclude_images:
# FIXME pdfium does not seem to provide APIs to translate XObject to page coordinates, so not sure how to handle images nested in XObjects.
# FIXME we'd also like to take alpha masks into account, but this may be difficult as long as pdfium does not expose them directly.
have_images, obj_walker = iterator_hasvalue( page.get_objects([pdfium_c.FPDF_PAGEOBJ_IMAGE], max_depth=1) )
if have_images:
mask = PIL.Image.new("1", src_image.size)
draw = PIL.ImageDraw.Draw(mask)
for obj in obj_walker:
qpoints = [posconv.to_bitmap(x, y) for x, y in obj.get_quad_points()]
draw.polygon(qpoints, fill=1)
dst_image.paste(src_image, mask=mask)
return dst_image
class NumpyPILEngine (PILEngine):
def do_imports(self):
logger.debug("NumPy+PIL engine imports")
global PIL
import PIL.Image
super().do_imports()
@staticmethod
def _to_pil_hook(bitmap):
return PIL.Image.fromarray(bitmap.to_numpy(), bitmap.mode)
class NumpyCV2Engine (SavingEngine):
def do_imports(self):
logger.debug("NumPy+cv2 engine imports")
global cv2, np
import cv2
if self.postproc_kwargs["exclude_images"]:
import numpy as np
def _saving_hook(self, out_path, bitmap, page, postproc_kwargs):
np_array = bitmap.to_numpy()
np_array = self.postprocess(np_array, bitmap, page, **postproc_kwargs)
cv2.imwrite(str(out_path), np_array)
@classmethod
def postprocess(cls, src_image, bitmap, page, invert_lightness, exclude_images):
dst_image = src_image
if invert_lightness:
if bitmap.format == pdfium_c.FPDFBitmap_Gray:
dst_image = ~src_image
else:
convert_to, convert_from = (cv2.COLOR_RGB2HLS, cv2.COLOR_HLS2RGB) if bitmap.rev_byteorder else (cv2.COLOR_BGR2HLS, cv2.COLOR_HLS2BGR)
dst_image = cv2.cvtColor(dst_image, convert_to)
h, l, s = cv2.split(dst_image)
l = ~l
dst_image = cv2.merge([h, l, s])
dst_image = cv2.cvtColor(dst_image, convert_from)
if exclude_images:
assert bitmap.format != pdfium_c.FPDFBitmap_BGRx, "Not sure how to paste with mask on {RGB,BGR}X image using cv2" # FIXME?
posconv = bitmap.get_posconv(page)
have_images, obj_walker = iterator_hasvalue( page.get_objects([pdfium_c.FPDF_PAGEOBJ_IMAGE], max_depth=1) )
if have_images:
mask = np.zeros((bitmap.height, bitmap.width, 1), np.uint8)
for obj in obj_walker:
qpoints = np.array([posconv.to_bitmap(x, y) for x, y in obj.get_quad_points()], np.int32)
cv2.fillPoly(mask, [qpoints], 1)
dst_image = cv2.copyTo(src_image, mask=mask, dst=dst_image)
return dst_image
def _render_parallel_init(logging_init, engine_init, input, password, may_init_forms, kwargs, engine):
logging_init()
logger.info(f"Initializing data for process {os.getpid()}")
engine_init()
pdf = pdfium.PdfDocument(input, password=password, autoclose=True)
if may_init_forms:
pdf.init_forms()
global ProcObjs
ProcObjs = (pdf, kwargs, engine)
def _render_job(i, pdf, kwargs, engine):
# logger.info(f"Started page {i+1} ...")
page = pdf[i]
bitmap = page.render(**kwargs)
engine(i, bitmap, page)
page.close()
def _render_parallel_job(i):
global ProcObjs
_render_job(i, *ProcObjs)
def _do_nothing(): pass
# TODO turn into a python-usable API yielding output paths as they are written
def main(args):
if not args.output.is_dir():
# make sure the output directory exists (PIL throws an error if it doesn't, but cv2 may silently skip)
raise ValueError(f"Output path is not an existing directory: {args.output!r}")
pdf = get_input(args, init_forms=args.draw_forms)
pdf_len = len(pdf)
if not all(0 <= i < pdf_len for i in args.pages):
raise ValueError("Out-of-bounds page indices are prohibited.")
if len(args.pages) != len(set(args.pages)):
raise ValueError("Duplicate page indices are prohibited.")
if args.prefix is None:
args.prefix = f"{args.input.stem}_"
if args.fill_color is None:
args.fill_color = (0, 0, 0, 255) if args.sample_theme else (255, 255, 255, 255)
if args.format is None:
# can't use jpeg with transparency rsp. when there is an alpha channel
args.format = "jpg" if args.fill_color[3] == 255 else "png"
if args.linear is None:
args.linear = 4
# numpy+cv2 is much faster for PNG, and PIL faster for JPG, but this might simply be due to different encoding defaults
if args.engine_cls is None:
assert have_pil or have_cv2, "Either pillow or numpy+cv2 must be installed for rendering CLI."
if (not have_pil) or (have_cv2 and args.format == "png"):
args.engine_cls = NumpyCV2Engine
else:
args.engine_cls = PILEngine
# PIL is faster with rev_byteorder and prefer_bgrx = True, as this achieves a natively supported pixel format. For numpy+cv2 there doesn't seem to be a difference.
if args.rev_byteorder is None:
args.rev_byteorder = issubclass(args.engine_cls, PILEngine)
if args.prefer_bgrx is None:
# PIL can't save BGRX as PNG
args.prefer_bgrx = issubclass(args.engine_cls, PILEngine) and args.format != "png"
cs_kwargs = dict()
if args.sample_theme:
cs_kwargs.update(**SampleTheme)
cs_kwargs.update(**{f: getattr(args, f) for f in ColorSchemeFields if getattr(args, f)})
color_scheme = pdfium.PdfColorScheme(**cs_kwargs) if cs_kwargs else None
kwargs = dict(
scale = args.scale,
rotation = args.rotation,
crop = args.crop,
grayscale = args.grayscale,
fill_color = args.fill_color,
optimize_mode = args.optimize_mode,
draw_annots = args.draw_annots,
may_draw_forms = args.draw_forms,
force_halftone = args.force_halftone,
rev_byteorder = args.rev_byteorder,
prefer_bgrx = args.prefer_bgrx,
maybe_alpha = args.maybe_alpha,
bitmap_maker = BitmapMakers[args.bitmap_maker],
color_scheme = color_scheme,
fill_to_stroke = args.fill_to_stroke,
)
for type in args.no_antialias:
kwargs[f"no_smooth{type}"] = True
saver_args = types.SimpleNamespace(
output_dir = args.output,
prefix = args.prefix,
n_digits = len(str(pdf_len)),
format = args.format,
maybe_alpha = args.maybe_alpha,
)
postproc_kwargs = dict(
invert_lightness = args.invert_lightness,
exclude_images = args.exclude_images,
)
if args.invert_lightness and args.optimize_mode == "lcd":
logger.warning("LCD optimization clashes with lightness inversion, as post-processing colors defeats the idea of subpixel rendering.")
print_args = vars(args).copy()
del print_args["subcommand"], print_args["pages"]
if print_args["password"]:
print_args["password"] = "<obfuscated>"
logger.debug(f"{print_args}") # TODO prettier?
if color_scheme:
logger.debug(f"{color_scheme}")
engine = args.engine_cls(saver_args, postproc_kwargs)
if len(args.pages) <= args.linear:
logger.info("Linear rendering ...")
engine.do_imports()
for i in args.pages:
_render_job(i, pdf, kwargs, engine)
else:
logger.info("Parallel rendering ...")
ctx = mp.get_context(args.parallel_strategy)
pool_backends = dict(
mp = (ctx.Pool, "imap"),
ft = (functools.partial(ft.ProcessPoolExecutor, mp_context=ctx), "map"),
)
pool_ctor, map_attr = pool_backends[args.parallel_lib]
if args.parallel_map:
map_attr = args.parallel_map
if args.parallel_strategy == "fork":
logging_init, engine_init = _do_nothing, _do_nothing
engine.do_imports()
else:
logging_init, engine_init = setup_logging, engine.do_imports
pool_kwargs = dict(
initializer = _render_parallel_init,
initargs = (logging_init, engine_init, pdf._input, args.password, args.draw_forms, kwargs, engine),
)
n_procs = min(args.processes, len(args.pages))
with pool_ctor(n_procs, **pool_kwargs) as pool:
map_func = getattr(pool, map_attr)
for _ in map_func(_render_parallel_job, args.pages):
pass
@@ -0,0 +1,83 @@
# SPDX-FileCopyrightText: 2026 geisserml <geisserml@gmail.com>
# SPDX-License-Identifier: Apache-2.0 OR BSD-3-Clause
from enum import Enum
from pathlib import Path
import pypdfium2 as pdfium
import pypdfium2.raw as pdfium_c
from pypdfium2_cli._parsers import add_input, get_input
class Units (Enum):
PT = 0
MM = 1
CM = 2
IN = 3
def units_to_pt(value, unit):
if unit is Units.PT:
return value
elif unit is Units.IN:
return value*72
elif unit is Units.CM:
return (value*72) / 2.54
elif unit is Units.MM:
return (value*72) / 25.4
else:
raise ValueError(f"Invalid unit type {unit}")
def attach(parser):
add_input(parser, pages=False)
parser.add_argument(
"--output", "-o",
required = True,
type = Path,
help = "Target path for the new document",
)
parser.add_argument(
"--rows", "-r",
type = int,
required = True,
help = "Number of rows (horizontal tiles)",
)
parser.add_argument(
"--cols", "-c",
type = int,
required = True,
help = "Number of columns (vertical tiles)",
)
# NOTE no short aliases for width and height since -h would conflict with argparse help
parser.add_argument(
"--width",
type = float,
required = True,
help = "Target width",
)
parser.add_argument(
"--height",
type = float,
required = True,
help = "Target height",
)
parser.add_argument(
"--unit", "-u",
default = Units.MM,
type = lambda string: Units[string.upper()],
help = "Unit for target width and height (pt, mm, cm, in)",
)
def main(args):
# Rudimentary page tiling, powered by pdfium
# A more sophisticated implementation could place XObjects rather than using PDFium's helper function, support merging and arranging on the fly, etc.
w = units_to_pt(args.width, args.unit)
h = units_to_pt(args.height, args.unit)
src_pdf = get_input(args)
raw_dest = pdfium_c.FPDF_ImportNPagesToOne(src_pdf, w, h, args.cols, args.rows)
dest_pdf = pdfium.PdfDocument(raw_dest)
dest_pdf.save(args.output)
@@ -0,0 +1,85 @@
# SPDX-FileCopyrightText: 2026 geisserml <geisserml@gmail.com>
# SPDX-License-Identifier: Apache-2.0 OR BSD-3-Clause
import pypdfium2.internal as pdfium_i
from pypdfium2_cli._parsers import (
add_input, add_n_digits,
get_input, round_list,
)
from pypdfium2_cfg.stl import BooleanOptionalAction
def attach(parser):
add_input(parser, pages=False)
add_n_digits(parser)
parser.add_argument(
"--max-depth",
type = int,
default = 15,
help = "Maximum recursion depth to consider when parsing the table of contents",
)
parser.add_argument(
"--highlight",
action = BooleanOptionalAction,
default = True,
help = "Whether console ANSI escape sequences may be used for styling or color indication. Defaults to true.",
)
class ColorIndicator:
def __init__(self, indicator, sep):
self.indicator = indicator
self.sep = sep
def __call__(self, color):
r, g, b = tuple(round(c*255) for c in color)
return f"\x1b[38;2;{r};{g};{b}m" + self.indicator + "\x1b[0m" + self.sep
@staticmethod
def noop(color):
return ""
def main(args):
pdf = get_input(args)
if args.highlight:
icol = ColorIndicator("⬤", sep=" ")
else:
icol = ColorIndicator.noop
for bm in pdf.get_toc(max_depth=args.max_depth):
title = bm.get_title()
style = bm.get_style()
color = bm.get_color()
count = bm.get_count()
count_str = f"{count:+}" if count != 0 else "*"
out = " " * bm.level
# unconditionally add "->" regardless of whether a dest follows or not, to avoid ambiguity with titles potentially containing the same
# TODO apply style to title via ANSI escape sequence
out += "[%s] %s -> " % (count_str, title)
dest = bm.get_dest()
if dest:
index = dest.get_index()
view_mode, view_pos = dest.get_view()
out += "%s # %s %s" % (
index+1 if index != None else "?",
pdfium_i.ViewmodeToStr.get(view_mode),
round_list(view_pos, args.n_digits),
)
else:
out += "_"
extras = []
if style:
# is this awful? yes. but it's for compatibility with python < 3.11 ...
extras.append(str(style).split(".", maxsplit=1)[1].replace("|", "+").lower())
if color:
extras.append(icol(color) + f"RGB{round_list(color, args.n_digits)}")
if extras:
out += " | " + ", ".join(extras)
print(out)