1CoreControls.forceBackendType('ems');
2CoreControls.setPDFWorkerPath('/lib/core/pdf'); // path to web workers
3CoreControls.disableEmbeddedJavaScript(); // disabling pdf javascript
4
5// array of url of PDFs to merge
6const urls = [
7 'https://pdftron.s3.amazonaws.com/downloads/pl/demo-annotated.pdf',
8 'https://pdftron.s3.amazonaws.com/downloads/pl/Cheetahs.pdf',
9 'https://pdftron.s3.amazonaws.com/downloads/pl/magazine-short.pdf',
10];
11
12mergeDocuments(urls).then(mergedPdf => {
13 // merged pdf, here you can download it using mergedPdf.getFileData
14
15});
16
17
18// recursive function with promise
19function mergeDocuments(urlArray, nextCount = 1, doc = null) {
20 return new Promise(async function(resolve, reject) {
21 if (!doc) {
22 doc = await CoreControls.createDocument(urlArray[0]);
23 }
24 const newDoc = await CoreControls.createDocument(urlArray[nextCount]);
25 const newDocPageCount = newDoc.getPageCount();
26
27 // create an array containing 1…N
28 const pages = Array.from({ length: newDocPageCount }, (v, k) => k + 1);
29 const pageIndexToInsert = doc.getPageCount() + 1;
30 // in this example doc.getPageCount() returns 3
31
32 doc.insertPages(newDoc, pages, pageIndexToInsert)
33 .then(result => resolve({
34 next: urlArray.length - 1 > nextCount,
35 doc: doc,
36 })
37 );
38 // end Promise
39 }).then(res => {
40 return res.next ?
41 mergeDocuments(urlArray, nextCount + 1, res.doc) :
42 res.doc;
43 });
44}