Sample JavaScript code to manipulate a PDF document in the browser (no servers or other external dependencies required). This sample lets you rotate a PDF page and delete, move or insert a new page into your document. You can also crop pages in your PDF or merge multiple documents into a consolidated file. In the case of MS Office files (DOCX, XLSX, PPTX), documents are converted to PDF files where modifications are saved. This sample works on all browsers (including IE11) and mobile devices without using plug-ins. For an example view our Page Manipulation demo. Learn more about our Web SDK.
1// eslint-disable-next-line
2/* global saveAs */
3// eslint-disable-next-line no-undef
4const WebViewerConstructor = isWebComponent() ? WebViewer.WebComponent : WebViewer;
5
6WebViewerConstructor(
7 {
8 path: '../../../lib',
9 useDownloader: false,
10 initialDoc: '../../../samples/files/demo.pdf',
11 },
12 document.getElementById('viewer')
13).then(instance => {
14 samplesSetup(instance);
15 const { documentViewer, PageRotation, annotationManager, createDocument } = instance.Core;
16
17 documentViewer.addEventListener('documentLoaded', () => {
18 const doc = documentViewer.getDocument();
19
20 const editDropdown = document.getElementById('edit');
21 const moveFromDropdown = document.getElementById('move-from');
22 const moveToDropdown = document.getElementById('move-to');
23 const insertAtDropdown = document.getElementById('insert-at');
24 const extractAtList = document.getElementById('extract-list');
25 const rotateButton = document.getElementById('rotate');
26 const cropButton = document.getElementById('crop');
27 const deleteButton = document.getElementById('delete');
28 const moveButton = document.getElementById('move');
29 const insertButton = document.getElementById('insert');
30 const extractButton = document.getElementById('extract');
31 const filePickerButton = document.getElementById('file-picker');
32
33 // Updates page dropdowns when page count changes
34 const updatePages = pageCount => {
35 editDropdown.innerHTML = '';
36 moveFromDropdown.innerHTML = '';
37 moveToDropdown.innerHTML = '';
38 insertAtDropdown.innerHTML = '';
39 extractAtList.value = pageCount > 1 ? `1-${pageCount}` : 1;
40
41 let i;
42 let option;
43 for (i = 0; i < pageCount; i++) {
44 option = document.createElement('option');
45 option.innerHTML = i + 1;
46 editDropdown.appendChild(option);
47 moveFromDropdown.appendChild(option.cloneNode(true));
48 moveToDropdown.appendChild(option.cloneNode(true));
49 insertAtDropdown.appendChild(option.cloneNode(true));
50 }
51
52 const clonedOption = option.cloneNode(true);
53 clonedOption.innerHTML = i + 1;
54 insertAtDropdown.appendChild(clonedOption);
55 };
56
57 rotateButton.onclick = () => {
58 // Rotate pages
59 doc.rotatePages([Number(editDropdown.value)], PageRotation.E_90);
60 };
61
62 cropButton.onclick = () => {
63 // Crop pages
64 doc.cropPages([Number(editDropdown.value)], 40, 40, 40, 40);
65 };
66
67 deleteButton.onclick = () => {
68 const newPageCount = doc.getPageCount() - 1;
69 // Delete pages
70 doc.removePages([Number(editDropdown.value)]);
71 updatePages(newPageCount);
72 };
73
74 moveButton.onclick = () => {
75 const pageFrom = Number(moveFromDropdown.value);
76 let pageTo = Number(moveToDropdown.value);
77 if (pageFrom < pageTo) {
78 pageTo++;
79 }
80
81 // Move pages
82 doc.movePages([pageFrom], pageTo);
83 };
84
85 insertButton.onclick = () => {
86 const info = doc.getPageInfo(1);
87 const width = info.width;
88 const height = info.height;
89 const newPageCount = doc.getPageCount() + 1;
90 // Insert blank pages
91 doc.insertBlankPages([Number(insertAtDropdown.value)], width, height);
92 updatePages(newPageCount);
93 };
94
95 extractButton.onclick = async function() {
96 extractAtList.setCustomValidity('');
97 if (!extractAtList.checkValidity()) {
98 extractAtList.reportValidity();
99 return; // exit since invalid input
100 }
101 const pagesToExtract = [];
102 const pageCount = doc.getPageCount();
103 extractAtList.value.split(',').forEach(group => {
104 const range = group.split('-');
105 const start = Number(range[0]);
106 let end = Number(range.length === 1 ? range[0] : range[1]);
107 if (end > pageCount) {
108 end = pageCount;
109 }
110 for (let i = start; i <= end; i++) {
111 pagesToExtract.push(i);
112 }
113 });
114 const annotationList = annotationManager.getAnnotationsList().filter(annot => pagesToExtract.indexOf(annot.PageNumber) > -1);
115 const xfdfString = await annotationManager.exportAnnotations({ annotationList });
116 const data = await doc.extractPages(pagesToExtract, xfdfString);
117 const arr = new Uint8Array(data);
118 const blob = new Blob([arr], { type: 'application/pdf' });
119 saveAs(blob, 'extracted.pdf');
120 };
121
122 extractAtList.oninvalid = function() {
123 extractAtList.setCustomValidity('Should only contain valid page numbers, commas, or dashes ex 1,2,3-5');
124 };
125
126 filePickerButton.onchange = e => {
127 const file = e.target.files[0];
128 createDocument(file, {} /* , license key here */).then(newDoc => {
129 const pages = [];
130 for (let i = 0; i < newDoc.getPageCount(); i++) {
131 pages.push(i + 1);
132 }
133 const newPageCount = doc.getPageCount() + newDoc.getPageCount();
134 // Insert (merge) pages
135 doc.insertPages(newDoc, pages, doc.getPageCount() + 1);
136 updatePages(newPageCount);
137 });
138 };
139
140 updatePages(doc.getPageCount());
141 });
142});
Did you find this helpful?
Trial setup questions?
Ask experts on DiscordNeed other help?
Contact SupportPricing or product questions?
Contact Sales