How to Load Multiple Files in a Single Viewer Instance

To load multiple PDF files and show them in a single viewer instance, you can merge your documents with our document editor API and load the resulting merged document.

Follow the steps below to merge documents on your web clients using PSPDFKit.

  1. Create a headless instance (i.e. without a user interface) with the first document loaded:

const instance = await PSPDFKit.load({
  ...configuration,
  document: first_document,
  headless: true
});
  1. Fetch the rest of documents:

const documents = [second_document_url, third_document_url];
const documentBlobs = await Promise.all(
  documents.map((url) => fetch(url).then((result) => result.blob()))
);
  1. Create an importDocument operation for each document that should be appended:

// We need to keep track of the target page index for the imported document.
let afterPageIndex = instance.totalPageCount - 1;

const mergeDocumentOperations = await Promise.all(
  documentBlobs.map(async (blob, idx) => {
    const operation = {
      type: "importDocument",
      afterPageIndex,
      treatImportedDocumentAsOnePage: false,
      document: blob
    };

    // Retrieve page count of the merged document to calculate page index
    // of the next imported document. This can be skipped for the last
    // operation since we don't care how large the last document is.
    if (idx < documentBlobs.length - 1) {
      const documentInstance = await PSPDFKit.load({
        ...configuration,
        document: await blob.arrayBuffer(),
        headless: true
      });
      afterPageIndex += documentInstance.totalPageCount - 1;
      PSPDFKit.unload(documentInstance);
    }
    return operation;
  })
);
  1. Run instance.exportPDFWithOperations to apply the operations:

const mergedDocument = await instance.exportPDFWithOperations(
  mergeDocumentOperations
);
  1. Clean up the headless instance and load the merged document:

PSPDFKit.unload(instance);

PSPDFKit.load({
  ...configuration,
  document: mergedDocument
});

This has been tested with PSPDFKit for Web 2020.6.4.

Information

If you need to merge files frequently, we recommend preparing your files in advance on the server side. You can use the document editor server API with the same `importDocument` operations.