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:

1WebViewer({
2 ... // other options
3 // when inserting pages from another document, the 'useDownloader' option should be false
4 url: '/url/to/first.pdf',
5 useDownloader: false,
6}, document.getElementById('viewer'))
7 .then(async instance => {
8 const { documentViewer } = instance.Core;
9 const doc = documentViewer.getDocument();
10
11 const secondDoc = await instance.Core.createDocument('url/to/second.pdf');
12 const pagesToInsert = [4, 5, 6];
13 const pageIndexToInsert = doc.getPageCount() + 1;
14 // in this example doc.getPageCount() returns 3
15
16 doc.insertPages(secondDoc, pagesToInsert, pageIndexToInsert).then(() => {
17 doc.getPageCount(); // 6
18 });
19 });

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:

1Core.forceBackendType('ems');
2Core.setPDFWorkerPath('/lib/core/pdf'); // path to web workers
3Core.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 Core.createDocument(urlArray[0]);
23 }
24 const newDoc = await Core.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}

Did you find this helpful?

Trial setup questions?

Ask experts on Discord

Need other help?

Contact Support

Pricing or product questions?

Contact Sales