### Native Build with Clang Setup Source: https://github.com/pypdfium2-team/pypdfium2/blob/main/README.md Prepare the system for building with Clang by installing LLVM/LLD and creating necessary symbolic links for the Clang compiler. This is an alternative to using GCC. ```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" ``` -------------------------------- ### Install pypdfium2 with System PDFium Source: https://github.com/pypdfium2-team/pypdfium2/blob/main/README.md Use this command to install pypdfium2, instructing it to find and bind against a system-provided PDFium shared library. Environment variables can be used to guide the search for the library, headers, and version information. ```bash PDFIUM_PLATFORM="system-search" python -m pip install -v . ``` -------------------------------- ### Toolchained Build Example Source: https://github.com/pypdfium2-team/pypdfium2/blob/main/README.md Execute the toolchained build script and then install pypdfium2. This method uses Google's toolchain and may require significant time and disk space. ```bash # call build script with --help to list options python ./setupsrc/build_toolchained.py ``` ```bash PDFIUM_PLATFORM="sourcebuild" python -m pip install -v . ``` -------------------------------- ### Setup pypdfium2 with Caller-Provided Data Files Source: https://github.com/pypdfium2-team/pypdfium2/blob/main/README.md This bash script demonstrates the process of manually setting up pypdfium2 by providing your own data files. It covers selecting a target platform (sourcebuild or system), copying the PDFium DLL, generating bindings using ctypesgen, creating a version.json file, and installing pypdfium2. ```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" < Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. ``` -------------------------------- ### Parallel Strategy Selection Source: https://github.com/pypdfium2-team/pypdfium2/blob/main/docs/source/shell_api.md Choose the process start method for parallel rendering. 'fork' is discouraged due to stability issues. ```shell --parallel-strategy {spawn,forkserver,fork} ``` -------------------------------- ### Advanced cibuildwheel Configuration Source: https://github.com/pypdfium2-team/pypdfium2/blob/main/README.md An example of a more complex cibuildwheel command, specifying architecture, container engine, and enabling tests. ```bash CIBW_BUILD="cp314-musllinux_s390x" CIBW_ARCHS=s390x CIBW_CONTAINER_ENGINE=podman TEST_PDFIUM=1 cibuildwheel ``` -------------------------------- ### Install GN with Requirements Source: https://github.com/pypdfium2-team/pypdfium2/blob/main/README.md Install the correct GN version for PDFium using the provided requirements file. This ensures compatibility with PDFium's build scripts. ```bash python3 -m pip install -r req/gn.txt ``` -------------------------------- ### Get Bookmark Title String Source: https://github.com/pypdfium2-team/pypdfium2/blob/main/README.md Example of retrieving a bookmark's title. Requires two calls: first to determine buffer size, then to populate the buffer. The title is expected in UTF-16LE encoding and includes a NUL terminator. ```python # (Assuming `bookmark` is an FPDF_BOOKMARK) # First call to get the required number of bytes (not units!), including space for a NUL terminator n_bytes = pdfium_c.FPDFBookmark_GetTitle(bookmark, None, 0) # Initialise the output buffer buffer = ctypes.create_string_buffer(n_bytes) # Second call with the actual buffer pdfium_c.FPDFBookmark_GetTitle(bookmark, buffer, n_bytes) # Decode to string, cutting off the NUL terminator (encoding: UTF-16LE) title = decode(memoryview(buffer)[:n_bytes-2], "utf-16-le") ``` -------------------------------- ### Install pypdfium2 Helpers via Conda Source: https://github.com/pypdfium2-team/pypdfium2/blob/main/README.md Install the pypdfium2_helpers package using Conda after configuring the official channels. This command installs the package from the configured channels. ```bash conda install pypdfium2-team::pypdfium2_helpers ``` -------------------------------- ### Install pypdfium2 after Native Build Source: https://github.com/pypdfium2-team/pypdfium2/blob/main/README.md Install pypdfium2 after completing the native build process. This step makes the library available for use in your Python projects. ```bash # Install PDFIUM_PLATFORM="sourcebuild" python -m pip install -v . ``` -------------------------------- ### Native Build with Clang Source: https://github.com/pypdfium2-team/pypdfium2/blob/main/docs/source/readme.md Configure and build pypdfium2 using Clang. This involves installing LLVM/LLDB, setting up symbolic links for Clang's builtins, and then running the native build script. ```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 ``` -------------------------------- ### Native Build with GCC Source: https://github.com/pypdfium2-team/pypdfium2/blob/main/README.md Build pypdfium2 using the native build script with GCC as the compiler. Ensure all dependencies are installed beforehand. ```bash # Build with GCC python ./setupsrc/build_native.py --compiler gcc ``` -------------------------------- ### Add Conda Channels and Install pypdfium2 Helpers Source: https://github.com/pypdfium2-team/pypdfium2/blob/main/docs/source/readme.md Installs the pypdfium2 helper package by adding official channels to your Conda configuration. This method is encouraged for permanent channel management. ```bash conda config --add channels bblanchon conda config --add channels pypdfium2-team conda config --set channel_priority strict conda install pypdfium2-team::pypdfium2_helpers ``` -------------------------------- ### Basic BigInteger Arithmetic Example Source: https://github.com/pypdfium2-team/pypdfium2/blob/main/BUILD_LICENSES/v8_xfa/bigint.txt Demonstrates basic arithmetic operations with the BigInteger class, including initialization and multiplication. Requires including the 'BigIntegerLibrary.hh' header. ```C++ #include "BigIntegerLibrary.hh" BigInteger a = 65536; cout << (a * a * a * a * a * a * a * a); ``` -------------------------------- ### Install Android Termux Dependencies Source: https://github.com/pypdfium2-team/pypdfium2/blob/main/README.md Installs essential build dependencies for pypdfium2 on Android using the Termux package manager. ```bash pkg install gn ninja freetype littlecms libjpeg-turbo openjpeg libpng zlib libicu libtiff harfbuzz glib ``` -------------------------------- ### Display pypdfium2 Version Source: https://github.com/pypdfium2-team/pypdfium2/blob/main/docs/source/shell_api.md Use the `--version` flag to display the installed version of pypdfium2 and the underlying PDFium library. This is useful for verifying installation and compatibility. ```text $ pypdfium2 --version pypdfium2 5.11.0+5.g9df9188b@editable pdfium 151.0.7920.0 at /workspace/input/src/pypdfium2_raw/libpdfium.so ``` -------------------------------- ### Native Build Dependencies (Ubuntu 24.04) Source: https://github.com/pypdfium2-team/pypdfium2/blob/main/README.md Install necessary build tools and development libraries for the native build on Ubuntu 24.04. This includes GN, Ninja, and various PDFium dependencies. ```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 ``` -------------------------------- ### Configure Conda Channels in GitHub Workflow Source: https://github.com/pypdfium2-team/pypdfium2/blob/main/docs/source/readme.md Sets up Conda channels and priority within a GitHub Actions workflow using the setup-miniconda action. This ensures consistent environment setup for CI/CD. ```yaml steps: - name: ... uses: conda-incubator/setup-miniconda@v4 # or pin to hash with: # ... your options channels: pypdfium2-team,bblanchon channel-priority: strict ``` -------------------------------- ### PdfUnspHandler.setup Source: https://github.com/pypdfium2-team/pypdfium2/blob/main/docs/source/python_api.md Registers the unsupported feature handler with PDFium. This method can only be called once per session. It installs an exit function to keep the handler alive and optionally adds a default callback to log unsupported features. ```APIDOC ## PdfUnspHandler.setup(add_default=True) ### Description 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 [`PdfUnspHandler`](#pypdfium2._helpers.unsupported.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 [`handlers`](#pypdfium2._helpers.unsupported.PdfUnspHandler.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. ``` -------------------------------- ### Access Bitmap Buffer Source: https://github.com/pypdfium2-team/pypdfium2/blob/main/README.md Example of accessing the raw byte buffer of an FPDF_BITMAP. It involves getting a pointer from PDFium, casting it to a byte pointer, and then creating a ctypes array view or a Python bytes object. ```python # (Assuming `bitmap` is an FPDF_BITMAP and `size` is the expected number of bytes in the buffer) # FPDFBitmap_GetBuffer() has c_void_p as restype, which ctypes will auto-resolve to int or None buffer_ptrval = pdfium_c.FPDFBitmap_GetBuffer(bitmap) assert buffer_ptrval # make sure it's non-null # Get an actual pointer object so we can access .contents buffer_ptr = ctypes.cast(buffer_ptrval, ctypes.POINTER(ctypes.c_ubyte)) # Buffer as ctypes array (a view of the original buffer, will be unavailable as soon as the bitmap is destroyed) c_buffer = (ctypes.c_ubyte * size).from_address( ctypes.addressof(buffer_ptr.contents) ) # Buffer as Python bytes (independent copy) py_buffer = bytes(c_buffer) ``` -------------------------------- ### Cross-build PDFium with Toolchain Source: https://github.com/pypdfium2-team/pypdfium2/blob/main/README.md Demonstrates cross-compiling PDFium using its own toolchain, recommended for Linux architectures not natively supported by CI. ```bash # assuming cross-compilation dependencies are installed python setupsrc/build_toolchained.py --target-cpu arm PDFIUM_PLATFORM=sourcebuild CROSS_TAG="manylinux_2_17_armv7l" python -m build -wxn ``` -------------------------------- ### Image to PDF Conversion Help Source: https://github.com/pypdfium2-team/pypdfium2/blob/main/docs/source/shell_api.md Shows help for the `imgtopdf` command. This command is used to convert image files into a PDF document. ```shell $ pypdfium2 imgtopdf --help usage: pypdfium2 imgtopdf [-h] --output OUTPUT [--inline] images [images ...] Convert images to PDF positional arguments: images Input images options: -h, --help show this help message and exit --output, -o OUTPUT Target path for the new PDF --inline If JPEG, whether to use PDFium's inline loading function. ``` -------------------------------- ### Show Help for render Command Source: https://github.com/pypdfium2-team/pypdfium2/blob/main/docs/source/shell_api.md Use the --help flag to display usage information and available options for the render command. This command is used for rasterizing PDF pages into images. ```shell $ pypdfium2 render --help ``` -------------------------------- ### Import pypdfium2 Library Source: https://github.com/pypdfium2-team/pypdfium2/blob/main/README.md Import the necessary pypdfium2 libraries for use. This is the first step for most operations. ```python import pypdfium2 as pdfium import pypdfium2.raw as pdfium_c ``` -------------------------------- ### Initialize C Array for Output Parameters Source: https://github.com/pypdfium2-team/pypdfium2/blob/main/README.md Shows the general method for initializing C-style arrays using ctypes for output parameters. Includes 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 View Mode and Position from PDF Destination Source: https://github.com/pypdfium2-team/pypdfium2/blob/main/README.md Demonstrates getting the view mode and target position from a PDF destination object. It initializes a C array for coordinates and slices it to the actual number of values returned. ```python # (Assuming `dest` is an FPDF_DEST) n_params = ctypes.c_ulong() # Create a C array to store up to four coordinates view_pos = (pdfium_c.FS_FLOAT * 4)() view_mode = pdfium_c.FPDFDest_GetView(dest, n_params, view_pos) # Slice the array to the actual number of coordinates. This implicitly converts the C array to a Python list. view_pos = view_pos[:n_params.value] ``` -------------------------------- ### get_bitmap Source: https://github.com/pypdfium2-team/pypdfium2/blob/main/docs/source/python_api.md Gets a bitmap rasterization of the image. ```APIDOC ## get_bitmap(render=False, scale_to_original=True) ### Description Gets a bitmap rasterization of the image. ### Parameters #### Parameters - **render** (bool) - Optional - Whether the image should be rendered, thereby applying possible transform matrices and alpha masks. - **scale_to_original** (bool) - Optional - 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). ``` -------------------------------- ### Display pypdfium2 Main Help Source: https://github.com/pypdfium2-team/pypdfium2/blob/main/docs/source/shell_api.md Invoke pypdfium2 with the `--help` flag to view the main help message. This provides an overview of available subcommands and general usage instructions. ```text $ 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 `python3.14 -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 ``` -------------------------------- ### Build PyPI Packages Source: https://github.com/pypdfium2-team/pypdfium2/blob/main/README.md Build platform-specific wheel packages and a source distribution for PyPI upload using the 'just' build tool. This command prepares the distribution files. ```bash just packaging-pypi ``` -------------------------------- ### get_version Source: https://github.com/pypdfium2-team/pypdfium2/blob/main/docs/source/python_api.md Gets the PDF version of the document. ```APIDOC ## get_version() ### Description Gets the PDF version of the document. ### 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. ``` -------------------------------- ### PdfTextPage.get_charbox Source: https://github.com/pypdfium2-team/pypdfium2/blob/main/docs/source/python_api.md Gets the bounding box of a single character at a specified index. An option for a more comprehensive box is available. ```APIDOC ## PdfTextPage.get_charbox ### Description 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) - Optional - Get a more comprehensive box covering the entire font bounds, as opposed to the default tight box specific to the one character. Defaults to False. ### Returns Values for left, bottom, right and top in PDF canvas units. ### Return type float ``` -------------------------------- ### Build HTML Documentation Source: https://github.com/pypdfium2-team/pypdfium2/blob/main/README.md Render API documentation to HTML format using Sphinx. A short alias 'just docs-build' is available. ```bash sphinx-build -b html ./docs/source ./docs/build/html/ ``` ```bash just docs-build ``` -------------------------------- ### Bitmap Maker Options Source: https://github.com/pypdfium2-team/pypdfium2/blob/main/docs/source/shell_api.md Select the bitmap maker strategy for rendering. Options include native, foreign, foreign_packed, and foreign_simple. ```shell --bitmap-maker {native,foreign,foreign_packed,foreign_simple} ``` -------------------------------- ### Pageobjects Info Help Source: https://github.com/pypdfium2-team/pypdfium2/blob/main/docs/source/shell_api.md Displays help for the `pageobjects` command. Use this to get detailed information about objects within PDF pages. ```shell $ pypdfium2 pageobjects --help usage: pypdfium2 pageobjects [-h] [--password PASSWORD] [--pages PAGES] [--n-digits N_DIGITS] [--filter T [T ...]] [--max-depth MAX_DEPTH] [--info {pos,imginfo,text} [{pos,imginfo,text} ...]] input Print info on pageobjects 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 --filter T [T ...] Object types to include. Choices: ['?', 'text', 'path', 'image', 'shading', 'form'] --max-depth MAX_DEPTH Maximum recursion depth to consider when descending into Form XObjects. --info {pos,imginfo,text} [{pos,imginfo,text} ...] Object details to show. ``` -------------------------------- ### PdfObject.get_quad_points Source: https://github.com/pypdfium2-team/pypdfium2/blob/main/docs/source/python_api.md Gets the quadriliteral corner points of a page object. This is particularly useful for objects that have been transformed, providing a more accurate representation than a simple rectangle. ```APIDOC ## PdfObject.get_quad_points ### Description 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. ### Method `get_quad_points()` ### Returns Corner positions as (x, y) tuples, counter-clockwise from origin, i.e. bottom-left, bottom-right, top-right, top-left, in PDF page coordinates. ### Return type tuple[tuple[float*2] * 4] ``` -------------------------------- ### Native Build with Clang Execution Source: https://github.com/pypdfium2-team/pypdfium2/blob/main/README.md Execute the native build script using Clang as the compiler after setting up the necessary symbolic links. This allows for building with Clang. ```bash python ./setupsrc/build_native.py --compiler clang ``` -------------------------------- ### Get and Set Page Properties Source: https://github.com/pypdfium2-team/pypdfium2/blob/main/README.md Retrieve page dimensions and set the absolute rotation of a page. Page dimensions are in PDF canvas units. ```python # Get page dimensions in PDF canvas units (1pt->1/72in by default) width, height = page.get_size() # Set the absolute page rotation to 90° clockwise page.set_rotation(90) ``` -------------------------------- ### Show Help for pypdfium2 Arrange Command Source: https://github.com/pypdfium2-team/pypdfium2/blob/main/docs/source/shell_api.md Displays the help message for the 'arrange' command, outlining its usage and available options for rearranging and merging PDF pages. ```text $ 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 ``` -------------------------------- ### PdfTextSearcher.get_prev() Source: https://github.com/pypdfium2-team/pypdfium2/blob/main/docs/source/python_api.md Finds the previous occurrence of the searched text. Returns the start character index and count of the match, or None if the last occurrence has been passed. ```APIDOC ## PdfTextSearcher.get_prev() ### Description Returns the 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. ### Returns - (int, int) | None - A tuple containing the start index and count of the previous match, or None. ``` -------------------------------- ### Dark Background Sample Theme Source: https://github.com/pypdfium2-team/pypdfium2/blob/main/docs/source/shell_api.md Apply a dark background sample theme as the base for rendering. Explicit color parameters will override selectively. ```shell --sample-theme ``` -------------------------------- ### PdfTextSearcher.get_next() Source: https://github.com/pypdfium2-team/pypdfium2/blob/main/docs/source/python_api.md Finds the next occurrence of the searched text. Returns the start character index and count of the match, or None if the last occurrence has been passed. ```APIDOC ## PdfTextSearcher.get_next() ### Description Returns the start character index and count of the next occurrence, or None if the last occurrence was passed. ### Returns - (int, int) | None - A tuple containing the start index and count of the next match, or None. ```