Getting started
Activate a license, open a PDF, count its pages, render a page to PNG and extract its text with NexPDF for Node.js.
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
Add @nexdevit/nexpdf-node and its WebAssembly engine as described in
Installation.
Write the script
import { readFile, writeFile } from 'node:fs/promises';
import { activateLicense, PdfDocument } from '@nexdevit/nexpdf-node';
// 1. Activate the license once per process (optional for viewing).
if (process.env.NEXPDF_LICENSE) {
activateLicense(await readFile(process.env.NEXPDF_LICENSE, 'utf8'), 'com.acme.quickstart');
}
// 2. Open the document.
const path = process.argv[2] ?? 'sample.pdf';
const doc = await PdfDocument.open(path);
try {
// 3. Page count and size.
const { width, height } = doc.pageSize(0);
console.log(`${path}: ${doc.pageCount} pages, first page ${width.toFixed(0)} x ${height.toFixed(0)} pt`);
// 4. Render the first page at 144 dpi.
await writeFile('page1.png', doc.render(0, { dpi: 144 }));
// 5. Extract the text of every page.
for (let i = 0; i < doc.pageCount; i++) {
console.log(`--- page ${i + 1} ---`);
console.log(doc.text(i));
}
} finally {
doc.close();
}What the code does
activateLicense(keyOrXml, appId)accepts the license XML or the bare key. The app id must be one the key was issued for. See License.PdfDocument.open(source, { password })opens a PDF from a path, aUint8Arrayor anArrayBuffer. Word, Excel and PowerPoint files are converted when the license includesconversion; JPEG, PNG and TIFF pictures become one page each.PdfDocument.fromBytes(bytes)is the synchronous form for bytes.pageSize(i)is the displayed size in points: crop box, rotation and/UserUnitapplied.render(i, { dpi })returns PNG bytes. 72 dpi is one pixel per point; the default is 150.text(i)returns the page text in reading order.close()frees the document's memory.