### Install pypdfium2 with Default Setup Source: https://pypdfium2.readthedocs.io/en/stable/readme.html Installs pypdfium2 using the default setup, which typically downloads pre-built binaries and generates bindings. Use the -v flag for verbose output during installation. ```bash # In the pypdfium2/ directory python -m pip install -v . ``` -------------------------------- ### Sysfont Handler Setup and Management Source: https://pypdfium2.readthedocs.io/en/stable/_modules/pypdfium2/_helpers/sysfontinfo.html Methods for installing, closing, and managing the lifecycle of the system font handler. The `setup` method installs the handler, `close` allows manual unregistration, and `Release`, `EnumFonts`, `MapFont`, `GetFont`, `GetFontData`, `GetFaceName`, `GetFontCharset`, and `DeleteFont` delegate to the default handler for font operations. ```APIDOC ## `setup(reusable=False)` ### Description Installs (activates) the sysfont handler. This handler is kept alive until the end of the session by default, but can be closed earlier using the `close` method. Sysfont handlers are singletons; installing a new one implicitly closes the previous one. ### Parameters * `reusable` (bool): If True, the handler can be reused after closing. Defaults to False. ## `close(reusable=None)` ### Description Manually closes the sysfont handler, unregistering the exit handler and releasing resources immediately. The `reusable` parameter controls whether the underlying default handler is preserved. ### Parameters * `reusable` (bool): If False (default), destroys pdfium's default handler. If True, the default handler is preserved for potential reuse. ## `Release(_)` ### Description Releases the sysfont handler if it is not reusable. Otherwise, it's a no-op. ### Parameters * `_`: Ignored parameter. ## `EnumFonts(_, pMapper)` ### Description Enumerates available fonts. Delegates to the default handler. ### Parameters * `_`: Ignored parameter. * `pMapper`: Font mapper object. ## `MapFont(_, weight, bItalic, charset, pitch_family, face, _ignored)` ### Description Maps a font based on specified attributes. Delegates to the default handler. ### Parameters * `_`: Ignored parameter. * `weight` (int): Font weight. * `bItalic` (bool): Whether the font is italic. * `charset` (int): Font character set. * `pitch_family` (int): Font pitch and family. * `face` (str): Font face name. * `_ignored`: Ignored parameter. ## `GetFont(_, face)` ### Description Retrieves a font handle for a given font face name. Delegates to the default handler. ### Parameters * `_`: Ignored parameter. * `face` (str): Font face name. ## `GetFontData(_, hFont, table, buffer, buf_size)` ### Description Retrieves data for a given font handle and table. Delegates to the default handler. ### Parameters * `_`: Ignored parameter. * `hFont`: Font handle. * `table` (str): Table name (e.g., 'head', 'OS/2'). * `buffer`: Buffer to store font data. * `buf_size` (int): Size of the buffer. ## `GetFaceName(_, hFont, buffer, buf_size)` ### Description Retrieves the face name for a given font handle. Delegates to the default handler. ### Parameters * `_`: Ignored parameter. * `hFont`: Font handle. * `buffer`: Buffer to store the face name. * `buf_size` (int): Size of the buffer. ## `GetFontCharset(_, hFont)` ### Description Retrieves the character set for a given font handle. Delegates to the default handler. ### Parameters * `_`: Ignored parameter. * `hFont`: Font handle. ## `DeleteFont(_, hFont)` ### Description Deletes a font handle. Delegates to the default handler. ### Parameters * `_`: Ignored parameter. * `hFont`: Font handle. ``` -------------------------------- ### Install Docker on Fedora Source: https://pypdfium2.readthedocs.io/en/stable/readme.html Installs Docker using dnf on Fedora. Enables and starts the Docker service, and adds the current user to the docker group. ```bash sudo dnf in moby-engine # this provides the docker command sudo systemctl start docker sudo systemctl enable docker sudo usermod -aG docker $USER # then reboot (re-login might also suffice) ``` -------------------------------- ### Custom pypdfium2 Setup with Provided Data Files Source: https://pypdfium2.readthedocs.io/en/stable/readme.html This script demonstrates how to manually configure pypdfium2 by providing your own PDFium DLL, bindings, and version information. It's useful when you need to bypass pypdfium2's automated deployment or have specific build requirements. Ensure you have the correct PDFium DLL and the pypdfium2-team fork of ctypesgen installed. ```bash # First, ask yourself: Do you want to bundle pdfium (in-tree), or use system # pdfium (out-of-tree)? For bundling, set "sourcebuild", else set "system". TARGET="sourcebuild" # or "system" STAGING_DIR="data/$TARGET" # If you have decided for bundling, copy over the pdfium DLL in question. # Otherwise, skip this step. cp "$MY_BINARY_PATH" "$STAGING_DIR/libpdfium.so" # Now, we will call ctypesgen to generate the bindings interface. # Reminder: You'll want to use the pypdfium2-team fork of ctypesgen. # It generates much cleaner bindings, and it's what our source expects # (there may be subtle API differences in terms of output). # How exactly you do this is down to you. # See ctypesgen --help or base.py::run_ctypesgen() for further options. ctypesgen --library pdfium --rt-libpaths $MY_RT_LIBPATHS --ct-libpaths $MY_CT_LIBPATHS \ --headers $MY_INCLUDE_DIR/fpdf*.h -o $STAGING_DIR/bindings.py [-D $MY_RAW_FLAGS] # Then write the version file (fill the placeholders). # Note, this is not a mature interface yet and might change any time! # See also https://pypdfium2.readthedocs.io/en/stable/python_api.html#pypdfium2.version.PDFIUM_INFO # major/minor/build/patch: integers forming the pdfium version being packaged # n_commits/hash: git describe like post-tag info (0/null for release commit) # origin: a string to identify the build # flags: a comma-delimited list of pdfium feature flag strings # (e.g. "V8", "XFA") - may be empty for default build cat > "$STAGING_DIR/version.json" < None: """Register the handler with PDFium.""" pass ``` -------------------------------- ### Basic cibuildwheel Invocation Source: https://pypdfium2.readthedocs.io/en/stable/readme.html A basic example of running cibuildwheel for a specific build target. CIBW_BUILD specifies the Python version and platform. ```bash CIBW_BUILD="cp314-manylinux_x86_64" cibuildwheel ``` -------------------------------- ### Advanced cibuildwheel Invocation Source: https://pypdfium2.readthedocs.io/en/stable/readme.html An advanced cibuildwheel example specifying the architecture, container engine, and enabling tests. CIBW_ARCHS and CIBW_CONTAINER_ENGINE are used for customization. ```bash CIBW_BUILD="cp314-musllinux_s390x" CIBW_ARCHS=s390x CIBW_CONTAINER_ENGINE=podman TEST_PDFIUM=1 cibuildwheel ``` -------------------------------- ### Clone pypdfium2 repository Source: https://pypdfium2.readthedocs.io/en/stable/readme.html Clone the pypdfium2 repository from GitHub to build or contribute to the project. Navigate into the cloned directory to proceed with setup. ```bash git clone "https://github.com/pypdfium2-team/pypdfium2.git" cd pypdfium2/ ``` -------------------------------- ### Show Image Converter Help Source: https://pypdfium2.readthedocs.io/en/stable/shell_api.html Displays the help message for the `imgtopdf` command, detailing options for converting images into PDF documents. This includes specifying the output path and whether to use inline loading for JPEGs. ```bash $ pypdfium2 imgtopdf --help ``` -------------------------------- ### Get Previous Text Occurrence Source: https://pypdfium2.readthedocs.io/en/stable/_modules/pypdfium2/_helpers/textpage.html Finds the previous occurrence of text in a PDF page. Returns the start character index and count of the occurrence, or None if no more occurrences are found. ```python 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) ``` -------------------------------- ### Show help for render command Source: https://pypdfium2.readthedocs.io/en/stable/shell_api.html Use the --help flag to display usage information and available options for the render command, which rasterizes PDF pages into images. ```bash $ pypdfium2 render --help usage: pypdfium2 render [-h] [--password PASSWORD] [--pages PAGES] --output OUTPUT [--prefix PREFIX] [--format FORMAT] [--engine ENGINE_CLS] [--scale SCALE] [--rotation {0,90,180,270}] [--fill-color C C C C] [--optimize-mode {lcd,print}] [--crop C C C C] [--draw-annots | --no-draw-annots] [--draw-forms | --no-draw-forms] [--no-antialias {text,image,path} [{text,image,path} ...]] [--force-halftone] [--bitmap-maker {native,foreign,foreign_packed,foreign_simple}] [--grayscale] [--byteorder REV_BYTEORDER] [--x-channel | --no-x-channel] [--maybe-alpha | --no-maybe-alpha] [--linear [LINEAR]] [--processes PROCESSES] [--parallel-strategy {spawn,forkserver,fork}] [--parallel-lib {mp,ft}] [--parallel-map PARALLEL_MAP] [--sample-theme] [--path-fill C C C C] [--path-stroke C C C C] [--text-fill C C C C] [--text-stroke C C C C] [--fill-to-stroke] [--invert-lightness] [--exclude-images] input Rasterize pages positional arguments: input Input PDF document options: -h, --help show this help message and exit --password PASSWORD A password to unlock the PDF, if encrypted --pages PAGES Page numbers and ranges to include --output, -o OUTPUT Output directory where the serially numbered images shall be placed. --prefix PREFIX Custom prefix for the images. Defaults to the input filename's stem. --format, -f FORMAT The image format to use (default: conditional). --engine ENGINE_CLS The saver engine to use ('pil', 'numpy+pil', 'numpy+cv2') --scale SCALE 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. --rotation {0,90,180,270} Rotate pages by 90, 180 or 270 degrees. --fill-color C C C C 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. --optimize-mode {lcd,print} The rendering optimisation mode. None if not given. --crop C C C C Amount to crop from (left, bottom, right, top). --draw-annots, --no-draw-annots Whether annotations may be shown (default: true). --draw-forms, --no-draw-forms Whether forms may be shown (default: true). --no-antialias {text,image,path} [{text,image,path} ...] Item types that shall not be smoothed. --force-halftone Always use halftone for image stretching. Bitmap options: Bitmap config, including pixel format. ``` -------------------------------- ### Get Next Text Occurrence Source: https://pypdfium2.readthedocs.io/en/stable/_modules/pypdfium2/_helpers/textpage.html Finds the next occurrence of text in a PDF page. Returns the start character index and count of the occurrence, or None if no more occurrences are found. ```python @property def parent(self): 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) ``` -------------------------------- ### Access Default TTF Font Map Source: https://pypdfium2.readthedocs.io/en/stable/_modules/pypdfium2/_helpers/sysfontinfo.html Provides access to the default TTF font map used by PDFium. Use the `.value` cached property to get the map or `.get(charset)` to retrieve a font name by charset. Note that PDFium may choose a system or internal substitute if a default font is not installed. ```python 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() ``` -------------------------------- ### Build Packages for PyPI Source: https://pypdfium2.readthedocs.io/en/stable/readme.html Build platform-specific wheel packages and a source distribution suitable for PyPI upload using the 'just packaging-pypi' command. ```bash just packaging-pypi ``` -------------------------------- ### Initialize C Array for Output Parameters Source: https://pypdfium2.readthedocs.io/en/stable/readme.html Demonstrates how to initialize a C-style array using ctypes for output parameters. Supports both long and short form initialization. ```python # long form array_type = (c_type * array_length) array_object = array_type() # short form array_object = (c_type * array_length)() ``` -------------------------------- ### Get Image Pixel Size in Python Source: https://pypdfium2.readthedocs.io/en/stable/_modules/pypdfium2/_helpers/pageobjects.html Get the image dimensions in pixels as a tuple of (width, height). Prefer this method over `get_metadata` if only the size is needed. ```python 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 ``` -------------------------------- ### Import pypdfium2 library Source: https://pypdfium2.readthedocs.io/en/stable/readme.html Import the main library and its raw API components. ```python import pypdfium2 as pdfium import pypdfium2.raw as pdfium_c ``` -------------------------------- ### Build HTML Documentation Source: https://pypdfium2.readthedocs.io/en/stable/readme.html Use sphinx-build to render API documentation to HTML format. The 'just docs-build' command is a convenient alias. ```bash sphinx-build -b html ./docs/source ./docs/build/html/ just docs-build # short alias ``` -------------------------------- ### Native Build Dependencies (Ubuntu 24.04) Source: https://pypdfium2.readthedocs.io/en/stable/readme.html Install necessary system dependencies for the native build on Ubuntu 24.04, including GN, ninja, and various development libraries. ```bash # Install dependencies python -m pip install -r req/gn.txt # see above sudo apt-get install ninja-build libfreetype-dev liblcms2-dev libjpeg-dev libopenjp2-7-dev libpng-dev libtiff-dev zlib1g-dev libicu-dev libglib2.0-dev libharfbuzz-dev # generate-ninja ``` -------------------------------- ### Native Build with Clang Source: https://pypdfium2.readthedocs.io/en/stable/readme.html Configure and build PDFium using Clang as the compiler. This involves installing Clang, setting up symbolic links for Clang versions, and ensuring builtins are available. ```bash # Alternatively, build with Clang sudo apt-get install llvm lld VERSION=18 ARCH=$(uname -m) sudo ln -s "/usr/lib/clang/$VERSION/lib/linux" "/usr/lib/clang/$VERSION/lib/$ARCH-unknown-linux-gnu" sudo ln -s "/usr/lib/clang/$VERSION/lib/linux/libclang_rt.builtins-$ARCH.a" "/usr/lib/clang/$VERSION/lib/linux/libclang_rt.builtins.a" python ./setupsrc/build_native.py --compiler clang ``` -------------------------------- ### Display pypdfium2 Main Help Source: https://pypdfium2.readthedocs.io/en/stable/shell_api.html Shows the main help message for the pypdfium2 command-line interface, listing available subcommands and options. This is useful for understanding the CLI's capabilities. ```shell $ pypdfium2 --help usage: pypdfium2 [-h] [-v] {arrange,attachments,extract-images,extract-text,imgtopdf,pageobjects,pdfinfo,fonts,default-fonts,render,tile,toc} ... pypdfium2 is a Python binding to PDFium, a PDF processing library. This is the command-line interface. Invoke as `pypdfium2` or `python -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 {debug,warning,critical} = warning How much info to print about (auto-)closing of PDFium objects. - 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. positional arguments: {arrange,attachments,extract-images,extract-text,imgtopdf,pageobjects,pdfinfo,fonts,default-fonts,render,tile,toc} 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 options: -h, --help show this help message and exit -v, --version show program's version number and exit ``` -------------------------------- ### Get Bookmark Child Count Source: https://pypdfium2.readthedocs.io/en/stable/_modules/pypdfium2/_helpers/document.html Gets the number of child bookmarks visible if the bookmark were open. A positive number indicates the bookmark is initially open, negative indicates closed, and zero means no descendants. ```python return pdfium_c.FPDFBookmark_GetCount(self) ``` -------------------------------- ### classmethod new_foreign_simple(_width_ , _height_ , _use_alpha_ , _rev_byteorder =False_) Source: https://pypdfium2.readthedocs.io/en/stable/python_api.html Create a new bitmap using `FPDFBitmap_Create()`. This method uses a boolean `_use_alpha_` to determine the format (BGRA or BGRx) and allocates the buffer via PDFium. ```APIDOC classmethod new_foreign_simple(_width_ , _height_ , _use_alpha_ , _rev_byteorder =False_)[source] Create a new bitmap using `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_*()` methods, this method does not take a format constant, but a _use_alpha_ boolean. If True, the format will be `FPDFBitmap_BGRA`, `FPFBitmap_BGRx` otherwise. Other bitmap formats cannot be used with this method. Note, the recommended default bitmap creation strategy is `new_native()`. ``` -------------------------------- ### get_filters Source: https://pypdfium2.readthedocs.io/en/stable/_modules/pypdfium2/_helpers/pageobjects.html Get a list of image filters applied to the image stream. ```APIDOC ## get_filters ### Description Get a list of image filters applied to the image stream. ### 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). ``` -------------------------------- ### PdfBookmark.get_count Source: https://pypdfium2.readthedocs.io/en/stable/_modules/pypdfium2/_helpers/document.html Gets the number of child bookmarks that would be visible if the bookmark were open. ```APIDOC ## PdfBookmark.get_count ### Description Gets the number of child bookmarks that would be visible if the bookmark were open. The bookmark's initial state is open (expanded) if the number is positive, closed (collapsed) if negative. Zero if the bookmark has no descendants. ### Method GET ### Endpoint `/bookmarks/{id}/count` ### Parameters #### Path Parameters - **id** (int) - Required - The ID of the bookmark. ### Response #### Success Response (200) - **count** (int) - The number of visible child bookmarks. ### Response Example ```json { "count": 5 } ``` ``` -------------------------------- ### Get Page by Index Source: https://pypdfium2.readthedocs.io/en/stable/_modules/pypdfium2/_helpers/document.html Retrieves a specific page from the document using its index. ```python def __getitem__(self, i): return self.get_page(i) ``` -------------------------------- ### Get Page Count Source: https://pypdfium2.readthedocs.io/en/stable/_modules/pypdfium2/_helpers/document.html Returns the total number of pages in the PDF document. ```python def __len__(self): return pdfium_c.FPDF_GetPageCount(self) ``` -------------------------------- ### Get Bookmark Destination Source: https://pypdfium2.readthedocs.io/en/stable/_modules/pypdfium2/_helpers/document.html Retrieves the destination associated with a bookmark. Returns None on failure. ```python raw_dest = pdfium_c.FPDFBookmark_GetDest(self.pdf, self) if not raw_dest: return None return PdfDest(raw_dest, pdf=self.pdf) ``` -------------------------------- ### Page Tiler Help Source: https://pypdfium2.readthedocs.io/en/stable/shell_api.html Displays help information for the pypdfium2 tile command. Use this to understand the available options for tiling PDF pages. ```shell $ pypdfium2 tile --help usage: pypdfium2 tile [-h] [--password PASSWORD] --output OUTPUT --rows ROWS --cols COLS --width WIDTH --height HEIGHT [--unit UNIT] input Tile pages (N-up) positional arguments: input Input PDF document options: -h, --help show this help message and exit --password PASSWORD A password to unlock the PDF, if encrypted --output, -o OUTPUT Target path for the new document --rows, -r ROWS Number of rows (horizontal tiles) --cols, -c COLS Number of columns (vertical tiles) --width WIDTH Target width --height HEIGHT Target height --unit, -u UNIT Unit for target width and height (pt, mm, cm, in) ``` -------------------------------- ### Get Bookmark Title Source: https://pypdfium2.readthedocs.io/en/stable/_modules/pypdfium2/_helpers/document.html Retrieves the title of a PDF bookmark. Handles UTF-16LE decoding. ```python 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") ``` -------------------------------- ### Show help for fonts command Source: https://pypdfium2.readthedocs.io/en/stable/shell_api.html Use the --help flag to display usage information and available options for the fonts command. Note that 'tabulate' may be required for formatted output. ```bash $ pypdfium2 fonts --help You may want to install `tabulate` for prettier output. usage: pypdfium2 fonts [-h] [--password PASSWORD] [--pages PAGES] input List a document's fonts 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. positional arguments: input Input PDF document options: -h, --help show this help message and exit --password PASSWORD A password to unlock the PDF, if encrypted --pages PAGES Page numbers and ranges to include ``` -------------------------------- ### classmethod new_native(_width_ , _height_ , _format_ , _rev_byteorder =False_, _buffer =None_, _stride =None_) Source: https://pypdfium2.readthedocs.io/en/stable/python_api.html Create a new bitmap using `FPDFBitmap_CreateEx()`, with a buffer allocated by Python/ctypes, or provided by the caller. Handles cases where buffer and/or stride are provided or not. ```APIDOC classmethod new_native(_width_ , _height_ , _format_ , _rev_byteorder =False_, _buffer =None_, _stride =None_)[source] Create a new bitmap using `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. ``` -------------------------------- ### Get Page Dimensions Source: https://pypdfium2.readthedocs.io/en/stable/_modules/pypdfium2/_helpers/page.html Retrieve the width and height of a PDF page in PDF canvas units. ```python page.get_width() page.get_height() page.get_size() ``` -------------------------------- ### Get page label Source: https://pypdfium2.readthedocs.io/en/stable/_modules/pypdfium2/_helpers/document.html Retrieves the label of a page, which serves as an alias for its number. The label is returned as a string. ```python 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") ``` -------------------------------- ### Show help for pdfinfo command Source: https://pypdfium2.readthedocs.io/en/stable/shell_api.html Use the --help flag to display usage information and available options for the pdfinfo command. ```bash $ pypdfium2 pdfinfo --help usage: pypdfium2 pdfinfo [-h] [--password PASSWORD] [--pages PAGES] [--n-digits N_DIGITS] Print info on document and pages positional arguments: input Input PDF document options: -h, --help show this help message and exit --password PASSWORD A password to unlock the PDF, if encrypted --pages PAGES Page numbers and ranges to include --n-digits N_DIGITS Number of digits to which coordinates/sizes shall be rounded ``` -------------------------------- ### Get Font Weight Source: https://pypdfium2.readthedocs.io/en/stable/_modules/pypdfium2/_helpers/pageobjects.html Retrieves the weight of the font. Typical values are 400 (normal) and 700 (bold). ```python weight = pdfium_c.FPDFFont_GetWeight(self) if weight == -1: raise PdfiumError("Failed to get font weight.") return weight ``` -------------------------------- ### Get Font Family Name Source: https://pypdfium2.readthedocs.io/en/stable/_modules/pypdfium2/_helpers/pageobjects.html Retrieves the family name of the font. Uses the internal `_get_name_impl` helper. ```python return self._get_name_impl(pdfium_c.FPDFFont_GetFamilyName, "family", errors) ``` -------------------------------- ### Subclassing PdfSysfontBase for Custom Callbacks Source: https://pypdfium2.readthedocs.io/en/stable/python_api.html Demonstrates how to subclass PdfSysfontBase to implement custom system font callbacks. It shows how to wrap default implementations and delegate calls. ```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 ``` -------------------------------- ### Get Font Base Name Source: https://pypdfium2.readthedocs.io/en/stable/_modules/pypdfium2/_helpers/pageobjects.html Retrieves the base name of the font. Uses the internal `_get_name_impl` helper. ```python return self._get_name_impl(pdfium_c.FPDFFont_GetBaseFontName, "base", errors) ``` -------------------------------- ### Get Destination Page Index Source: https://pypdfium2.readthedocs.io/en/stable/_modules/pypdfium2/_helpers/document.html Retrieves the zero-based page index of a PDF destination. Returns None on failure. ```python val = pdfium_c.FPDFDest_GetDestPageIndex(self.pdf, self) return val if val >= 0 else None ``` -------------------------------- ### classmethod from_raw(_raw_ , _rev_byteorder =False_, _ex_buffer =None_) Source: https://pypdfium2.readthedocs.io/en/stable/python_api.html Construct a `PdfBitmap` wrapper around a raw PDFium bitmap handle. This method is primarily meant for bitmaps provided by pdfium. For bitmaps created by the caller, it may be preferable to call the `PdfBitmap` constructor directly. ```APIDOC classmethod from_raw(_raw_ , _rev_byteorder =False_, _ex_buffer =None_)[source] Construct a `PdfBitmap` wrapper around a raw PDFium bitmap handle. Note This method is primarily meant for bitmaps provided by pdfium (as in `PdfImage.get_bitmap()`). For bitmaps created by the caller, where the parameters are already known, it may be preferable to call the `PdfBitmap` constructor directly. Parameters: * **raw** (_FPDF_BITMAP_) – PDFium bitmap handle. * **rev_byteorder** (_bool_) – Whether the bitmap uses reverse byte order. * **ex_buffer** (_Array_ _[__c_ubyte_ _]__|__None_) – If the bitmap was created from a buffer allocated by Python/ctypes, pass in the ctypes array to keep it referenced. ``` -------------------------------- ### Get page size Source: https://pypdfium2.readthedocs.io/en/stable/_modules/pypdfium2/_helpers/document.html Retrieves the width and height of a page in PDF canvas units using its zero-based index. ```python 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) ``` -------------------------------- ### Help for pypdfium2 arrange command Source: https://pypdfium2.readthedocs.io/en/stable/shell_api.html Displays the help message for the 'arrange' subcommand, outlining its purpose and available options for rearranging and merging PDF documents. ```shell $ pypdfium2 arrange --help usage: pypdfium2 arrange [-h] [--pages PAGES [PAGES ...]] [--passwords PASSWORDS [PASSWORDS ...]] --output OUTPUT inputs [inputs ...] Rearrange/merge documents positional arguments: inputs Sequence of PDF files. options: -h, --help show this help message and exit --pages PAGES [PAGES ...] Sequence of page texts, definig the pages to include from each PDF. Use '_' as placeholder for all pages. --passwords PASSWORDS [PASSWORDS ...] Passwords to unlock encrypted PDFs. Any placeholder may be used for non-encrypted documents. --output, -o OUTPUT Target path for the output document ``` -------------------------------- ### Get Attachment by Index Source: https://pypdfium2.readthedocs.io/en/stable/_modules/pypdfium2/_helpers/document.html Retrieves a specific attachment from the document by its zero-based index. Raises PdfiumError if the attachment cannot be retrieved. ```python 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) ``` -------------------------------- ### get_bitmap Source: https://pypdfium2.readthedocs.io/en/stable/_modules/pypdfium2/_helpers/pageobjects.html Get a bitmap rasterization of the image. This method can optionally render the image, applying transformations and alpha masks. ```APIDOC ## get_bitmap ### Description Get a bitmap rasterization of the image. This method can optionally render the image, applying transformations and alpha masks. ### 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). ``` -------------------------------- ### Set up Conda Channels in a GitHub Workflow Source: https://pypdfium2.readthedocs.io/en/stable/readme.html Configures Conda channels and priority within a GitHub Actions workflow using the setup-miniconda action. This ensures the correct channels are used during CI/CD processes. ```yaml - name: ... uses: conda-incubator/setup-miniconda@v4 # or pin to hash with: # ... your options channels: pypdfium2-team,bblanchon channel-priority: strict ``` -------------------------------- ### Get Image Filters Source: https://pypdfium2.readthedocs.io/en/stable/_modules/pypdfium2/_helpers/pageobjects.html Retrieves a list of filters applied to the image stream. Simple filters can be optionally excluded. ```python 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 ``` -------------------------------- ### Initialize PdfDocument Source: https://pypdfium2.readthedocs.io/en/stable/_modules/pypdfium2/_helpers/document.html Initializes a PdfDocument instance. It handles various input types for the PDF, including file paths, bytes, and raw PDFium document handles. It also manages passwords for encrypted PDFs and ensures proper resource closure. ```python 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, byte stream, or raw PDFium document handle. A byte stream is defined as an object that implements ``seek() tell() read() readinto()``. 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) ``` -------------------------------- ### classmethod new_foreign(_width_ , _height_ , _format_ , _rev_byteorder =False_, _force_packed =False_) Source: https://pypdfium2.readthedocs.io/en/stable/python_api.html Create a new bitmap using `FPDFBitmap_CreateEx()`, with a buffer allocated by PDFium. Allows specifying if the buffer should be packed. ```APIDOC classmethod new_foreign(_width_ , _height_ , _format_ , _rev_byteorder =False_, _force_packed =False_)[source] Create a new bitmap using `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 `new_native()`. ```