### Install pypdfium2 from source with implicit pre-built binary Source: https://pypdfium2.readthedocs.io/en/v4/readme This command installs pypdfium2 from the local source directory. When executed, it implicitly downloads a pre-built PDFium binary from `pdfium-binaries` and bundles it into the pypdfium2 package during the installation process. ```bash # In the pypdfium2/ directory python -m pip install -v . ``` -------------------------------- ### Install pypdfium2 from source with pre-built PDFium Source: https://pypdfium2.readthedocs.io/en/stable/readme Installs pypdfium2 directly from the local source directory. This method implicitly downloads a pre-built PDFium binary from `pdfium-binaries` and bundles it into the pypdfium2 package during installation, simplifying the build process. ```Shell python -m pip install -v . ``` -------------------------------- ### Verify pypdfium2 Conda installation channels and sources Source: https://pypdfium2.readthedocs.io/en/v4/readme Provides commands to verify the origin channels of installed `pypdfium2` and `pdfium-binaries` packages using `conda list --show-channel-urls`. It also shows how to inspect the global Conda channel configuration with `conda config --show-sources` to confirm correct channel setup. ```bash conda list --show-channel-urls "pypdfium2|pdfium-binaries" conda config --show-sources ``` -------------------------------- ### Install pypdfium2 from PyPI Source: https://pypdfium2.readthedocs.io/en/v4/readme This command installs the pypdfium2 library from the Python Package Index (PyPI) using pip. It's the recommended and easiest method, utilizing a pre-built wheel package for straightforward installation. ```bash python -m pip install -U pypdfium2 ``` -------------------------------- ### Configure pypdfium2 Binary Selection via $PDFIUM_PLATFORM Source: https://pypdfium2.readthedocs.io/en/stable/readme Defines which Pdfium binary to include during setup, allowing specification of platform, V8 support, and version. This environment variable provides fine-grained control over the embedded Pdfium library. ```APIDOC $PDFIUM_PLATFORM: Configure Pdfium binary selection Format: [$PLATFORM][-v8][:$VERSION] [] = optional segments, $CAPS = variables Parameters: $PLATFORM: - auto: Detects host platform and selects corresponding binary. - explicit_platform_id (e.g., linux_x64, darwin_arm64): Uses binaries for the specified platform. - system: Binds against system-provided Pdfium; requires explicit $VERSION for matching bindings. - sourcebuild: Uses binaries from data/sourcebuild/ (assumes prior sourcebuild.py run). - sdist: Excludes platform-dependent files for source distribution. Note: 'sourcebuild' and 'sdist' are standalone and cannot be followed by other specifiers. -v8: (Optional) If present, uses V8 (JavaScript) and XFA enabled Pdfium binaries. Otherwise, uses regular (non-V8) binaries. $VERSION: (Optional) If present, uses the specified pdfium-binaries release. Otherwise, uses the latest release. Prefix: prepared!: Prepend to install with existing platform files instead of generating on the fly. Value is used for metadata/file inclusion. Useful for isolated environments where ctypesgen is unavailable. Examples: auto auto:5975 auto-v8:5975 linux_x64 prepared!linux_x64 ``` -------------------------------- ### Install pypdfium2 Helpers via Conda with Temporary Channels Source: https://pypdfium2.readthedocs.io/en/stable/readme This command installs 'pypdfium2_helpers' using Conda by temporarily overriding existing channel configurations. It specifies the required channels directly in the install command, suitable for one-off installations or specific environment setups. ```Bash conda install pypdfium2-team::pypdfium2_helpers --override-channels -c pypdfium2-team -c bblanchon -c defaults ``` -------------------------------- ### Install pypdfium2 from source with self-built PDFium binary Source: https://pypdfium2.readthedocs.io/en/v4/readme These commands facilitate installing pypdfium2 by first building the PDFium library from source, which can be a lengthy process. Subsequently, pypdfium2 is installed from its source, configured to link against the newly self-built PDFium binary by setting the `PDFIUM_PLATFORM` environment variable. ```bash python setupsrc/pypdfium2_setup/build_pdfium.py PDFIUM_PLATFORM="sourcebuild" python -m pip install -v . ``` -------------------------------- ### Install pypdfium2 from PyPI Source: https://pypdfium2.readthedocs.io/en/stable/readme Installs the pypdfium2 library using pip from the Python Package Index (PyPI). This method is recommended as it uses a pre-built wheel package, offering the easiest and most straightforward installation experience. ```Shell python -m pip install -U pypdfium2 ``` -------------------------------- ### Install pypdfium2 from source with system-provided PDFium binary Source: https://pypdfium2.readthedocs.io/en/v4/readme This command installs pypdfium2 from its source, instructing it to link against an external, system-provided PDFium library. It requires substituting `$PDFIUM_VER` with the exact build version of the system PDFium for ensuring ABI compatibility and correct binding generation. ```bash PDFIUM_PLATFORM="system:$PDFIUM_VER" python -m pip install -v . ``` -------------------------------- ### Clone pypdfium2 repository for source installation Source: https://pypdfium2.readthedocs.io/en/v4/readme These commands clone the pypdfium2 Git repository from GitHub and navigate into the project directory. This is the essential first step for any source-based installation, allowing access to the project's build scripts and files. ```bash git clone "https://github.com/pypdfium2-team/pypdfium2.git" cd pypdfium2/ ``` -------------------------------- ### Final installation of pypdfium2 with caller-provided data Source: https://pypdfium2.readthedocs.io/en/v4/readme This command performs the ultimate installation of pypdfium2 from source after all custom components, such as bindings, version information, and optionally a custom binary, have been prepared. The `--no-build-isolation` flag is used for specific build environments, and `PDFIUM_PLATFORM` is set to indicate a pre-prepared build. ```bash PDFIUM_PLATFORM='prepared!$MY_PLATFORM:$PDFIUM_BUILD' python -m pip install --no-build-isolation -v . ``` -------------------------------- ### Execute pypdfium2 source build script Source: https://pypdfium2.readthedocs.io/en/stable/readme Runs the `sourcebuild.py` script located within the pypdfium2 setup directory. This script is responsible for compiling PDFium from source, which can be a time-consuming process due to PDFium's bundled toolchain and dependencies. Use `--help` to list available build options. ```Shell python setupsrc/pypdfium2_setup/sourcebuild.py ``` -------------------------------- ### Analyze PDFs with pypdfium2 CLI and find Command Source: https://pypdfium2.readthedocs.io/en/stable/readme These examples demonstrate how to use the pypdfium2 command-line interface in conjunction with the `find` command to process multiple PDF files. Example A extracts image objects from PDFs, while Example B parses the table of contents, showcasing batch processing capabilities. ```bash # Example A: Analyse PDF images (in the current working directory) find . -name '*.pdf' -exec bash -c "echo \"{}\" && pypdfium2 pageobjects \"{}\" --filter image" \; # Example B: Parse PDF table of contents find . -name '*.pdf' -exec bash -c "echo \"{}\" && pypdfium2 toc \"{}\"" \; ``` -------------------------------- ### Install pypdfium2 with system-level PDFium Source: https://pypdfium2.readthedocs.io/en/stable/readme Installs pypdfium2 by configuring it to link against an existing external system-level PDFium library. It requires substituting `$PDFIUM_VER` with the exact version of the system's PDFium build to ensure ABI compatibility and proper binding generation. ```Shell PDFIUM_PLATFORM="system:$PDFIUM_VER" python -m pip install -v . ``` -------------------------------- ### Install pypdfium2 with permanent Conda channel configuration Source: https://pypdfium2.readthedocs.io/en/v4/readme Provides commands to permanently add `bblanchon` and `pypdfium2-team` channels to Conda configuration, set strict channel priority, and then install `pypdfium2_helpers`. This setup ensures `conda update` includes pypdfium2 by default and prevents accidental replacement from other channels. ```bash conda config --add channels bblanchon conda config --add channels pypdfium2-team conda config --set channel_priority strict conda install pypdfium2-team::pypdfium2_helpers ``` -------------------------------- ### Build and Install pypdfium2 from Source with Pip Source: https://pypdfium2.readthedocs.io/en/stable/readme This script demonstrates how to build pypdfium2 from source, copy the compiled binary, and then install it using pip. It utilizes environment variables for versioning and platform specification, and includes common pip options for debugging and development. ```Bash "minor": $PDFIUM_MINOR, "build": $PDFIUM_BUILD, "patch": $PDFIUM_PATCH, "n_commits": $POST_TAG_COMMIT_COUNT, "hash": $POST_TAG_HASH, "origin": "$ORIGIN", "flags": [$MY_FLAGS] } END # optional: copy in a binary if bundling cp "$BINARY_PATH" src/pypdfium2_raw/libpdfium.so # Finally, install # set $MY_PLATFORM to "system" if building against system pdfium (not bundled), "auto", "sourcebuild" or the platform name otherwise. PDFIUM_PLATFORM='prepared!$MY_PLATFORM:$PDFIUM_BUILD' python -m pip install --no-build-isolation -v . ``` -------------------------------- ### Render PDF Page to Bitmap and Get Buffer with pypdfium2 Source: https://pypdfium2.readthedocs.io/en/stable/readme This comprehensive example demonstrates how to load a PDF document, retrieve its first page, and render it onto a bitmap using `pypdfium2`'s raw API. It covers calculating page dimensions, creating a bitmap with optional alpha, filling it with a background color, and finally rendering the page with specified flags. The snippet concludes by obtaining a pointer to the rendered bitmap's buffer, which can then be used to create a PIL image or other image formats. ```Python import math import ctypes import os.path import PIL.Image import pypdfium2.raw as pdfium_c # Load the document filepath = os.path.abspath("tests/resources/render.pdf") pdf = pdfium_c.FPDF_LoadDocument((filepath+"\x00").encode("utf-8"), None) # Check page count to make sure it was loaded correctly page_count = pdfium_c.FPDF_GetPageCount(pdf) assert page_count >= 1 # Load the first page and get its dimensions page = pdfium_c.FPDF_LoadPage(pdf, 0) width = math.ceil(pdfium_c.FPDF_GetPageWidthF(page)) height = math.ceil(pdfium_c.FPDF_GetPageHeightF(page)) # Create a bitmap # (Note, pdfium is faster at rendering transparency if we use BGRA rather than BGRx) use_alpha = pdfium_c.FPDFPage_HasTransparency(page) bitmap = pdfium_c.FPDFBitmap_Create(width, height, int(use_alpha)) # Fill the whole bitmap with a white background # The color is given as a 32-bit integer in ARGB format (8 bits per channel) pdfium_c.FPDFBitmap_FillRect(bitmap, 0, 0, width, height, 0xFFFFFFFF) # Store common rendering arguments render_args = ( bitmap, # the bitmap page, # the page # positions and sizes are to be given in pixels and may exceed the bitmap 0, # left start position 0, # top start position width, # horizontal size height, # vertical size 0, # rotation (as constant, not in degrees!) pdfium_c.FPDF_LCD_TEXT | pdfium_c.FPDF_ANNOT, # rendering flags, combined with binary or ) # Render the page pdfium_c.FPDF_RenderPageBitmap(*render_args) # Get a pointer to the first item of the buffer buffer_ptr = pdfium_c.FPDFBitmap_GetBuffer(bitmap) ``` -------------------------------- ### Configure PDFium Binary Selection with $PDFIUM_PLATFORM Source: https://pypdfium2.readthedocs.io/en/v4/readme Details the `$PDFIUM_PLATFORM` environment variable for controlling which PDFium binary is used during `pypdfium2` setup. It covers platform detection, explicit platform specification, system binding, source build integration, source distribution, V8/XFA support, and versioning. ```APIDOC $PDFIUM_PLATFORM: Defines which binary to include on setup. Format Spec: [$PLATFORM][-v8][:$VERSION] Parameters: $PLATFORM: - auto: Detects host platform and selects corresponding binary. - Explicit platform identifier (e.g., linux_x64, darwin_arm64): Uses binaries for the requested platform. - system: Binds against system-provided pdfium; requires explicit version for binding generation. - sourcebuild: Takes binaries from data/sourcebuild/, assuming prior build_pdfium.py run. - sdist: No platform-dependent files included (for source distribution). (Note: sourcebuild and sdist are standalone, cannot be followed by additional specifiers.) -v8: - If given, uses V8 (JavaScript) and XFA enabled pdfium binaries. - Otherwise, uses regular (non-V8) binaries. $VERSION: - If given, uses the specified pdfium-binaries release. - Otherwise, uses the latest one. Special Prefix: prepared!: Prepend to install with existing platform files instead of generating on the fly. - Value used for metadata/file inclusion. - Useful for isolated environments (e.g., conda) where ctypesgen is unavailable but reference bindings are not desired. ``` -------------------------------- ### Install pypdfium2 from source with self-built PDFium Source: https://pypdfium2.readthedocs.io/en/stable/readme Installs pypdfium2 from the local source directory, leveraging a PDFium binary that has been self-built. This is achieved by setting the `PDFIUM_PLATFORM` environment variable to `sourcebuild` before executing the pip installation command, ensuring the custom-built binary is used. ```Shell PDFIUM_PLATFORM="sourcebuild" python -m pip install -v . ``` -------------------------------- ### Install pypdfium2 with symlinked system PDFium Source: https://pypdfium2.readthedocs.io/en/stable/readme Installs pypdfium2 using a system-level PDFium binary that has been made accessible via a symbolic link from a non-standard location (e.g., LibreOffice). Similar to other system-level installations, `$PDFIUM_VER` must be correctly specified to match the version of the symlinked PDFium build. ```Shell PDFIUM_PLATFORM="system:$PDFIUM_VER" python -m pip install -v . ``` -------------------------------- ### Render PDF Page to PIL Image with PDFium Source: https://pypdfium2.readthedocs.io/en/v4/readme Provides a comprehensive example of how to load a PDF document, access its first page, create a bitmap, render the page onto the bitmap with specified rendering flags, and finally prepare the bitmap's buffer for conversion into a PIL (Pillow) image in RGBA format. ```Python import math import ctypes import os.path import PIL.Image import pypdfium2.raw as pdfium_c # Load the document filepath = os.path.abspath("tests/resources/render.pdf") pdf = pdfium_c.FPDF_LoadDocument((filepath+"\x00").encode("utf-8"), None) # Check page count to make sure it was loaded correctly page_count = pdfium_c.FPDF_GetPageCount(pdf) assert page_count >= 1 # Load the first page and get its dimensions page = pdfium_c.FPDF_LoadPage(pdf, 0) width = math.ceil(pdfium_c.FPDF_GetPageWidthF(page)) height = math.ceil(pdfium_c.FPDF_GetPageHeightF(page)) # Create a bitmap # (Note, pdfium is faster at rendering transparency if we use BGRA rather than BGRx) use_alpha = pdfium_c.FPDFPage_HasTransparency(page) bitmap = pdfium_c.FPDFBitmap_Create(width, height, int(use_alpha)) # Fill the whole bitmap with a white background # The color is given as a 32-bit integer in ARGB format (8 bits per channel) pdfium_c.FPDFBitmap_FillRect(bitmap, 0, 0, width, height, 0xFFFFFFFF) # Store common rendering arguments render_args = ( bitmap, # the bitmap page, # the page # positions and sizes are to be given in pixels and may exceed the bitmap 0, # left start position 0, # top start position width, # horizontal size height, # vertical size 0, # rotation (as constant, not in degrees!) pdfium_c.FPDF_LCD_TEXT | pdfium_c.FPDF_ANNOT, # rendering flags, combined with binary or ) # Render the page pdfium_c.FPDF_RenderPageBitmap(*render_args) # Get a pointer to the first item of the buffer buffer_ptr = pdfium_c.FPDFBitmap_GetBuffer(bitmap) # Re-interpret the pointer to encompass the whole buffer buffer_ptr = ctypes.cast(buffer_ptr, ctypes.POINTER(ctypes.c_ubyte * (width * height * 4))) ``` -------------------------------- ### Clone pypdfium2 source repository Source: https://pypdfium2.readthedocs.io/en/stable/readme Clones the official pypdfium2 repository from GitHub to obtain the source code. After cloning, the command changes the current directory into the newly created `pypdfium2/` folder, preparing the environment for source-based installations. ```Shell git clone "https://github.com/pypdfium2-team/pypdfium2.git" cd pypdfium2/ ``` -------------------------------- ### Open PDF document and get basic info with pypdfium2 Source: https://pypdfium2.readthedocs.io/en/v4/readme Demonstrates how to open a PDF file using the `PdfDocument` helper class. It supports file paths, bytes, and byte buffers. The snippet also shows how to retrieve the PDF standard version, count the total number of pages, and load a specific page by its index. ```python pdf = pdfium.PdfDocument("./path/to/document.pdf") version = pdf.get_version() # get the PDF standard version n_pages = len(pdf) # get the number of pages in the document page = pdf[0] # load a page ``` -------------------------------- ### Configure Conda Channels in GitHub Actions Workflow Source: https://pypdfium2.readthedocs.io/en/stable/readme This YAML configuration demonstrates how to set up Conda channels and channel priority within a GitHub Actions workflow using the `conda-incubator/setup-miniconda@v3` action. It ensures consistent environment setup for CI/CD. ```YAML - name: ... uses: conda-incubator/setup-miniconda@v3 with: # ... your options channels: pypdfium2-team,bblanchon channel-priority: strict ``` -------------------------------- ### Import pypdfium2 library Source: https://pypdfium2.readthedocs.io/en/stable/readme Imports the pypdfium2 library, aliasing it as `pdfium` for convenient access to its functionalities. ```python import pypdfium2 as pdfium ``` -------------------------------- ### Importing pypdfium2 Raw API and Internal Helpers Source: https://pypdfium2.readthedocs.io/en/v4/readme Demonstrates how to import the raw PDFium C API bindings (`pypdfium2.raw`) and internal helper utilities (`pypdfium2.internal`) for direct low-level interaction with the PDFium library. ```python import pypdfium2.raw as pdfium_c import pypdfium2.internal as pdfium_i ``` -------------------------------- ### Install pypdfium2 with temporary Conda channel configuration Source: https://pypdfium2.readthedocs.io/en/v4/readme Demonstrates an alternative installation method for `pypdfium2_helpers` using temporary channel configuration. The `--override-channels` and `-c` flags allow specifying channels directly for a single `conda install` command without modifying global or environment-specific settings. ```bash conda install pypdfium2-team::pypdfium2_helpers --override-channels -c pypdfium2-team -c bblanchon -c defaults ``` -------------------------------- ### Upload pypdfium2 Packages to PyPI Source: https://pypdfium2.readthedocs.io/en/stable/readme These commands use `twine` to first validate the built packages in the `dist/` directory and then upload them to the Python Package Index (PyPI). This step makes the new release available for public installation, interactively asking for credentials. ```bash twine check dist/* twine upload dist/* ``` -------------------------------- ### Control pypdfium2 Module Inclusion with $PYPDFIUM_MODULES Source: https://pypdfium2.readthedocs.io/en/v4/readme Explains the `$PYPDFIUM_MODULES` environment variable, which allows specifying which `pypdfium2` modules (e.g., `raw`, `helpers`) should be included during installation, enabling modular packaging. ```APIDOC $PYPDFIUM_MODULES: Defines the pypdfium2 modules to include. Format: [module1,module2,...] (e.g., raw,helpers) Usage: - Allows packagers to decouple raw bindings and helpers. - Relevant when packaging against system pdfium. - Enables installing only specific modules (e.g., only raw, or only helpers with a custom raw module). Effect: - Metadata adapts dynamically based on included modules. ``` -------------------------------- ### Control pypdfium2 Module Inclusion via $PYPDFIUM_MODULES Source: https://pypdfium2.readthedocs.io/en/stable/readme Defines which pypdfium2 modules (raw bindings, helpers) to include. This allows packagers to decouple components or install only specific parts of the library based on their needs. ```APIDOC $PYPDFIUM_MODULES: Define modules to include Format: [raw,helpers] (comma-separated list of modules) Purpose: - Allows packagers to decouple raw bindings and helpers. - Enables installation of only the raw module, only helpers, or helpers with a custom raw module. Example: $PYPDFIUM_MODULES=raw,helpers ``` -------------------------------- ### Install pypdfium2 Helpers via Conda with Permanent Channels Source: https://pypdfium2.readthedocs.io/en/stable/readme This command sequence configures Conda to permanently add the 'bblanchon' and 'pypdfium2-team' channels, sets strict channel priority, and then installs the 'pypdfium2_helpers' package. This is the recommended approach for consistent updates. ```Bash conda config --add channels bblanchon conda config --add channels pypdfium2-team conda config --set channel_priority strict conda install pypdfium2-team::pypdfium2_helpers ``` -------------------------------- ### Import pypdfium2 library Source: https://pypdfium2.readthedocs.io/en/v4/readme Imports the pypdfium2 library, aliasing it as 'pdfium' for convenience, which is a common practice for this library. ```python import pypdfium2 as pdfium ``` -------------------------------- ### Verify Conda Package Sources and Channel Configuration Source: https://pypdfium2.readthedocs.io/en/stable/readme These commands allow users to verify the source channels of installed pypdfium2 packages and inspect the global Conda channel configuration. This is crucial for debugging installation issues and ensuring packages are from expected sources. ```Bash conda list --show-channel-urls "pypdfium2|pdfium-binaries" conda config --show-sources ``` -------------------------------- ### Override pypdfium2 Bindings Generation via $PDFIUM_BINDINGS Source: https://pypdfium2.readthedocs.io/en/stable/readme Allows overriding ctypesgen to use a reference bindings file. This is a convenience option for installation in environments where ctypesgen is unavailable, but it comes with important ABI safety warnings. ```APIDOC $PDFIUM_BINDINGS: Override ctypesgen and use reference bindings Value: reference Purpose: - Convenience option to install pypdfium2 from source when a working ctypesgen is not available in the install environment. Warning: - May not be ABI-safe. Ensure binary/bindings build headers match to avoid ABI issues. Example: $PDFIUM_BINDINGS=reference ``` -------------------------------- ### Git Commands for Committing Version File Source: https://pypdfium2.readthedocs.io/en/v4/readme These commands are used during a manual release process to stage, commit, and push changes made to the version file, typically after incrementing the project version. ```Shell git add src/pypdfium2/version.py git commit -m "increment version" git push ``` -------------------------------- ### pypdfium2 Custom Build Version File Schema Source: https://pypdfium2.readthedocs.io/en/stable/readme Defines the schema for `src/pypdfium2_raw/version.json`, a configuration file used to store metadata about the PDFium build bundled with pypdfium2. This schema is vital for custom and offline installations, providing details like version numbers, git information, build origin, and feature flags. ```APIDOC version.json Schema: { "major": "integer", // The major version of the PDFium build. "minor": "integer", // The minor version of the PDFium build. "build": "integer", // The build number of the PDFium build. "patch": "integer", // The patch version of the PDFium build. "n_commits": "integer", // Number of commits since the last tag (git describe like). Use 0 for release commit. "hash": "string", // Git commit hash (git describe like). Use null for release commit. "origin": "string", // Identifier for the build, e.g., "$BUILDER", "$DISTNAME/$BUILDER", "system/$BUILDER", "system/$DISTNAME/$BUILDER". "flags": "string" // Comma-delimited list of PDFium feature flags (e.g., "V8", "XFA"). Can be empty. } ``` -------------------------------- ### Getting Array Output Parameters with FPDFDest_GetView Source: https://pypdfium2.readthedocs.io/en/stable/readme This example illustrates how to handle array output parameters from a PDFium function like `FPDFDest_GetView`. It demonstrates initializing a `ctypes.c_ulong` for the number of parameters and a C array of `FS_FLOAT` for coordinates, then converting the C array to a Python list, truncating it based on the actual number of elements 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) # Convert the C array to a Python list and cut it down to the actual number of coordinates view_pos = list(view_pos)[:n_params.value] ``` -------------------------------- ### Retrieving Integer Output Parameters with ctypes.c_int Source: https://pypdfium2.readthedocs.io/en/stable/readme This example demonstrates how to retrieve an integer output parameter from a C function using `ctypes.c_int`. It shows the initialization of a `c_int` object, passing it by reference to `FPDF_GetFileVersion`, and then accessing its `value` attribute to get the Python integer, handling success/failure based on the function's return code. ```Python # Initialise an integer object (defaults to 0) c_version = ctypes.c_int() # Let the function assign a value to the c_int object, and capture its return code (True for success, False for failure) ok = pdfium_c.FPDF_GetFileVersion(pdf, c_version) # If successful, get the Python int by accessing the `value` attribute of the c_int object # Otherwise, set the variable to None (in other cases, it may be desired to raise an exception instead) version = c_version.value if ok else None ``` -------------------------------- ### Save PDF document to file Source: https://pypdfium2.readthedocs.io/en/stable/readme Shows how to save the current `PdfDocument` object to a specified file path. The `version` parameter allows setting the PDF standard version for the output file, for example, PDF 1.7. ```python pdf.save("output.pdf", version=17) ``` -------------------------------- ### Build pypdfium2 Packages Locally Source: https://pypdfium2.readthedocs.io/en/stable/readme These Python scripts are executed to build the project packages. `update.py` downloads necessary binaries, and `craft.py` builds platform-specific wheel packages and a source distribution, preparing them for PyPI upload. ```python python setupsrc/pypdfium2_setup/update.py python setupsrc/pypdfium2_setup/craft.py ``` -------------------------------- ### Process Multiple PDFs with pypdfium2 CLI using find Source: https://pypdfium2.readthedocs.io/en/v4/readme These `find` commands demonstrate how to process multiple PDF files in a directory using the `pypdfium2` command-line interface. Example A analyzes PDF images by filtering page objects, while Example B parses the table of contents for each PDF found, showcasing batch processing capabilities. ```bash # Example A: Analyse PDF images (in the current working directory) find . -name '*.pdf' -exec bash -c "echo \"{}\" && pypdfium2 pageobjects \"{}\" --filter image" \; # Example B: Parse PDF table of contents find . -name '*.pdf' -exec bash -c "echo \"{}\" && pypdfium2 toc \"{}\"" \; ``` -------------------------------- ### ctypes Binding Declaration for FPDF_LoadDocument Source: https://pypdfium2.readthedocs.io/en/v4/readme Provides an example of how a ctypes binding for a C function like `FPDF_LoadDocument` is declared. This includes specifying argument types (`argtypes`) and the return type (`restype`) for proper Python-C type conversion. ```python if _libs["pdfium"].has("FPDF_LoadDocument", "cdecl"): FPDF_LoadDocument = _libs["pdfium"].get("FPDF_LoadDocument", "cdecl") FPDF_LoadDocument.argtypes = [FPDF_STRING, FPDF_BYTESTRING] FPDF_LoadDocument.restype = FPDF_DOCUMENT ``` -------------------------------- ### Python Commands for Building PyPI Packages Source: https://pypdfium2.readthedocs.io/en/v4/readme These Python commands are executed to prepare the project for PyPI distribution. The first command downloads necessary PDFium binaries, and the second builds platform-specific wheel packages and a source distribution. ```Shell python setupsrc/pypdfium2_setup/update_pdfium.py python setupsrc/pypdfium2_setup/craft_packages.py pypi ``` -------------------------------- ### Save PDF document with pypdfium2 Source: https://pypdfium2.readthedocs.io/en/v4/readme Provides a simple example of how to save the currently open or created PDF document to a specified file path. It also demonstrates how to explicitly set the PDF standard version for the output file, in this case, to PDF 1.7. ```python pdf.save("output.pdf", version=17) ``` -------------------------------- ### Execute pypdfium2 Test Suite using Pytest Source: https://pypdfium2.readthedocs.io/en/stable/readme This command runs the pypdfium2 test suite using pytest. Users can pass `-sv` for more detailed output or set `$DEBUG_AUTOCLOSE=1` to get debugging information related to automatic object finalization during testing. ```shell ./run test ``` -------------------------------- ### Read PDF table of contents with pypdfium2 Source: https://pypdfium2.readthedocs.io/en/v4/readme Provides an example of how to access and iterate through the table of contents (TOC) of a PDF document. For each item in the TOC, it extracts and prints details such as its hierarchical level, state (collapsed/expanded), title, target page index, view mode, and position. ```python for item in pdf.get_toc(): state = "*" if item.n_kids == 0 else "-" if item.is_closed else "+" target = "?" if item.page_index is None else item.page_index+1 print( " " * item.level + "[%s] %s -> %s # %s %s" % ( state, item.title, target, item.view_mode, item.view_pos, ) ) ``` -------------------------------- ### Build pypdfium2 Documentation with Sphinx Source: https://pypdfium2.readthedocs.io/en/v4/readme These commands are used to build the pypdfium2 API documentation. The first command utilizes `sphinx-build` to generate HTML documentation from source files located in `./docs/source`. The second command, `./run build`, is a short alias for the same build process, likely defined in a project-specific `run` script. ```bash sphinx-build -b html ./docs/source ./docs/build/html/ ./run build # short alias ``` -------------------------------- ### Reading C Memory Buffer from PDFium into Python with ctypes Source: https://pypdfium2.readthedocs.io/en/stable/readme This example demonstrates how to safely read data from a C memory buffer obtained from PDFium. It shows how to re-interpret a raw pointer using ctypes.cast() to create a Python-accessible ctypes array or an independent bytes copy. ```Python # (Assuming `bitmap` is an FPDF_BITMAP and `size` is the expected number of bytes in the buffer) buffer_ptr = pdfium_c.FPDFBitmap_GetBuffer(bitmap) buffer_ptr = ctypes.cast(buffer_ptr, ctypes.POINTER(ctypes.c_ubyte * size)) # Buffer as ctypes array (referencing the original buffer, will be unavailable as soon as the bitmap is destroyed) c_array = buffer_ptr.contents # Buffer as Python bytes (independent copy) data = bytes(c_array) ``` -------------------------------- ### Build pypdfium2 Documentation with Sphinx Source: https://pypdfium2.readthedocs.io/en/stable/readme These commands demonstrate how to build the pypdfium2 API documentation using Sphinx. The first command builds HTML documentation from source, while the second is a short alias for the same operation, facilitating local documentation generation. ```shell sphinx-build -b html ./docs/source ./docs/build/html/ ./run build # short alias ``` -------------------------------- ### Using ctypes Arrays for Structured Output (View Position) Source: https://pypdfium2.readthedocs.io/en/v4/readme Provides a concrete example of using a ctypes array (`FS_FLOAT * 4`) to capture multiple float values (e.g., view position coordinates) from a C function (`FPDFDest_GetView`) and converting the C array to a Python list. ```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) # Convert the C array to a Python list and cut it down to the actual number of coordinates view_pos = list(view_pos)[:n_params.value] ``` -------------------------------- ### Checking PDFium Object Identity with ctypes.addressof() Source: https://pypdfium2.readthedocs.io/en/stable/readme This example demonstrates how to determine if two PDFium objects are the same by comparing their underlying C memory addresses using ctypes.addressof(). This technique is essential for detecting circular references, such as in document outlines, where ctypes's object return behavior can be misleading. ```Python # (Assuming `pdf` is an FPDF_DOCUMENT) seen = set() bookmark = pdfium_c.FPDFBookmark_GetFirstChild(pdf, None) while bookmark: # bookmark is a pointer, so we need to use its `contents` attribute to get the object the pointer refers to # (otherwise we'd only get the memory address of the pointer itself, which would result in random behaviour) address = ctypes.addressof(bookmark.contents) if address in seen: break # circular reference detected else: seen.add(address) bookmark = pdfium_c.FPDFBookmark_GetNextSibling(pdf, bookmark) ``` -------------------------------- ### Create new PDF with empty A4 page using pypdfium2 Source: https://pypdfium2.readthedocs.io/en/v4/readme Demonstrates the process of initializing a new, empty PDF document from scratch. It then shows how to add a new page to this document, specifying its dimensions to create a standard A4-sized page. ```python pdf = pdfium.PdfDocument.new() width, height = (595, 842) page_a = pdf.new_page(width, height) ``` -------------------------------- ### Implement Custom File Access Callback for PDFium Source: https://pypdfium2.readthedocs.io/en/v4/readme Demonstrates how to provide a Python buffer to PDFium's C API for custom document loading. It shows the implementation of a `__call__` method for data transfer and the setup of the `FPDF_FILEACCESS` structure to enable PDFium to read from a Python file-like object. ```Python self.py_buffer = py_buffer def __call__(self, _, position, p_buf, size): # Write data from Python buffer into C buffer, as explained before buffer_ptr = ctypes.cast(p_buf, ctypes.POINTER(ctypes.c_char * size)) self.py_buffer.seek(position) self.py_buffer.readinto(buffer_ptr.contents) return 1 # non-zero return code for success # (Assuming py_buffer is a Python file buffer, e. g. io.BufferedReader) # Get the length of the buffer py_buffer.seek(0, os.SEEK_END) file_len = py_buffer.tell() py_buffer.seek(0) # Set up an interface structure for custom file access fileaccess = pdfium_c.FPDF_FILEACCESS() fileaccess.m_FileLen = file_len # Assign the callback, wrapped in its CFUNCTYPE fileaccess.m_GetBlock = type(fileaccess.m_GetBlock)( _reader_class(py_buffer) ) # Finally, load the document pdf = pdfium_c.FPDF_LoadCustomDocument(fileaccess, None) ``` -------------------------------- ### Extracting Bounded Text from PDF with pypdfium2 and ctypes Source: https://pypdfium2.readthedocs.io/en/stable/readme This example demonstrates how to extract text within specified rectangular boundaries from a PDF page using pypdfium2's FPDFText_GetBoundedText. It involves calculating buffer sizes, handling UTF-16LE encoding, and managing ctypes pointers for efficient data transfer. ```Python # (Assuming `textpage` is an FPDF_TEXTPAGE and the boundary variables are set) # Store common arguments for the two calls args = (textpage, left, top, right, bottom) # First call to get the required number of units (not bytes!) - a possible null terminator is not included n_chars = pdfium_c.FPDFText_GetBoundedText(*args, None, 0) # If no characters were found, return an empty string if n_chars <= 0: return "" # Calculate the required number of bytes (encoding: UTF-16LE again) # The function signature uses c_ushort, so 1 unit takes sizeof(c_ushort) == 2 bytes n_bytes = 2 * n_chars # Initialise the output buffer - this function can work without null terminator, so skip it buffer = ctypes.create_string_buffer(n_bytes) # Re-interpret the type from char to unsigned short* as required by the function buffer_ptr = ctypes.cast(buffer, ctypes.POINTER(ctypes.c_ushort)) # Second call with the actual buffer pdfium_c.FPDFText_GetBoundedText(*args, buffer_ptr, n_chars) # Decode to string (You may want to pass `errors="ignore"` to skip possible errors in the PDF's encoding) text = buffer.raw.decode("utf-16-le") ``` -------------------------------- ### Copy PDFium binary for pypdfium2 bundling Source: https://pypdfium2.readthedocs.io/en/v4/readme This optional command copies a pre-compiled PDFium binary from a user-specified path (`$BINARY_PATH`) into the `src/pypdfium2_raw/` directory. This step is necessary only if the user intends to bundle a custom or pre-existing PDFium binary directly within the pypdfium2 package. ```bash cp "$BINARY_PATH" src/pypdfium2_raw/libpdfium.so ``` -------------------------------- ### pypdfium2 Main Help and Subcommands Overview Source: https://pypdfium2.readthedocs.io/en/stable/shell_api Provides an overview of the pypdfium2 command-line interface, listing available subcommands for various PDF operations and general options like help and version. ```APIDOC usage: pypdfium2 [-h] [--version] {arrange,attachments,extract-images,extract-text,imgtopdf,pageobjects,pdfinfo,render,tile,toc} ... Command line interface to the pypdfium2 library (Python binding to PDFium) positional arguments: {arrange,attachments,extract-images,extract-text,imgtopdf,pageobjects,pdfinfo,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 render rasterize pages tile tile pages (N-up) toc print table of contents options: -h, --help show this help message and exit --version, -v show program's version number and exit ``` -------------------------------- ### Extracting Bounded Text from PDFPage using ctypes Source: https://pypdfium2.readthedocs.io/en/v4/readme This example illustrates the process of extracting text within specified rectangular boundaries from a PDF text page. It involves two calls to `FPDFText_GetBoundedText`: first to determine the required buffer size for the text, and then to retrieve the actual UTF-16LE encoded text into a `ctypes` buffer. ```Python # (Assuming `textpage` is an FPDF_TEXTPAGE and the boundary variables are set) # Store common arguments for the two calls args = (textpage, left, top, right, bottom) # First call to get the required number of characters (not bytes!) - a possible null terminator is not included n_chars = pdfium_c.FPDFText_GetBoundedText(*args, None, 0) # If no characters were found, return an empty string if n_chars <= 0: return "" # Calculate the required number of bytes (UTF-16LE encoding again) n_bytes = 2 * n_chars # Initialise the output buffer - this function can work without null terminator, so skip it buffer = ctypes.create_string_buffer(n_bytes) # Re-interpret the type from char to unsigned short as required by the function buffer_ptr = ctypes.cast(buffer, ctypes.POINTER(ctypes.c_ushort)) # Second call with the actual buffer pdfium_c.FPDFText_GetBoundedText(*args, buffer_ptr, n_chars) # Decode to string (You may want to pass `errors="ignore"` to skip possible errors in the PDF's encoding) text = buffer.raw.decode("utf-16-le") ``` -------------------------------- ### Embed JPEG image into PDF with pypdfium2 Source: https://pypdfium2.readthedocs.io/en/v4/readme Illustrates how to create a new PDF document and embed an existing JPEG image into it. The example covers loading the image, retrieving its dimensions, creating a transformation matrix to scale the image, and finally inserting the image object onto a newly created page within the PDF. ```python pdf = pdfium.PdfDocument.new() image = pdfium.PdfImage.new(pdf) image.load_jpeg("./tests/resources/mona_lisa.jpg") width, height = image.get_size() matrix = pdfium.PdfMatrix().scale(width, height) image.set_matrix(matrix) page = pdf.new_page(width, height) page.insert_obj(image) page.gen_content() ``` -------------------------------- ### Symlink LibreOffice PDFium library for pypdfium2 Source: https://pypdfium2.readthedocs.io/en/stable/readme Creates a symbolic link from the LibreOffice PDFium shared library (`libpdfiumlo.so`) to a standard system library path (`/usr/local/lib/libpdfium.so`). This allows pypdfium2 to discover and utilize the PDFium library provided by LibreOffice, especially useful on platforms where PDFium is not typically packaged independently. This operation usually requires root privileges. ```Shell sudo ln -s /usr/lib/libreoffice/program/libpdfiumlo.so /usr/local/lib/libpdfium.so ``` -------------------------------- ### pypdfium2 Command-Line Interface Overview Source: https://pypdfium2.readthedocs.io/en/v4/shell_api Provides the top-level help for the pypdfium2 CLI, listing all available subcommands (e.g., `arrange`, `attachments`, `render`) and global options like `--help` and `--version`. It serves as a quick reference for the CLI's capabilities. ```APIDOC usage: pypdfium2 [-h] [--version] {arrange,attachments,extract-images,extract-text,imgtopdf,pageobjects,pdfinfo,render,tile,toc} ... Command line interface to the pypdfium2 library (Python binding to PDFium) positional arguments: {arrange,attachments,extract-images,extract-text,imgtopdf,pageobjects,pdfinfo,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 page objects pdfinfo print info on document and pages render rasterize pages tile tile pages (N-up) toc print table of contents options: -h, --help show this help message and exit --version, -v show program's version number and exit ```