Skip to Content
NexPDF

Getting started

Activate a license, open a PDF, count its pages, render a page to PNG and extract its text with NexPDF for Rust.

English

This example opens a PDF, prints the page count, renders the first page to a PNG file and prints the text of every page. It runs without a license key too: viewing is always allowed, and rendered pages then carry a watermark.

Create the project

cargo new quickstart
cd quickstart
Cargo.toml
[dependencies]
nexpdf-sdk = { git = "https://github.com/nexdevit/nexpdf-rust", tag = "v1.1.0" }

Download the native library and set NEXPDF_LIB_DIR as described in Installation.

Write the program

src/main.rs
use nexpdf_sdk::{license, Document};

fn main() -> nexpdf_sdk::Result<()> {
    // 1. Activate the license once per process (optional for viewing).
    if let Ok(license_file) = std::env::var("NEXPDF_LICENSE") {
        let key = std::fs::read_to_string(license_file)?;
        let activation = license::activate(&key, "server", "com.acme.quickstart")?;
        println!("NexPDF {} ({activation:?})", nexpdf_sdk::version());
    }

    // 2. Open the document.
    let path = std::env::args().nth(1).unwrap_or_else(|| "sample.pdf".to_owned());
    let doc = Document::open(&path)?;

    // 3. Page count and size.
    let count = doc.page_count()?;
    println!(
        "{path}: {count} pages, first page {:.0} x {:.0} pt",
        doc.page_width(0),
        doc.page_height(0)
    );

    // 4. Render the first page at 144 dpi.
    std::fs::write("page1.png", doc.render_page_png(0, 144.0)?)?;

    // 5. Extract the text of every page.
    for i in 0..count as usize {
        println!("--- page {} ---", i + 1);
        println!("{}", doc.extract_page_text(i)?);
    }
    Ok(())
}

Run it

export NEXPDF_LIB_DIR=/opt/nexpdf-ffi-1.1.0-linux-x64/lib
cargo run -- contract.pdf

page1.png is written to the current folder. With the shared library, the program needs an rpath or LD_LIBRARY_PATH to find it when you run the binary outside Cargo; see Installation.

What the code does

  • license::activate(key_or_xml, platform, app_id) accepts the license XML or the bare key and returns Activation::Trial or Activation::Commercial. The app id must be one the key was issued for. See License.
  • Document::open(path) reads and opens a PDF. Word, Excel and PowerPoint files, e-books and CBZ comics are converted when the license includes conversion; JPEG, PNG and TIFF pictures become one page each. The document is freed when doc goes out of scope.
  • page_width(i) and page_height(i) are the displayed size in points: crop box, rotation and /UserUnit applied. They return f64 directly.
  • render_page_png(i, dpi) returns the PNG as Vec<u8>. 72 dpi is one pixel per point.
  • extract_page_text(i) returns the page text in reading order.
  • ? works for every call because they all return nexpdf_sdk::Result, and std::io::Error converts into nexpdf_sdk::Error.

Next steps

On this page