Opening and saving
Open PDFs from files, URLs and bytes, open encrypted files, create PDFs from pictures, HTML, Office files, e-books and comics, and save, download, linearize and copy documents in the browser with NexPDF for the web.
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 files, e-books and comics needs the conversion module
(Startup tier and above).
Open a file, a URL or bytes
| Method | Source | Returns |
|---|---|---|
nex.PdfDocument.fromFile(blob, { password }) | A File or Blob, for example from a file input or a drop | Promise<PdfDocument> |
nex.PdfDocument.fromUrl(url, { password }) | A URL, fetched with fetch | Promise<PdfDocument> |
nex.PdfDocument.fromBytes(bytes, { password }) | A Uint8Array you already have | PdfDocument |
import { loadNexPdf } from '@nexdevit/nexpdf-web/engine';
const nex = await loadNexPdf();
input.addEventListener('change', async () => {
const doc = await nex.PdfDocument.fromFile(input.files![0]);
console.log(doc.pageCount, 'pages');
doc.close();
});
const fromServer = await nex.PdfDocument.fromUrl('/contracts/42.pdf');fromUrl throws Error('HTTP <status>') when the response is not OK. It uses fetch with its
defaults, so for cross-origin files the server must allow CORS. To send credentials or headers,
fetch the file yourself and pass the bytes to fromBytes.
All three 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. nex.detectKind(bytes) tells you beforehand what
fromBytes will do with a file: 'ebook', 'office' or 'pdf' (a PDF or pictures).
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 fromBytes, fromFile and fromUrl is
an OpenError with two flags: passwordRequired (no password, or a wrong one) and wrongPassword
(a password was given and it is wrong).
import { loadNexPdf, type OpenError } from '@nexdevit/nexpdf-web/engine';
async function openWithPassword(file: File) {
let password: string | undefined;
for (;;) {
try {
return await nex.PdfDocument.fromFile(file, { password });
} catch (e) {
const err = e as OpenError;
if (!err.passwordRequired) throw e;
password = prompt(err.wrongPassword ? 'Wrong password, try again' : 'Password') ?? undefined;
if (password === undefined) throw e;
}
}
}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.raw.securityJson() reports the encryption and permissions; see
Security.
Create a PDF from other formats
| Source | Method | Module |
|---|---|---|
| JPEG, PNG, TIFF | PdfDocument.fromFile, fromUrl or fromBytes | none |
| HTML | nex.PdfDocument.fromHtml(html) | conversion |
| Word, Excel, PowerPoint | PdfDocument.fromFile, fromUrl or fromBytes, or nex.PdfDocument.fromOffice(bytes) | conversion |
| EPUB, FictionBook, XPS/OpenXPS, CBZ | PdfDocument.fromFile, fromUrl or fromBytes, or nex.PdfDocument.fromEbook(bytes) | conversion |
const scan = await nex.PdfDocument.fromFile(tiffFile); // one page per TIFF frame
const invoice = nex.PdfDocument.fromHtml('<h1>Invoice 42</h1><p>Total: 120 EUR</p>');
const book = nex.PdfDocument.fromEbook(new Uint8Array(await epubFile.arrayBuffer()));fromOffice and fromEbook force one converter, whatever detectKind says.
To add pictures to an existing document, use doc.raw.insertImagePages(index, bytes); see
Editing.
Save
toBytes() returns the document with every change as a complete new PDF, and toBlob() the same
bytes as an application/pdf Blob. To let the user download it:
const url = URL.createObjectURL(doc.toBlob());
const link = Object.assign(document.createElement('a'), { href: url, download: 'contract.pdf' });
link.click();
URL.revokeObjectURL(url);
await fetch('/api/contracts/42', { method: 'PUT', body: doc.toBytes() }); // or upload itFast Web View
A linearized file shows its first page before the download ends, which helps when PDFs are served over HTTP:
const webBytes = doc.toLinearizedBytes();Signed files
sign returns the finished signed file. Keep 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. Use it as an undo snapshot, or to keep the original
before editing:
const snapshot = new nex.PdfDocument(doc.raw.clone());
doc.raw.deletePage(0);
// ... undo:
doc.close();
doc = snapshot;Related
- Document structure: metadata, bookmarks and attachments
- Conversion: PDF to Word, Excel, HTML and more
- Compare and optimise: smaller files and memory