Getting started
Activate a license, open a PDF, count its pages, render a page to PNG and extract its text with NexPDF for Rust.
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[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
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.pdfpage1.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 returnsActivation::TrialorActivation::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 includesconversion; JPEG, PNG and TIFF pictures become one page each. The document is freed whendocgoes out of scope.page_width(i)andpage_height(i)are the displayed size in points: crop box, rotation and/UserUnitapplied. They returnf64directly.render_page_png(i, dpi)returns the PNG asVec<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 returnnexpdf_sdk::Result, andstd::io::Errorconverts intonexpdf_sdk::Error.