Skip to Content
NexPDF

Getting started

Load the NexPDF WebAssembly engine, open a PDF the user picks, render a page and extract its text in the browser.

English

This example lets the user pick a PDF, shows the first page and prints the text of every page. Nothing is uploaded: the file is read and rendered inside the 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-web and its WebAssembly module as described in Installation.

Add the markup

index.html
<input type="file" id="file" accept="application/pdf" />
<img id="page" alt="First page" />
<pre id="text"></pre>
<script type="module" src="/main.ts"></script>

Write the script

main.ts
import { loadNexPdf } from '@nexdevit/nexpdf-web/engine';

// 1. Load the engine once.
const nex = await loadNexPdf();

// 2. Activate the license (optional for viewing). Web keys are bound to the host name.
const key = import.meta.env.VITE_NEXPDF_LICENSE;
if (key) nex.activateLicense(key, location.hostname);

document.querySelector<HTMLInputElement>('#file')!.addEventListener('change', async (e) => {
  const file = (e.target as HTMLInputElement).files?.[0];
  if (!file) return;

  // 3. Open the document.
  const doc = await nex.PdfDocument.fromFile(file);
  try {
    // 4. Page count and size.
    const { width, height } = doc.pageSize(0);
    console.log(`${file.name}: ${doc.pageCount} pages, first page ${width.toFixed(0)} x ${height.toFixed(0)} pt`);

    // 5. Render the first page at 110 dpi.
    const img = document.querySelector<HTMLImageElement>('#page')!;
    URL.revokeObjectURL(img.src);
    img.src = doc.renderUrl(0, { dpi: 110 });

    // 6. Extract the text of every page.
    const pages: string[] = [];
    for (let i = 0; i < doc.pageCount; i++) pages.push(`--- page ${i + 1} ---\n${doc.text(i)}`);
    document.querySelector('#text')!.textContent = pages.join('\n');
  } finally {
    doc.close();
  }
});

Run it

npx vite

Open the page and pick a PDF.

What the code does

  • loadNexPdf(wasmUrl?) fetches and instantiates the WebAssembly module once.
  • nex.activateLicense(keyOrXml, host) accepts the license XML or the bare key. The host must be one the key was issued for. See License.
  • PdfDocument.fromFile(blob), fromBytes(bytes) and fromUrl(url) open a PDF. Word, Excel and PowerPoint files are converted when the license includes conversion. Each takes { password } as a second argument.
  • pageSize(i) is the displayed size in points: crop box, rotation and /UserUnit applied.
  • renderUrl(i, { dpi }) returns an object URL of a PNG; revoke it when you no longer need it. render(i, { dpi }) returns the PNG bytes. The default is 110 dpi.
  • text(i) returns the page text in reading order.
  • close() frees the document's memory.

Next steps

On this page