Some test text!

menu
Advanced featureskeyboard_arrow_down

Advanced features of Full API

To get started with setting up a full API project, refer to the getting starting guide.

The full API contains several methods for more advanced control over its processes via locking and memory management. This guide will provide an explanation of how to use these features and will also shed some light on the backend processes of the full API.

Understanding Full API backends

For optimal performance, the full API uses two different backends to run its processes, WebAssembly Threads and Emscripten.

  • WebAssembly Threads has better performance, since it supports multithreading but currently is only supported on Google Chrome for Desktop. This may change in the future.
  • Emscripten (which compiles both non-threaded WebAssembly and asm.js implementations) starts up a little faster and is compatible with most browsers, but has slower runtime performance.

On Google Chrome the WebAssembly Threads backend will be used by default, while other browsers will use the Emscripten backend.

Full API locking

Locking prevents multiple simultaneous accesses to a PDF document in a Full API process so that it cannot be changed by outside operations.

A PDFTron SDK lock is based on two principles:

Reentrant mutex (also known as recursive lock)
Recursive mutex may be locked multiple times by the same process/thread without causing a deadlock.

Readers-writer (RW) lock (also known as shared-exclusive lock)
An RW lock allows concurrent access for read-only operations, while write operations require exclusive access.

Full API contains three main types of locking and unlocking statements:

Lock and unlock

Locks a PDF document to prevent competing threads from accessing the document at the same time. Threads attempting to access the document will wait in suspended state until the thread that owns the lock calls doc.Unlock().

  • [PDFDoc].lock()
  • [PDFDoc].unlock() -

Auto unlock

Documents are automatically unlocked upon process completion if the user code is being using PDFNet.runWithCleanup().

  • PDFNet.runWithCleanup()

LockRead and unlockRead

Locks the document to prevent competing write threads (using lock()) from accessing the document at the same time. Read-only threads however, will be allowed to access the document.

  • [PDFDoc].lockRead()
  • [PDFDoc].unlockRead()

Threads attempting to obtain write access to the document will wait in suspended state until the thread that owns the lock calls doc.unlockRead(). Documents are automatically unlocked upon process completion if the user code is being run with PDFNet.runWithCleanup().

Note
Obtaining a write lock while holding a read lock is not permitted and will throw an exception. If this situation is encountered please either unlock the read lock before the write lock is obtained or acquire a write lock (rather than read lock) in the first place.

Manual document locking example

async function main() {
  try {
    const doc = await PDFNet.PDFDoc.create();
    doc.initSecurityHandler();
    // documents require locking
    doc.lock();
    // do stuff with document
  } catch (err){
    console.log(err);
  } finally {
    // unlocks the document
    await doc.unlock();
  }
}
PDFNet.runWithoutCleanup(main);
// if you use PDFNet.runWithCleanup(main), no need to unlock

BeginOperation and finishOperation

beginOperation() locks all worker operations on PDFNet.

  • PDFNet.beginOperation()
  • PDFNet.finishOperation()

RunWithCleanup and runWithoutCleanup

Both PDFNet.runWithCleanup() and PDFNet.runWithoutCleanup() call beginOperation() and end with finishOperation(), so beginOperation() and finishOperation() should only be used when PDFNet needs to be unlocked in the middle of a process.

  • PDFNet.runWithCleanup()
  • PDFNet.runWithoutCleanup()
async function main() {
  // ...
}
// Automatically locks all worker operations
PDFNet.runWithCleanup(main);

Queue operations

Running multiple unrelated full API operations simultaneously may result in race conditions. This can be resolved by synchronizing the full API operations using a queue. The deck.js sample demonstrates this by queuing its renderPage calls to prevent race conditions on its single shared PDFDraw object.

For this reason, calling beginOperation() a second time before finishOperation() is called will cause an exception to be thrown.

There are some cases where unlocking in the middle of a full API process may be required. This usually happens if requirePage() needs to be called on a document.

The ViewerEdit sample on the samples page shows a situation where manual unlocking and re-locking may be used.

const doc = await PDFNet.PDFDoc.create();
doc.initSecurityHandler();
doc.lock();
// ...

// This section is only required to ensure the page is available
// for incremental download. At the moment the call to requirePage must be
// wrapped in this manner to avoid potential deadlocks and
// allow other parts of the viewer to run while the page is being downloaded.
doc.unlock();
await PDFNet.finishOperation();
// requirePage(pageNum) ensures that the first page is downloaded before it is accessed.
await doc.requirePage(1);
await PDFNet.beginOperation();
doc.lock();

Memory management

The full API automatically cleans up all objects in a process initialized using PDFNet.runWithCleanup() once the process has finished running. In almost all cases it is recommended to use this function to avoid memory leaks and complicated memory management.

Retain objects

In some situations you may wish to retain an object after the process has finished. A common example of this would be to create a document and retain it after processing. The ViewerPreprocess sample on the samples page has an example of how this can be done.

  • [Obj].takeOwnership()

For most use cases using PDFNet.runWithCleanup() and [Obj].takeOwnership() is sufficient. However, there are additional ways to manage memory:

Deallocate objects

Deallocates individual objects. Only objects that derive from PDFNet.Destroyable have this method.

  • [Obj].destroy()

Deallocate stack

Stack-based deallocation. Calling endDeallocateStack() will deallocate all objects that were created since the last call to PDFNet.startDeallocateStack().

  • PDFNet.startDeallocateStack()
  • PDFNet.endDeallocateStack()

In general, stack-based deallocation is recommended because it is easier to manage for larger sections of code.

More examples

Example of default/automatic deallocation:

async function main() {
  try {
    // documents require deallocation
    const doc = await PDFNet.PDFDoc.create();
    // object that requires deallocation
    const page_iter = await doc.getPageIterator();
    // object that requires deallocation
    const writer = await PDFNet.ElementWriter.create();
  } catch (err){
    console.log(err);
  }
}

// deallocates all objects once main finishes running
PDFNet.runWithCleanup(main);

Example of individual deallocation:

async function main() {
  try {
    const doc = await PDFNet.PDFDoc.create();
    const page_iter = await doc.getPageIterator();
    const writer = await PDFNet.ElementWriter.create();
  } catch (err){
    console.log(err);
  } finally {
    await doc.destroy();
    await page_iter.destroy();
    await writer.destroy();
  }
}
PDFNet.runWithoutCleanup(main);

Example of stack-based deallocation:

async function main() {
  try {
    await PDFNet.startDeallocateStack();
    const doc = await PDFNet.PDFDoc.create();
    const page_iter = await doc.getPageIterator();
    const writer = await PDFNet.ElementWriter.create();
    await PDFNet.endDeallocateStack();
  } catch (err){
    console.log(err);
  }
}
PDFNet.runWithoutCleanup(main);

Get the answers you need: Support

close

Free Trial

Get unlimited trial usage of PDFTron SDK to bring accurate, reliable, and fast document processing capabilities to any application or workflow.

Select a platform to get started with your free trial.

Unlimited usage. No email address required.