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

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

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.

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

Did you find this helpful?

Trial setup questions?

Ask experts on Discord

Need other help?

Contact Support

Pricing or product questions?

Contact Sales