How to load multiple files in a single viewer instance

Q: How can I load multiple PDF files and show them in a single viewer instance?

A: You can merge your documents with our document editor API and load the resulting merged document.

You’ll need to follow these steps to merge documents on your Web clients using the PSPDFKit:

  1. First create a headless instance (i.e. without any UI) 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 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 is the last document.
    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. And finally cleanup 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.

Note: If you need to merge files frequently, we recommend preparing your files in advance on the server side. You can use Document Editor server API with the same importDocument operations to achieve just that.