Getting started
Activate a license, open a PDF, count its pages, render a page to PNG and extract its text with NexPDF for C++.
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.
Install the SDK
Get nexpdf-cpp and the native library, and add the nexdevit::nexpdf target to your build, as
described in Installation.
Write the program
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <iterator>
#include <string>
#include <vector>
#include <nexpdf.hpp>
namespace nexpdf = nexdevit::nexpdf;
// Small file helpers used throughout the guides.
std::vector<uint8_t> read_file(const std::string& path) {
std::ifstream f(path, std::ios::binary);
return {std::istreambuf_iterator<char>(f), std::istreambuf_iterator<char>()};
}
std::string read_text(const std::string& path) {
std::ifstream f(path);
return {std::istreambuf_iterator<char>(f), std::istreambuf_iterator<char>()};
}
void write_file(const std::string& path, const std::vector<uint8_t>& data) {
std::ofstream f(path, std::ios::binary);
f.write(reinterpret_cast<const char*>(data.data()), static_cast<std::streamsize>(data.size()));
}
int main(int argc, char** argv) {
try {
// 1. Activate the license once per process (optional for viewing).
if (const char* license_file = std::getenv("NEXPDF_LICENSE")) {
nexpdf::activate_license(read_text(license_file), "server", "com.acme.quickstart");
}
// 2. Open the document.
std::string path = argc > 1 ? argv[1] : "sample.pdf";
auto doc = nexpdf::Document::open(path);
// 3. Page count and size.
int32_t count = doc.page_count();
std::printf("%s: %d pages, first page %.0f x %.0f pt\n",
path.c_str(), count, doc.page_width(0), doc.page_height(0));
// 4. Render the first page at 144 dpi.
write_file("page1.png", doc.render_page_png(0, 144));
// 5. Extract the text of every page.
for (int32_t i = 0; i < count; ++i) {
std::cout << "--- page " << i + 1 << " ---\n" << doc.extract_page_text(i) << "\n";
}
} catch (const nexpdf::Error& e) {
std::cerr << e.what() << "\n";
return 1;
}
}Build and run it
cmake -S . -B build -DNEXPDF_LIB_DIR=/opt/nexpdf-ffi-1.1.0-linux-x64/lib
cmake --build build
./build/app contract.pdfpage1.png is written to the current folder.
What the code does
nexpdf::activate_license(key_or_xml, platform, app_id)accepts the license XML or the bare key. The app id must be one the key was issued for. See License.Document::open(path, password)opens a PDF;passwordis optional. Word, Excel and PowerPoint files are converted when the license includesconversion; JPEG, PNG and TIFF pictures become one page each.page_width(i)andpage_height(i)are the displayed size in points: crop box, rotation and/UserUnitapplied.render_page_png(i, dpi)returns PNG bytes. 72 dpi is one pixel per point.extract_page_text(i)returns the page text in reading order.