Open a PDF using JavaScript

To open a PDF document.

JavaScript

1// open document from the filesystem or URL
2async function main() {
3 const doc = await PDFNet.PDFDoc.createFromURL(filename);
4
5 // optionally read a PDF document from a stream
6 const file = await PDFNet.Filter.createURLFilter(filename);
7 const doc_stream = await PDFNet.PDFDoc.createFromFilter(file);
8
9 // or pass-in a memory buffer
10 const file_sz = await file.size();
11 const file_reader = await PDFNet.FilterReader.create(file);
12 const mem = await file_reader.read(file_sz);
13 const doc_mem = await PDFNet.PDFDoc.createFromBuffer(mem);
14}
15PDFNet.runWithCleanup(main);

Read & write a PDF file from/to memory buffer
Full source code which illustrates how to read/write a PDF document from/to memory buffer. This is useful for applications that work with dynamic PDF documents that don't need to be saved/read from a disk.

About opening a document

The PDFDoc constructor creates a PDF document from scratch:

PDFDoc.Close()

When you are finished with a PDFDoc object, the PDFDoc.Close() method should be called to clean up memory, file handles, and resources.

JavaScript

1async function main() {
2 const doc = await PDFNet.PDFDoc.create();
3}
4PDFNet.runWithCleanup(main);

A newly-created document does not yet contain any pages. See the accessing pages section for details on creating new pages and working with existing pages.

Using Apryse SDK, you can open a document from a serialized file, from a memory buffer, or from a Filter stream.

To open an existing PDF document from a file, specify its file path in the PDFDoc constructor:

JavaScript

1async function main() {
2 const doc = await PDFNet.PDFDoc.createFromURL(filename);
3}
4PDFNet.runWithCleanup(main);

Here's how to open an existing PDF document from a memory buffer:

JavaScript

1async function main() {
2 const file = await PDFNet.Filter.createURLFilter(filename);
3 const file_sz = await file.size();
4 const file_reader = await PDFNet.FilterReader.create(file);
5 const mem = await file_reader.read(file_sz);
6 const doc_mem = await PDFNet.PDFDoc.createFromBuffer(mem);
7}
8PDFNet.runWithCleanup(main);

It's also easy to open a PDF document from a MemoryFilter or a custom Filter .

After creating a PDFDoc object, it's good practice to call InitSecurityHandler() on it. If the document is encrypted, calling the method will decrypt it. If the document is not encrypted, calling the method is harmless.

JavaScript

1async function main() {
2 const doc = await PDFNet.PDFDoc.createFromURL(filename);
3 if (!doc.initSecurityHandler()) {
4 console.log("Document authentication error...");
5 return;
6 }
7}
8PDFNet.runWithCleanup(main);

Did you find this helpful?

Trial setup questions?

Ask experts on Discord

Need other help?

Contact Support

Pricing or product questions?

Contact Sales