Skip to Content
NexPDF

Opening and saving

Open PDFs from files and bytes, open encrypted files, create PDFs from pictures, HTML, Office and e-book files, and save, linearize and copy documents with NexPDF for Node.js.

English

License module

Opening PDFs and pictures, saving and copying are part of the viewer module and work without a key. Creating a PDF from HTML, Office or e-book files needs the conversion module (Startup tier and above).

Open a file or bytes

PdfDocument.open(source, { password }) takes a file path, a Uint8Array (a Buffer works) or an ArrayBuffer, and resolves to a PdfDocument. PdfDocument.fromBytes(bytes, { password }) is the synchronous form for bytes you already have, for example from an upload or object storage.

import { readFile } from 'node:fs/promises';
import { PdfDocument } from '@nexdevit/nexpdf-node';

const doc = await PdfDocument.open('contract.pdf');
console.log(doc.pageCount, 'pages');
doc.close();

const fromUpload = PdfDocument.fromBytes(await readFile('contract.pdf'));
console.log(fromUpload.pageCount);
fromUpload.close();

Both accept JPEG, PNG and TIFF pictures too (one page per picture). With the conversion module, Word, Excel and PowerPoint files, EPUB and FictionBook books, XPS and OpenXPS files and CBZ comics are detected and converted on open. detectKind(bytes) tells you beforehand what open will do with a file: 'ebook', 'office' or 'pdf' (a PDF or pictures). A path that cannot be read rejects with the file system error (ENOENT and so on).

A document holds WebAssembly memory. Call close() when you are done with it; documents that are garbage collected are freed too, but not at a predictable time.

Encrypted documents

Pass the user (open) password or the owner password. RC4, AES-128 and AES-256 files are supported. When the password is missing or wrong, the error thrown by open and fromBytes has two flags: passwordRequired (no password, or a wrong one) and wrongPassword (a password was given and it is wrong).

try {
  const doc = await PdfDocument.open('locked.pdf', { password: 's3cret' });
} catch (e) {
  if (!e.passwordRequired) throw e;
  askTheUserAgain(e.wrongPassword ? 'Wrong password' : 'This file needs a password');
}

A password is used only for PDFs; Office files, e-books and comics are converted without one.

Files that are only restricted by permissions (no open password) open without a password. doc.security() reports the encryption and permissions; see Security.

Create a PDF from other formats

SourceCallModule
JPEG, PNG, TIFFPdfDocument.open(source), or PdfDocument.fromImage(source)none
HTMLPdfDocument.fromHtml(html)conversion
Word, Excel, PowerPointPdfDocument.open(source), or PdfDocument.fromOffice(source)conversion
EPUB, FictionBook, XPS/OpenXPS, CBZPdfDocument.open(source), or PdfDocument.fromEbook(source)conversion

fromImage, fromOffice and fromEbook take a path or bytes, resolve to a PdfDocument and force one converter, whatever detectKind says.

import { PdfDocument } from '@nexdevit/nexpdf-node';

const scan = await PdfDocument.open('scan.tiff');          // one page per TIFF frame
await scan.save('scan.pdf');

const invoice = PdfDocument.fromHtml('<h1>Invoice 42</h1><p>Total: 120 EUR</p>');
await invoice.save('invoice.pdf');

E-books, XPS and comics

PdfDocument.open and fromBytes recognise EPUB and FictionBook books, XPS files and CBZ comics and convert them with the e-book converter:

const book = await PdfDocument.open('book.epub');            // or PdfDocument.fromEbook('book.epub')
await book.save('book.pdf');

To add pictures to an existing document, use doc.raw.insertImagePages(index, bytes); see Editing.

Save

save(path) writes the document with every change as a complete new file and resolves to the path. toBytes() returns the same bytes instead of writing a file.

await doc.save('out.pdf');
const pdfBytes = doc.toBytes();          // e.g. to return from a web handler
res.setHeader('Content-Type', 'application/pdf');
res.end(pdfBytes);

Fast Web View

A linearized file shows its first page before the download ends, which helps when PDFs are served over HTTP:

await doc.save('web.pdf', { linearized: true });
const webBytes = doc.toLinearizedBytes();     // the same bytes, without a file

Signed files

Signing returns the finished signed file. Write those bytes as they are: saving the document object again rewrites the file and breaks the signature. See Signatures.

Copy a document

doc.raw.clone() returns an independent copy with the same content and changes. Wrap it in a PdfDocument to use the convenience methods, for example as an undo snapshot:

const snapshot = new PdfDocument(doc.raw.clone());
doc.deletePage(0);
// ... undo:
doc.close();
doc = snapshot;

On this page