Split a PDF into separate PDF documents programmatically

This example shows how to programmatically create PDFs from select pages of the PDF currently loaded into the viewer. The two custom buttons ('Even pages' and 'Last page') are defined in config.js, they use the 'pages' option of the save() method to save just some pages of the current PDF as new PDFs.

window.onload = function(){ var viewer = new DsPdfViewer("#viewer", getViewerOptions()); configureViewerUI(viewer); viewer.open("/document-solutions/javascript-pdf-viewer/demos/product-bundles/assets/pdf/AcmeFinancialReport.pdf"); }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Split PDF into separate PDF documents programmatically</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="./src/styles.css"> <script src="/document-solutions/javascript-pdf-viewer/demos/product-bundles/build/dspdfviewer.js"></script> <script src="/document-solutions/javascript-pdf-viewer/demos/resource/js/init.js"></script> <script src="./src/config.js"></script> <script src="./src/app.js"></script> </head> <body> <div id="viewer"></div> </body> </html>
#viewer { height: 100%; }
function getViewerOptions() { return { workerSrc: "/document-solutions/javascript-pdf-viewer/demos/product-bundles/build/dspdfviewer.worker.js", supportApi: { apiUrl: window.top.SUPPORTAPI_URL, token: window.top.SUPPORTAPI_TOKEN, webSocketUrl: false }, friendlyFileName: "split-pdf.pdf", restoreViewStateOnLoad: false }; } function configureViewerUI(viewer) { viewer.toggleSidebar(false); viewer.toolbar.addItem({ text: "Even pages", title: "Create PDF from only even pages of the current document", key: "even-pages", enabled: false, action: async function () { let pages = ""; for (let i = 0; i < viewer.pageCount; i += 2) { pages += "," + i; } // alert(pages); await viewer.save("even-pages.pdf", { pages: pages }); }, onUpdate: function () { return { enabled: viewer.hasDocument && viewer.canEditDocument }; } }); viewer.toolbar.addItem({ text: "Last page", title: "Create PDF from the last page of the current document", key: "last-page", enabled: false, action: function () { const lastPageIndex = viewer.pageCount - 1; viewer.save("last-page.pdf", { pages: lastPageIndex + "-" + lastPageIndex }); }, onUpdate: function () { return { enabled: viewer.hasDocument && viewer.canEditDocument }; } }); viewer.toolbarLayout.viewer.mobile = viewer.toolbarLayout.viewer.default = ["open", '$navigation', "even-pages", "last-page", "pdf-organizer", "about"]; }