Some test text!

Search
Hamburger Icon

Web / Guides / Merge files

Merging PDF pages using JavaScript

Two or more PDF files can be merged together by using the insertPage function on the Document instance. See the following example:

WebViewer({
  ... // other options
  // when inserting pages from another document, the 'useDownloader' option should be false
  url: '/url/to/first.pdf',
  useDownloader: false,
}, document.getElementById('viewer'))
  .then(async instance => {
    const { documentViewer } = instance.Core;
    const doc = documentViewer.getDocument();

    const secondDoc = await instance.Core.createDocument('url/to/second.pdf');
    const pagesToInsert = [4, 5, 6];
    const pageIndexToInsert = doc.getPageCount() + 1;
    // in this example doc.getPageCount() returns 3

    doc.insertPages(secondDoc, pagesToInsert, pageIndexToInsert).then(() => {
      doc.getPageCount(); // 6
    });
  });

Merge files without WebViewer

When using Core without WebViewer, certain flags need to set to make Core function correctly and to be able to load web workers from the correct path. You need to set setPDFWorkerPath, forceBackendType and disableEmbeddedJavaScript as shown:

Core.forceBackendType('ems');
Core.setPDFWorkerPath('/lib/core/pdf'); // path to web workers
Core.disableEmbeddedJavaScript(); // disabling pdf javascript

// array of url of PDFs to merge
const urls = [
  'https://pdftron.s3.amazonaws.com/downloads/pl/demo-annotated.pdf',
  'https://pdftron.s3.amazonaws.com/downloads/pl/Cheetahs.pdf',
  'https://pdftron.s3.amazonaws.com/downloads/pl/magazine-short.pdf',
];

mergeDocuments(urls).then(mergedPdf => {
  // merged pdf, here you can download it using mergedPdf.getFileData
  
});


// recursive function with promise 
function mergeDocuments(urlArray, nextCount = 1, doc = null) {
  return new Promise(async function(resolve, reject) {
    if (!doc) {
      doc = await Core.createDocument(urlArray[0]);
    }
    const newDoc = await Core.createDocument(urlArray[nextCount]);
    const newDocPageCount = newDoc.getPageCount();

    // create an array containing 1…N
    const pages = Array.from({ length: newDocPageCount }, (v, k) => k + 1);
    const pageIndexToInsert = doc.getPageCount() + 1;
    // in this example doc.getPageCount() returns 3

    doc.insertPages(newDoc, pages, pageIndexToInsert)
      .then(result => resolve({
        next: urlArray.length - 1 > nextCount,
        doc: doc,
      })
    );
    // end Promise
  }).then(res => {
    return res.next ?
      mergeDocuments(urlArray, nextCount + 1, res.doc) :
      res.doc;
  });
}

Trial setup questions? Ask experts on Discord
Need other help? Contact Support
Pricing or product questions? Contact Sales