Project Icon

pypdfium2

Python PDF处理库 支持渲染检查操作和创建

pypdfium2是Python 3的PDFium绑定库,实现PDF文档的渲染、检查、操作和创建。它提供辅助函数简化常见任务,支持多平台安装和预构建包。该库保留了PDFium/ctypes API访问,满足不同开发需求。

pypdfium2

Downloads

pypdfium2 is an ABI-level Python 3 binding to PDFium, a powerful and liberal-licensed library for PDF rendering, inspection, manipulation and creation.

It is built with ctypesgen and external PDFium binaries. The custom setup infrastructure provides a seamless packaging and installation process. A wide range of platforms is supported with pre-built packages.

pypdfium2 includes helpers to simplify common use cases, while the raw PDFium/ctypes API remains accessible as well.

Installation

  • From PyPI 🔗 (recommended)

    python -m pip install -U pypdfium2
    

    This will use a pre-built wheel package, the easiest way of installing pypdfium2.

  • From source 🔗

    • Dependencies:

      • System: git, C pre-processor (gcc/clang - alternatively, specify the command to envoke via $CPP)
      • Python: ctypesgen (pypdfium2-team fork), wheel, setuptools. Usually installed automatically.
    • Get the code

      git clone "https://github.com/pypdfium2-team/pypdfium2.git"
      cd pypdfium2/
      
    • With pre-built binary 🔗

      # In the pypdfium2/ directory
      python -m pip install -v .
      

      A binary is downloaded implicitly from pdfium-binaries and bundled into pypdfium2.

    • With self-built binary 🔗

      # call build script with --help to list options
      python setupsrc/pypdfium2_setup/build_pdfium.py
      PDFIUM_PLATFORM="sourcebuild" python -m pip install -v .
      

      Building PDFium may take a long time, as it comes with its bundled toolchain and deps, rather than taking them from the system.1 However, we can at least provide the --use-syslibs option to build against system-provided runtime libraries.

    • With system-provided binary 🔗

      # Substitute $PDFIUM_VER with the system pdfium's build version.
      # For ABI safety reasons, you'll want to make sure `$PDFIUM_VER` is correct and the bindings are rebuilt whenever system pdfium is updated.
      PDFIUM_PLATFORM="system:$PDFIUM_VER" python -m pip install -v .
      

      Link against external pdfium instead of bundling it. Note, this is basically a high-level convenience entry point to internal bindings generation, and intended for end users. Therefore it is less flexible, supporting only the "simple case" for now. For more sohpisticated use cases that need passing custom parameters to ctypesgen (e.g. runtime libdirs / headers / feature flags), consider caller-provided data files.

    • With caller-provided data files 🔗 (this is expected to work offline)
      # Call ctypesgen (see --help or packaging_base.py::run_ctypesgen() for further options)
      # Reminder: you'll want to use the pypdfium2-team fork of ctypesgen
      ctypesgen --library pdfium --runtime-libdirs $MY_LIBDIRS --headers $MY_INCLUDE_DIR/fpdf*.h -o src/pypdfium2_raw/bindings.py [-D $MY_FLAGS]
      
      # Write the version file (fill the placeholders).
      # Note, this is not a mature interface yet and might change!
      # 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, consisting of binary source and package provider (e.g. "system/debian", "pdfium-binaries/debian")
      # flags: a comma-delimited list of pdfium feature flag strings (e.g. "V8", "XFA") - may be empty for default build
      cat >"src/pypdfium2_raw/version.json" <<END
      {
        "major": $PDFIUM_MAJOR,
        "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, "auto" or the platform name otherwise
      PDFIUM_PLATFORM='prepared!$MY_PLATFORM:$PDFIUM_BUILD' python -m pip install --no-build-isolation -v .
      

    See Setup Magic for details.

    Support for source installs (esp. with self-built/system pdfium) is limited, as their integrity depends somewhat on a correctly acting caller.

    Installing an sdist does not implicitly trigger a sourcebuild if no pre-built binary is available. It is preferred to let callers decide consciously what to do, and run the build script without pip encapsulation.

    Relevant pip options:

    • -v: Verbose logging output. Useful for debugging.

    • -e: Install in editable mode, so the installation points to the source tree. This way, changes directly take effect without needing to re-install. Recommended for development.

    • --no-build-isolation: Do not isolate setup in a virtual env; use the main env instead. This renders pyproject.toml [build-system] inactive, setup deps must be prepared by caller. Useful to install custom versions of setup deps, or as speedup when installing repeatedly.

  • From Conda 🔗

    Beware: Any conda packages/recipes of pypdfium2 or pdfium-binaries that might be provided by other distributors, including anaconda/main or conda-forge default channels, are unofficial.

    • To install

      With permanent channel config (encouraged):

      conda config --add channels bblanchon
      conda config --add channels pypdfium2-team
      conda config --set channel_priority strict
      conda install pypdfium2-team::pypdfium2_helpers
      

      Alternatively, with temporary channel config:

      conda install pypdfium2-team::pypdfium2_helpers --override-channels -c pypdfium2-team -c bblanchon -c defaults
      

      Adding the channels permanently and tightening priority is encouraged to include pypdfium2 in conda update by default, and to avoid accidentally replacing the install with a different channel. (If desired, you may limit the channel config to the current environment by adding --env.) Otherwise, you should be cautious when making changes to the environment.

    • To depend on pypdfium2 in a conda-build recipe

      requirements:
        run:
          - pypdfium2-team::pypdfium2_helpers
      

      You'll want to have downstream callers handle the custom channels as shown above, otherwise conda will not be able to satisfy requirements.

    • To set up channels in a GH workflow

      - name: ...
        uses: conda-incubator/setup-miniconda@v3
        with:
          # ... your options
          channels: pypdfium2-team,bblanchon
          channel-priority: strict
      

      This is just a suggestion, you can also call conda config manually, or pass channels on command basis using -c, as discussed above.

    • To verify the sources

      conda list --show-channel-urls "pypdfium2|pdfium-binaries"
      conda config --show-sources
      

      The table should show pypdfium2-team and bblanchon in the channels column. If added permanently, the config should also include these channels, ideally with top priority. Please check this before reporting any issue with a conda install of pypdfium2.

    Note: Conda packages are normally managed using recipe feedstocks driven by third parties, in a Linux repository like fashion. However, with some quirks it is also possible to do conda packaging within the original project and publish to a custom channel, which is what pypdfium2-team does, and the above instructions are referring to.

  • Unofficial packages 🔗

    The authors of this project have no control over and are not responsible for possible third-party builds of pypdfium2, and we do not support them. Please use the official packages where possible. If you have an issue with a third-party build, either contact your distributor, or try to reproduce with an official build.

    Do not expect us to help with the creation of unofficial builds or add/change code for downstream setup tasks. Related issues or PRs may be closed without further notice if we don't see fit for upstream.

    If you are a third-party distributor, please point out clearly and visibly in the description that your package is unofficial, i.e. not affiliated with or endorsed by pypdfium2 team.

Runtime Dependencies

As of this writing, pypdfium2 does not need any mandatory runtime dependencies apart from Python itself.

However, some optional support model features require additional packages:

  • Pillow (module name PIL) is a pouplar imaging library for Python. pypdfium2 provides convenience methods to translate between raw bitmap buffers and PIL images.
  • NumPy is a library for scientific computing. Similar to Pillow, pypdfium2 provides helpers to get a numpy array view of a raw bitmap.

Setup Magic

As pypdfium2 requires a C extension and has custom setup code, there are some special features to consider. Note, the APIs below may change any time and are mostly of internal interest.

  • Binaries are stored in platform-specific sub-directories of data/, along with bindings and version information.

  • $PDFIUM_PLATFORM defines which binary to include on setup.

    • Format spec: [$PLATFORM][-v8][:$VERSION] ([] = segments, $CAPS = variables).
    • Examples: auto, auto:5975 auto-v8:5975 (auto may be substituted by an explicit platform name, e.g. linux_x64).
    • Platform:
      • If unset or auto, the host platform is detected and a corresponding binary will be selected.
      • If an explicit platform identifier (e.g. linux_x64, darwin_arm64, ...), binaries for the requested platform will be used.2
      • If system, bind against system-provided pdfium instead of embedding a binary. Version must be given explicitly so matching bindings can be generated.
      • If sourcebuild, binaries will be taken from data/sourcebuild/, assuming a prior run of build_pdfium.py.
      • If sdist, no platform-dependent files will be included, so as to create a source distribution. sourcebuild and sdist are standalone, they cannot be followed by additional specifiers.
    • V8: If given, use the V8 (JavaScript) and XFA enabled pdfium binaries. Otherwise, use the regular (non-V8) binaries.
    • Version: If given, use the specified pdfium-binaries release. Otherwise, use the latest one.
    • It is possible to prepend prepared! to install with existing platform files instead of generating on the fly; the value will be used for metadata / file inclusion. This can be helpful when installing in an isolated env where ctypesgen is not available, but it is not desirable to use the reference bindings (e.g. conda).
  • $PYPDFIUM_MODULES=[raw,helpers] defines the modules to include. Metadata adapts dynamically.

    • May be used by packagers to decouple raw bindings and helpers, which may be relevant if packaging against system pdfium.
    • Would also allow to install only the raw module without helpers, or only helpers with a custom raw module.
  • $PDFIUM_BINDINGS=reference allows to override ctypesgen and use the reference bindings file autorelease/bindings.py instead.

    • This is a convenience option to get pypdfium2 installed from source even if a working ctypesgen is not available in the install env.
    • Warning: This may not be ABI-safe. Please make sure binary/bindings build headers match to avoid ABI issues.

Usage

Support model

Here are some examples of using the support model API.

  • Import the library

    import pypdfium2 as pdfium
    
  • Open a PDF using the helper class PdfDocument (supports file path strings, bytes, and byte buffers)

    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
    
  • Render the page

    bitmap = page.render(
        scale = 1,    # 72dpi resolution
        rotation = 0, # no additional rotation
        # ... further rendering options
    )
    pil_image = bitmap.to_pil()
    pil_image.show()
    
  • Try some page methods

    # 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)
    
    # Locate objects on the page
    for obj in page.get_objects():
        print(obj.level, obj.type, obj.get_pos())
    
  • Extract and search text

    # Load a text page helper
    textpage = page.get_textpage()
    
    # Extract text from the whole page
    text_all = textpage.get_text_range()
    # Extract text from a specific rectangular area
    text_part = textpage.get_text_bounded(left=50, bottom=100, right=width-50, top=height-100)
    
    # Locate text on the page
    searcher = textpage.search("something", match_case=False, match_whole_word=False)
    # This returns the next occurrence as (char_index, char_count), or None if not found
    first_occurrence = searcher.get_next()
    
  • Read the table of contents

    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,
            )
        )
    
  • Create a new PDF with an empty A4 sized page

    pdf = pdfium.PdfDocument.new()
    width, height = (595, 842)
    page_a = pdf.new_page(width, height)
    
  • Include a JPEG image in a PDF

    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)
    

Footnotes

  1. This means pdfium may not compile on arbitrary hosts. The script is limited to build hosts supported by Google's toolchain. Ideally, we'd need an alternative build system that runs with system packages instead.

  2. Intended for packaging, so that wheels can be crafted for any platform without access to a native host.

项目侧边栏1项目侧边栏2
推荐项目
Project Cover

豆包MarsCode

豆包 MarsCode 是一款革命性的编程助手,通过AI技术提供代码补全、单测生成、代码解释和智能问答等功能,支持100+编程语言,与主流编辑器无缝集成,显著提升开发效率和代码质量。

Project Cover

问小白

问小白是一个基于 DeepSeek R1 模型的智能对话平台,专为用户提供高效、贴心的对话体验。实时在线,支持深度思考和联网搜索。免费不限次数,帮用户写作、创作、分析和规划,各种任务随时完成!

Project Cover

白日梦AI

白日梦AI提供专注于AI视频生成的多样化功能,包括文生视频、动态画面和形象生成等,帮助用户快速上手,创造专业级内容。

Project Cover

有言AI

有言平台提供一站式AIGC视频创作解决方案,通过智能技术简化视频制作流程。无论是企业宣传还是个人分享,有言都能帮助用户快速、轻松地制作出专业级别的视频内容。

Project Cover

讯飞绘镜

讯飞绘镜是一个支持从创意到完整视频创作的智能平台,用户可以快速生成视频素材并创作独特的音乐视频和故事。平台提供多样化的主题和精选作品,帮助用户探索创意灵感。

Project Cover

讯飞文书

讯飞文书依托讯飞星火大模型,为文书写作者提供从素材筹备到稿件撰写及审稿的全程支持。通过录音智记和以稿写稿等功能,满足事务性工作的高频需求,帮助撰稿人节省精力,提高效率,优化工作与生活。

Project Cover

阿里绘蛙

绘蛙是阿里巴巴集团推出的革命性AI电商营销平台。利用尖端人工智能技术,为商家提供一键生成商品图和营销文案的服务,显著提升内容创作效率和营销效果。适用于淘宝、天猫等电商平台,让商品第一时间被种草。

Project Cover

Trae

Trae是一种自适应的集成开发环境(IDE),通过自动化和多元协作改变开发流程。利用Trae,团队能够更快速、精确地编写和部署代码,从而提高编程效率和项目交付速度。Trae具备上下文感知和代码自动完成功能,是提升开发效率的理想工具。

Project Cover

AIWritePaper论文写作

AIWritePaper论文写作是一站式AI论文写作辅助工具,简化了选题、文献检索至论文撰写的整个过程。通过简单设定,平台可快速生成高质量论文大纲和全文,配合图表、参考文献等一应俱全,同时提供开题报告和答辩PPT等增值服务,保障数据安全,有效提升写作效率和论文质量。

投诉举报邮箱: service@vectorlightyear.com
@2024 懂AI·鲁ICP备2024100362号-6·鲁公网安备37021002001498号