Section:

Inserting a page into a PDF using JavaScript

Pages can be inserted into the current PDF document using the insertBlankPages and insertPages functions. Inserting blank pages is fairly straight forward.

Insert blank pages

1// config.js
2const docViewer = instance.Core.documentViewer;
3
4docViewer.addEventListener('documentLoaded', async () => {
5 const doc = docViewer.getDocument();
6
7 const width = 612;
8 const height = 792;
9 docViewer.getPageCount(); // 3
10
11 // Insert blank pages
12 await doc.insertBlankPages([2, 3], width, height);
13 // The document now contains [page1, newBlankPage1, page2, newBlankPage2, page3]
14 docViewer.getPageCount(); // 5
15});

Insert a page from another document or the same document

More likely someone will want to insert pages from one PDF into another. To achieve this, instantiate a new Document object by passing the URL of the second PDF to createDocument function as a first parameter.

Currently there aren't any functions to duplicate pages in the current document directly. If you want to copy a page, you'll need to instantiate a new Document object and load the same PDF into it using createDocument and insert the page into the current document.

1// config.js
2const { documentViewer } = instance.Core;
3
4documentViewer.addEventListener('documentLoaded', async () => {
5 const doc = documentViewer.getDocument();
6 const pagesToInsert = [4, 5, 6];
7 const pageIndexToInsert = doc.getPageCount() + 1;
8 // in this example doc.getPageCount() returns 3
9
10
11 // use createDocument to create CoreControls.Document instance
12 const docToInsert = await instance.Core.CoreControls.createDocument('http://localhost/pdf/another.pdf', {});
13
14 doc.insertPages(docToInsert, pagesToInsert, pageIndexToInsert).then(() => {
15 // page 4, 5, and 6 from 'another.pdf' has been inserted into to the current pdf
16 doc.getPageCount(); // 6
17 });
18
19});

Did you find this helpful?

Trial setup questions?

Ask experts on Discord

Need other help?

Contact Support

Pricing or product questions?

Contact Sales