skip to Main Content

I’m trying to load a PDF URL using Apryse’s webViewer method. When I use the method as specified in their docs it works as intended (as shown below). But I don’t want to initialize a new webViewer every function call so I tried to initialize webViewer once and call loadDocument() on the instance but that doesn’t work. I don’t get any errors or anything. What am I doing wrong?

Function calling:

loadDocViewer('https://pdfobject.com/pdf/sample.pdf')

Doesn’t work:

let webViewerInstance;

WebViewer({
    path: '/@pdftron/webviewer/public',
}, document.getElementById('doc-viewer'))
    .then(instance => {
        webViewerInstance = instance
    })
    .catch(error => {
        console.error('Error initializing WebViewer:', error);
    });

function loadDocViewer(url) {
    if (!webViewerInstance) {
        console.error('Doc Viewer is not initialized! Try again in a bit.');
        return;
    }

    webViewerInstance.UI.loadDocument(url);
}

Works:

function loadDocViewer(url) {
    WebViewer({
        path: '/@pdftron/webviewer/public',
    }, document.getElementById('doc-viewer'))
        .then(instance => {
            instance.UI.loadDocument(url);
        })
        .catch(error => {
            console.error('Error initializing WebViewer:', error);
        });
}

2

Answers


  1. But I don’t want to initialize a new webViewer every function

    In that case, i recommend you save the promise to a variable and reuse it:

    let promise;
    function loadDocViewer(url) {
      if (!promise) {
        promise = WebViewer(
          { path: "/@pdftron/webviewer/public" },
          document.getElementById("doc-viewer"),
        );
      }
    
      return promise
        .then((instance) => {
          return instance.UI.loadDocument(url);
        })
        .catch((error) => {
          console.error("Error initializing WebViewer:", error);
        });
    }
    

    The first time loadDocViewer runs it will create the promise and then have to wait a little for it to resolve. Subsequent times will not have to wait since the promise is already resolved.

    Login or Signup to reply.
  2. Since the WebViewer constructor is asynchronous, you will want to wait for WebViewer to fully resolve before calling your loadDocViewer function.
    See this guide for reference:
    https://docs.apryse.com/documentation/web/guides/events/loading-events/#webviewer-promise-ready-event

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search