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.
<a id="user-content-install-pypi" class="anchor" href="#install-pypi">From PyPI 🔗</a> (recommended)
python -m pip install -U pypdfium2
This will use a pre-built wheel package, the easiest way of installing pypdfium2.
<a id="user-content-install-source" class="anchor" href="#install-source">From source 🔗</a>
Dependencies:
$CPP
)Get the code
git clone "https://github.com/pypdfium2-team/pypdfium2.git"
cd pypdfium2/
<a id="user-content-install-source-default" class="anchor" href="#install-source-default">With pre-built binary 🔗</a>
# In the pypdfium2/ directory python -m pip install -v .
A binary is downloaded implicitly from pdfium-binaries
and bundled into pypdfium2.
<a id="user-content-install-source-selfbuilt" class="anchor" href="#install-source-selfbuilt">With self-built binary 🔗</a>
# 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.
<a id="user-content-install-source-system" class="anchor" href="#install-source-system">With system-provided binary 🔗</a>
# 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.
# 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.
<a id="user-content-install-conda" class="anchor" href="#install-conda">From Conda 🔗</a>
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.
<a id="user-content-install-unofficial" class="anchor" href="#install-unofficial">Unofficial packages 🔗</a>
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.
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.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.
[$PLATFORM][-v8][:$VERSION]
([]
= segments, $CAPS
= variables).auto
, auto:5975
auto-v8:5975
(auto
may be substituted by an explicit platform name, e.g. linux_x64
).auto
, the host platform is detected and a corresponding binary will be selected.linux_x64
, darwin_arm64
, ...), binaries for the requested platform will be used.2system
, bind against system-provided pdfium instead of embedding a binary. Version must be given explicitly so matching bindings can be generated.sourcebuild
, binaries will be taken from data/sourcebuild/
, assuming a prior run of build_pdfium.py
.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.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.
$PDFIUM_BINDINGS=reference
allows to override ctypesgen and use the reference bindings file autorelease/bindings.py
instead.
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)
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. ↩
Intended for packaging, so that wheels can be crafted for any platform without access to a native host. ↩
AI辅助编程,代码自动修复
Trae是一种自适应的集成开发环境(IDE),通过自动化和多元协作改变开发流程。利用Trae,团队能够更快速、精确地编写和部署代码,从而提高编程效率和项目交付速度。Trae具备上下文感知和代码自动完成功能,是提升开发效率的理想工具。
AI小说写作助手,一站式润色、改写、扩写
蛙蛙写作—国内先进的AI写作平台,涵盖小说、学术、社交媒体等多场景。提供续写、改写、润色等功能,助力创作者高效优化写作流程。界面简洁,功能全面,适合各类写作者提升内容品质和工作效率。
全能AI智能助手,随时解答生活与工作的多样问题
问小白,由元石科技研发的AI智能助手,快速准确地解答各种生活和工作问题,包括但不限于 搜索、规划和社交互动,帮助用户在日常生活中提高效率,轻松管理个人事务。
实时语音翻译/同声传译工具
Transly是一个多场景的AI大语言模型驱动的同声传译、专业翻译助手,它拥有超精准的音频识别翻译能力,几乎零延迟的使用体验和支持多国语言可以让你带它走遍全球,无论你是留学生、商务人士、韩剧美剧爱好者,还是出国游玩、 多国会议、跨国追星等等,都可以满足你所有需要同传的场景需求,线上线下通用,扫除语言障碍,让全世界的语言交流不再有国界。
一键生成PPT和Word,让学习生活更轻松
讯飞智文是一个利用 AI 技术的项目,能够帮助用户生成 PPT 以及各类文档。无论是商业领域的市场分析报告、年度目标制定,还是学生群体的职业生涯规划、实习避坑指南,亦或是活动策划、旅游攻略等内容,它都能提供支持,帮助用户精准表达,轻松呈现各种信息。
深度推理能力全新升级,全面对标OpenAI o1
科大讯飞的星火大模型,支持语言理解、知识问答和文本创作等多功能,适用于多种文件和业务场景,提升办公和日常生活的效率。讯飞星火是一个提供丰富智能服务的平台,涵盖科 技资讯、图像创作、写作辅助、编程解答、科研文献解读等功能,能为不同需求的用户提供便捷高效的帮助,助力用户轻松获取信息、解决问题,满足多样化使用场景。
一种基于大语言模型的高效单流解耦语音令牌文本到语音合成模型
Spark-TTS 是一个基于 PyTorch 的开源文本到语音合成项目,由多个知名机构联合参与。该项目提供了高效的 LLM(大语言模型)驱动的语音合成方案,支持语音克隆和语音创建功能,可通过命令行界面(CLI)和 Web UI 两种方式使用。用户可以根据需求调整语音的性别、音高、速度等参数,生成高质量的语音。该项目适用于多种场景,如有声读物制作、智能语音助手开发等。
AI助力,做PPT更简单!
咔片是一款轻量化在线演示设计工具,借助 AI 技术,实现从内容生成到智能设计 的一站式 PPT 制作服务。支持多种文档格式导入生成 PPT,提供海量模板、智能美化、素材替换等功能,适用于销售、教师、学生等各类人群,能高效制作出高品质 PPT,满足不同场景演示需求。
选题、配图、成文,一站式创作,让内容运营更高效
讯飞绘文,一个AI集成平台,支持写作、选题、配图、排版和发布。高效生成适用于各类媒体的定制内容,加速品牌传播,提升内容营销效果。
专业的AI公文写作平台,公文写作神器
AI 材料星,专业的 AI 公文写作辅助平台,为体制内工作人员提供高效的公文写作解决方案。拥有海量公文文库、9 大核心 AI 功能,支持 30 + 文稿类型生成,助力快速完成领导讲话、工作总结、述职报告等材料,提升办公效率,是体制打工人的得力写作神器。
最新AI工具、AI资讯
独家AI资源、AI项目落地
微信扫一扫关注公众号