Pdfium Getting Started and Integration Guide

Author

Reads 373

Back view focused ethnic male in white shirt reading document while sitting at desk with netbook in light office
Credit: pexels.com, Back view focused ethnic male in white shirt reading document while sitting at desk with netbook in light office

Getting started with Pdfium requires a basic understanding of the library's architecture. Pdfium is a portable document format (PDF) rendering engine written in C++.

The Pdfium library consists of two main components: the rendering engine and the PDF parser. The rendering engine is responsible for rendering PDF pages, while the PDF parser handles PDF document parsing.

To integrate Pdfium into your project, you'll need to download the library and link it to your project. You can download Pdfium from the official GitHub repository.

Getting Started

To get started with pdfium, visit crates.io for the latest version.

You can also use cargo search pdfium to find the latest version.

To begin, head over to crates.io for the latest pdfium version.

Integration and Bindings

To use PDFium in a CMake project, you'll need to follow a few steps. Set the environment variable PDFium_DIR to the folder where you've unzipped the PDFium package.

There are several ways to bind to Pdfium, including binding to a dynamically-built Pdfium library provided by the operating system, or binding to a statically-built Pdfium library linked to your executable at compile time.

Credit: youtube.com, Install Pypdfium2 Locally - PDF Rendering, Inspection, and Creation

To link your executable with PDFium in a CMake project, add the line "target_link_libraries(my_exe pdfium)" to your CMakeLists.txt file.

For Rust applications, you can use the pdfium-render library, which provides an idiomatic high-level Rust interface to Pdfium. This library binds to a Pdfium library at run-time, allowing for flexible selection of system-provided or bundled Pdfium libraries.

To link against the LLVM C++ standard library with pdfium-render, use the optional libc++ feature. This will pass the necessary flag to cargo.

Here are the options for binding to Pdfium:

  • Bind to a dynamically-built Pdfium library provided by the operating system.
  • Bind to a dynamically-built Pdfium library packaged alongside your Rust executable.
  • Bind to a statically-built Pdfium library linked to your executable at compile time.

Compiling and Linking

Compiling and linking Pdfium can be a bit tricky, but don't worry, I've got you covered. You have two options: static linking or dynamic linking.

Static linking involves linking Pdfium directly into your executable at compile time, which can be a good option if you prefer not to rely on external libraries. To do this, you can set the PDFIUM_STATIC_LIB_PATH environment variable when you run cargo build, pointing to the directory containing your static library.

Credit: youtube.com, Compiling and Linking

If you have a custom build pipeline that links Pdfium statically, you can leave these environment variables unset. However, if you're using pdfium-render, you can use the PDFIUM_DYNAMIC_LIB_PATH or PDFIUM_STATIC_LIB_PATH environment variables to save yourself the hassle of writing a custom build script.

To link to a dynamically-built library, set the PDFIUM_DYNAMIC_LIB_PATH environment variable when you run cargo build, pointing to the path of the containing directory. For example, on Linux, you can place the library in /usr/lib/, /usr/local/lib/, or /usr/lib/your_app/, while on macOS, you can place it in /usr/local/lib/ or /opt/homebrew/lib/.

For another approach, see: Geek Squad Build Computers

Compiling to WASM

Compiling to WASM can be a bit tricky, but don't worry, I've got the lowdown. Certain functions that access the file system are not available when compiling to WASM.

You can find a full example of how to bundle a Rust application using pdfium-render alongside a pre-built Pdfium WASM module at https://github.com/ajrcarey/pdfium-render/tree/master/examples.

If you're planning to compile to WASM, be aware that browser-specific alternatives are provided for functions that aren't available in WASM. For more information, check out the link above.

At the time of writing, the WASM builds of Pdfium at https://github.com/bblanchon/pdfium-binaries/releases are compiled with a non-growable WASM heap memory allocator. This can cause problems if you try to open a PDF document longer than a few pages.

Suggestion: E L E C T R O

Type Pool Added 0.5.0

Focused businessman working at desk with laptop and documents in modern office
Credit: pexels.com, Focused businessman working at desk with laptop and documents in modern office

In the latest update, a type Pool was added in version 0.5.0. This feature describes a PDFium worker pool where every instance manages its own resources.

A worker pool is essentially a group of workers that can be utilized to perform tasks concurrently. This can be particularly useful when dealing with large amounts of data or complex computations.

Each instance in the pool is responsible for its own resources, which means that if one instance crashes or fails, it won't affect the other instances in the pool. This level of isolation is beneficial for maintaining system stability and preventing resource leaks.

As a developer, I've found that managing resources effectively is crucial for creating efficient and scalable applications. By utilizing a worker pool, you can take advantage of multiple CPU cores and improve overall system performance.

Features and Performance

With pdfium, you have the option to choose between single-threaded, multi-threaded, and WebAssembly, all while keeping the same interface. This flexibility is a game-changer for developers who need to handle complex tasks.

Credit: youtube.com, LibreOffice Conference 2018: PDFium for better PDF rendering and editing

One of the standout features of pdfium is its ability to handle complicated cgo/WebAssembly gymnastics for you, so you don't need to have direct knowledge or usage of these technologies. This makes it much easier to get started and focus on the task at hand.

The library provides implementation of all PDFium public API methods, with some exceptions, and offers useful helpers to make your life easier. You can access all 440+ functions of the C API, fully documented, and select either Skia or AGG as the renderer for PDFium.

A different take: Websocket Api

Speed up JPEG rendering

Speed up JPEG rendering by using libjpeg-turbo, which is significantly faster than the default image/jpeg package that comes with Go. This will require installing libturbojpeg-dev during build time and libturbojpeg during runtime and build time.

You can enable libjpeg-turbo by using the build tag pdfium_use_turbojpeg. This will give you a speed improvement of around 3x, making the full process of rendering a page 3x as fast compared to a build without libjpeg-turbo.

This is supported in both the CGO and WebAssembly implementation, but the WebAssembly implementation currently uses CGO for libjpeg-turbo. There are plans to compile libjpeg-turbo to WebAssembly for the WebAssembly implementation in the future.

For more insights, see: Speed of 5g Network

Crate Features

A person typing on a keyboard with documents on a wooden desk. Modern workspace setup.
Credit: pexels.com, A person typing on a keyboard with documents on a wooden desk. Modern workspace setup.

You can choose between single-threaded, multi-threaded, and WebAssembly modes, all while keeping the same interface. This flexibility is a big plus.

This crate handles all the complicated cgo/WebAssembly gymnastics for you, so you don't need to have any direct cgo/WebAssembly usage or knowledge.

The crate implements all PDFium public API methods, except for a few that won't be implemented for now.

Here are some of the useful helpers that make your life easier:

  • Thread-safe static library access - Initialize once, use everywhere
  • Lifetime-free API - No complex lifetime management for documents, pages, and bitmaps
  • Access to C API - Safe access to the full C API. All 440+ functions are available, fully documented
  • Idiomatic Rust abstractions - An idiomatic high-level Rust interface to the most frequently used features
  • Renderer selection - Select either Skia or AGG (Anti-Grain Geometry) as renderer for PDFium

You can safely use pdfium-render as part of a multi-threaded application by locking access to Pdfium behind a mutex. This approach ensures that Pdfium will not crash, even when running as part of a multi-threaded application.

Readers also liked: OpenCable Application Platform

Crate and Library

pdfium is a C++ library that provides a powerful and flexible way to handle PDF files. It's designed to be used in a variety of applications, from simple PDF viewers to complex document management systems.

The library is organized into a series of crates, each of which provides a specific set of functionality. The main crate, pdfium, contains the core functionality of the library, including the PDF parser and renderer.

Credit: youtube.com, STOP Building PDF Editors in C# with Pdfium Until You Watch This!

The pdfium crate is built on top of the pdfium-core crate, which provides a set of low-level functions for working with PDF files. This allows developers to access the raw data of a PDF file and perform custom processing on it.

One of the key benefits of using pdfium is its ability to handle large PDF files efficiently. The library uses a combination of caching and lazy loading to minimize memory usage and improve performance.

The library also includes a number of tools and utilities for working with PDF files, including a command-line tool for extracting text from PDFs. This makes it easy to use pdfium in a variety of applications and workflows.

Expand your knowledge: How to Store Files in the Cloud

Troubleshooting

Troubleshooting can be a frustrating experience, but it's often a matter of identifying the root cause of the issue. If you're experiencing runtime errors, it might indicate an incompatible PDFium library version.

Try downloading a different build from the pdfium-binaries releases, as this can often resolve the issue.

Requirements and Details

Credit: youtube.com, What is Pdfium Viewer and How do I install and run it in Windows 10?

To get started with PDFium, you'll need to meet some basic requirements. Rust 1.80 or later is the minimum version you'll need to run PDFium.

You'll also need to have the PDFium dynamic library installed on your system. This library is available for Linux, Windows, and macOS, and can be downloaded from the GitHub repository for PDFium binaries.

To install the library, you'll need to place it in the correct location depending on your operating system. Here's a quick rundown of the required locations:

  • Linux: /usr/lib/, /usr/local/lib/, or /usr/lib/your_app/
  • macOS: /usr/local/lib/ or /opt/homebrew/lib/
  • Windows: the same directory as your executable

Rs

Rs is a Rust interface to the PDFium C library, designed for simplicity and thread safety in interactive applications.

PDFium is Google's PDF library developed for (and used in) the Chromium and Chrome web browsers.

The Rs interface is modern and streamlined, making it suitable for a variety of applications that require PDF rendering and manipulation.

PDFium's use in the Chromium and Chrome web browsers highlights its reliability and performance in handling complex PDF operations.

Rs provides a thread-safe way to interact with PDFium, ensuring that multiple threads can access and manipulate PDF documents simultaneously.

This thread safety feature makes Rs a valuable tool for developers creating interactive applications that require simultaneous PDF rendering and manipulation.

Worth a look: Chrome Nfc Tag

Requirements

A close-up view of a man's hands using a smartphone with papers on a table.
Credit: pexels.com, A close-up view of a man's hands using a smartphone with papers on a table.

To get started with PDFium-rs, you'll need to meet some basic requirements. The first one is to have Rust 1.80 or later installed on your system.

You'll also need to have the PDFium dynamic library available on your system, which can be obtained from various sources. For example, you can download pre-built libraries from the GitHub repository https://github.com/bblanchon/pdfium-binaries/releases.

Here's a quick rundown of the different platforms and how to obtain the necessary libraries:

Once you have the library, you'll need to place it in the correct location on your system. The exact location will depend on your platform, but here are some general guidelines:

  • Linux: /usr/lib/, /usr/local/lib/, or /usr/lib/your_app/
  • macOS: /usr/local/lib/ or /opt/homebrew/lib/
  • Windows: Place pdfium.dll in the same directory as your executable

If you're having trouble getting the library to work, don't worry! There are plenty of resources available to help you troubleshoot. For example, you can check the GitHub repository https://github.com/paulocoutinhox/pdfium-lib/releases for pre-built libraries suitable for runtime binding.

Recommended read: 802.11ax / Wifi 6 Mode

Implementations and Examples

You can find more information on how to use PDFium-rs in the examples/ directory.

PDFium-rs has a comprehensive set of examples that demonstrate its capabilities and help you get started with your own projects.

These examples are a great resource for learning the ins and outs of PDFium-rs, and can be a valuable asset as you work with the library.

Porting Code to New Language

Woman holding a white mug at a desk with documents and laptop in an office.
Credit: pexels.com, Woman holding a white mug at a desk with documents and laptop in an office.

Porting code to a new language can be a daunting task, but it doesn't have to be. With the right tools and knowledge, you can make the process much smoother.

You can use raw FFI bindings to the Pdfium API, defined in the PdfiumLibraryBindings trait, to make porting existing code from other languages trivial.

The Pdfium API uses three different string types, making it necessary to use the correct type when calling functions. The pdfium-render binding takes the standard Rust &str type for functions that take a C-style string or a UTF-8 byte array.

You can use the PdfiumLibraryBindings::get_pdfium_utf16le_bytes_from_str() and PdfiumLibraryBindings::get_string_from_pdfium_utf16le_bytes() utility functions to convert to and from FPDF_WIDESTRING in your own code.

Converting between RGB and BGR image data is also a breeze with the PdfiumLibraryBindings::bgr_to_rgba(), PdfiumLibraryBindings::bgra_to_rgba(), PdfiumLibraryBindings::rgb_to_bgra(), and PdfiumLibraryBindings::rgba_to_bgra() utility functions.

The PdfiumLibraryBindings::get_handle_from_document(), PdfiumLibraryBindings::get_handle_from_page(), and PdfiumLibraryBindings::get_handle_from_object() utility functions allow you to retrieve Pdfium object handles from pdfium-render object instances.

Implementations

In some implementations, a specific algorithm is used to optimize the process, such as the greedy algorithm, which makes the locally optimal choice at each stage with the hope of finding a global optimum solution.

Consider reading: Google Maps Algorithm Works

A woman in a suit uses a red pen to edit a printed document on a green table with a laptop.
Credit: pexels.com, A woman in a suit uses a red pen to edit a printed document on a green table with a laptop.

The algorithm is often used in problems that have a large number of possible solutions, such as the traveling salesman problem, where the goal is to find the shortest possible route that visits a set of cities and returns to the starting city.

In other implementations, a heuristic approach is used, which involves making an educated guess or approximation to solve the problem, such as the nearest neighbor algorithm, which starts at a random city and repeatedly chooses the closest city until all cities have been visited.

This approach is often used in problems where an exact solution is not feasible, such as in real-time systems where a fast solution is more important than an optimal one.

In some cases, a combination of algorithms is used, such as the simulated annealing algorithm, which starts with a random solution and gradually improves it by accepting worse solutions with a certain probability.

This approach is often used in problems where the optimal solution is not known in advance, such as in scheduling problems where the goal is to find a feasible solution that meets all constraints.

A unique perspective: Digital Solutions Provider

More Examples

Credit: youtube.com, Examples of implementation attacks on other machines

You can find more information on how to use PDFium-rs in the examples/ directory.

The examples directory is a treasure trove of code snippets and projects that demonstrate how to implement PDFium-rs in different scenarios.

You can find more information on how to use PDFium-rs in the examples/ directory.

Frequently Asked Questions

Who uses PDFium?

PDFium is used by popular browsers like Chrome and Windows Edge, as well as SaaS vendors like Dropbox for server-side PDF rendering.

Walter Brekke

Lead Writer

Walter Brekke is a seasoned writer with a passion for creating informative and engaging content. With a strong background in technology, Walter has established himself as a go-to expert in the field of cloud storage and collaboration. His articles have been widely read and respected, providing valuable insights and solutions to readers.

Love What You Read? Stay Updated!

Join our community for insights, tips, and more.