> For the complete documentation index, see [llms.txt](https://docs.apryse.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.apryse.com/web/get-started/samples/showcase-demo-pdf-page-manipulation-api.md).

# PDF Page Manipulation API Showcase Demo Code Sample

Perform page manipulation, including split, merge, append, replicate, reorder, and more.

{% hint style="info" %}
**Requirements**

*These packages are required to use these features in production. Trial keys have unlimited access to all features*

<a href="/web/get-started/readme.md" class="button primary">Web SDK</a><a href="https://apryse.com/capabilities#PageManipulation" class="button primary">Package: Page Manipulation</a><a href="https://showcase.apryse.com/pdf-page-manipulation-api" class="button primary">Live demo</a>
{% endhint %}

Easily perform changes to PDF pages, including split, merge, append, replicate, reorder, and more.

This demo allows you to:

* Choose your own PDF file.
* Perform programmatic page manipulation:
  * Split
  * Merge
  * Append
  * Replicate
  * Reorder
  * and more
* Download edited document.

**Implementation steps**

To add PDF Page Manipulation capability with WebViewer: Step 1: [Get started with WebViewer](/web/get-started/readme.md) in your preferred web stack. Step 2: Add the ES6 JavaScript sample code provided in this guide.

Once you generate your license key, it will automatically be included in your sample code below.

{% @apryse-license-key/apryse-license-key platform="WEB\_VIEWER" variant="compact" %}

{% tabs %}
{% tab title="index.js" %}

<pre class="language-js" data-line-numbers><code class="lang-js">
// ES6 Compliant Syntax
// GitHub Copilot - GPT-4 Model - October 16, 2025
// File: pdf-page-manipulation-api/index.js

import WebViewer from '@pdftron/webviewer';
import { saveAs } from 'file-saver';

const licenseKey = '<code class="expression">visitor.claims.wvKey || "YOUR_WEBVIEWER_LICENSE_KEY"</code>';
// Global variables
const element = document.getElementById('viewer');
let instance = null;

// Initialize WebViewer
function initializeWebViewer() {
  if (!element) {
    console.error('Viewer div not found.');
    return;
  }
  // Initialize WebViewer
  WebViewer({
    path: '/lib',
    licenseKey: licenseKey,
    initialDoc: 'https://apryse.s3.us-west-1.amazonaws.com/public/files/samples/WebviewerDemoDoc.pdf',
    enableFilePicker: true, // Enable file picker to open files. In WebViewer -> menu icon -> Open File
  }, element).then((inst) => {
    instance = inst;
    const { documentViewer} = instance.Core;
    documentViewer.addEventListener('documentLoaded', () => {
      const doc = documentViewer.getDocument();
      console.log(`Document loaded with ${doc.getPageCount()} pages.`);
      createUIElements().then(() => {
        // Now initialize rotateAngle options values (after UI elements are created)
        if (window.rotateAngle) {
          window.rotateAngle.children[0].value = instance.Core.PageRotation.E_90;
          window.rotateAngle.children[1].value = instance.Core.PageRotation.E_180;
          window.rotateAngle.children[2].value = instance.Core.PageRotation.E_270;
        } else {
          console.error('rotateAngle element not found after UI creation');
        }
        // activate thumbnails panel
        instance.UI.openElements(['tabPanel']);
        instance.UI.setActiveTabInPanel({ tabPanel: 'tabPanel', tabName: 'thumbnailsPanel' });
      });
    });
  });
} // Close initializeWebViewer function

// validate page number input
const validPageNumber = (pageNum, doc) => {
  if (pageNum > doc.getPageCount() || pageNum &#x3C; 1) {
    alert('Please enter a valid page number.');
    return false;
  }
  return true;
}

// convert a string like "1,2,5-7" to an array of numbers [1,2,5,6,7]
const parseStringToNumberArray = (val, maxVal) => {
  // check for valid number, comma, or dash pattern
  if (!/^[0-9]+([,-][0-9]+)*$/.test(val)) {
    return [];
  }
  const numbers = [];
  val.split(',').forEach((group) => {
    const range = group.split('-');
    const start = Number(range[0]);
    let end = Number(range.length === 1 ? range[0] : range[1]);
    if (end > maxVal) {
      end = maxVal;
    }
    for (let i = start; i &#x3C;= end; i++) {
      numbers.push(i);
    }
  });
  return numbers;
}

// delete specified pages from document
const deletePages = () => {
  const doc = instance.Core.documentViewer.getDocument();
  const pageNumbers = pagesRange.value;
  const result = parseStringToNumberArray(pageNumbers, doc.getPageCount());
  if (!validPageNumber(pageNumbers, doc)) return;
  if (result.length === doc.getPageCount()) {
    alert('Cannot delete all pages in the document.');
    return;
  }
  if (result.length > 0) {
    doc.removePages(result);
  } else {
    alert('Please enter a comma or dash separated list of valid page numbers ex 1,2,3-5 for the first 5 pages');
  }
}

// rotate specified pages in document
const rotatePages = () => {
  const pageNumbers = pagesRange.value;
  const rotation = Number(rotateAngle.value);
  const doc = instance.Core.documentViewer.getDocument();
  if (!validPageNumber(pageNumbers, doc)) return;
  let result = [];
  if (pageNumbers) {
    result = parseStringToNumberArray(pageNumbers, doc.getPageCount());
  } else {
    // No page numbers provided, rotating all pages
    for (let i = 1; i &#x3C;= doc.getPageCount(); i++) {
      result.push(i);
    }
  }
  if (result.length > 0) {
    doc.rotatePages(result, rotation);
  } else {
    alert('Please enter a comma or dash separated list of valid page numbers ex 1,2,3-5 for the first 5 pages');
  }
}

// move a page to a new location in the document
const movePage = () => {
  const doc = instance.Core.documentViewer.getDocument();
  const pageOne = Number(pageInput.value);
  let pageTwo = Number(locationInput.value);
  if (!validPageNumber(pageOne, doc) || !validPageNumber(pageTwo, doc)) return;
  if (pageOne &#x3C; pageTwo) pageTwo++; // adjust for removing the "from" page
  doc.movePages([pageOne], pageTwo);
}

// insert a blank page at the specified location
const insertBlankPage = () => {
  let pageNumber = Number(pageInput.value);
  const doc = instance.Core.documentViewer.getDocument();
  if (pageNumber === -1) { // append to end
    pageNumber = doc.getPageCount() + 1;
  } else if (!validPageNumber(pageNumber, doc)) return;
  const pageSize = doc.getPageInfo(1);
  doc.insertBlankPages([pageNumber], pageSize.width, pageSize.height);
}

// extract specified pages from document and save as a new file
const extractPages = async () => {
  const pageNumbers = pagesRange.value;
  const doc = instance.Core.documentViewer.getDocument();
  const pageCount = doc.getPageCount();
  if (!validPageNumber(pageNumbers, doc)) return;
  let pagesToExtract = [];
  if (pageNumbers) {
    pagesToExtract = parseStringToNumberArray(pageNumbers, pageCount);
  } else {
    for (let i = 1; i &#x3C;= pageCount; i++) {
      pagesToExtract.push(i);
    }
  }
  if (pagesToExtract.length > 0) {
    const annotList = instance.Core.annotationManager.getAnnotationsList().filter((annot) => pagesToExtract.indexOf(annot.PageNumber) > -1);
    const xfdfString = await instance.Core.annotationManager.exportAnnotations({ annotationList: annotList });
    doc.extractPages(pagesToExtract, xfdfString).then((data) => {
      const arr = new Uint8Array(data);
      const blob = new Blob([arr], { type: 'application/pdf' });
      saveAs(blob, 'extracted.pdf');
    });
  } else {
    alert('Please enter a comma or dash separated list of valid page numbers ex 1,2,3-5 for the first 5 pages');
  }
}

// crop the specified page by the specified pixel amounts from 4 sides
const cropPage = () => {
  const pageNumber = Number(pageInput.value);
  const doc = instance.Core.documentViewer.getDocument();
  if (!validPageNumber(pageNumber, doc)) return;
  const top = Number(cropTop.value);
  const bottom = Number(cropBottom.value);
  const left = Number(cropLeft.value);
  const right = Number(cropRight.value);
  doc.cropPages([pageNumber], top, bottom, left, right);
}

// merge an uploaded document into the current document at the specified location
const mergeDocuments = () => {
  if (!window.newDoc) {
    alert('Please upload a document to merge first');
    return;
  }
  const pageNumbers = pagesRange.value;
  let pagesToInsert = [];
  if (pageNumbers) {
    pagesToInsert = parseStringToNumberArray(pageNumbers, window.newDoc.getPageCount());
  } else {
    for (let i = 1; i &#x3C;= window.newDoc.getPageCount(); i++) {
      pagesToInsert.push(i);
    }
  }
  const locationToInsert = Number(locationInput.value);
  if (pagesToInsert.length > 0) {
    instance.Core.documentViewer.getDocument().insertPages(window.newDoc, pagesToInsert, locationToInsert);
  } else {
    alert('Please enter a comma or dash separated list of valid page numbers ex 1,2,3-5 for the first 5 pages');
  }
}

// Expose functions to global scope for UI elements
window.deletePages = deletePages;
window.rotatePages = rotatePages;
window.movePage = movePage;
window.insertBlankPage = insertBlankPage;
window.extractPages = extractPages;
window.cropPage = cropPage;
window.mergeDocuments = mergeDocuments;
window.parseStringToNumberArray = parseStringToNumberArray;
window.validPageNumber = validPageNumber;

// UI Elements
// Function to create and initialize UI elements
function createUIElements() {
  return new Promise((resolve) => {
    // Create a container for all controls (label, dropdown, and buttons)
    // Dynamically load ui-elements.js if not already loaded
    if (typeof UIElements === 'undefined') {
      const script = document.createElement('script');
      script.src = '/showcase-demos/pdf-page-manipulation-api/ui-elements.js';
      script.onload = () => {
        console.log('ui-elements.js loaded successfully');
        UIElements.init(instance);
        resolve(); // Resolve when UI elements are created
      };
      script.onerror = () => {
        console.error('Failed to load ui-elements.js');
        resolve(); // Resolve even on error to prevent hanging
      };
      document.head.appendChild(script);
    } else {
      console.log('UIElements already available, initializing...');
      UIElements.init(instance);
      resolve(); // Resolve immediately if UIElements is already loaded
    }
  });
}

// Initialize WebViewer when the window loads
initializeWebViewer();
</code></pre>

{% endtab %}

{% tab title="ui-elements.js" %}
{% code title="ui-elements.js" lineNumbers="true" %}

```js
// ES6 Compliant Syntax
// GitHub Copilot, Claude Sonnet 4 (Preview), October 16, 2025
// File: showcase-demos/pdf-page-manipulation-api/ui-elements.js

class UIElements {

  static init(instance) {
    this.createUIElements(instance);
  }

  static createUIElements(instance) {
    const element = document.getElementById('viewer');
    let newDoc = null; // document to merge into the current document

    // Check if controls container already exists
    let controlsContainer = document.getElementById('controls-container');
    if (controlsContainer) {
      console.log('Controls container already exists, skipping creation');
      return; // Exit early if container already exists
    }

    // UI section
    // Create a container and insert the controls in it
    controlsContainer = document.createElement('div');
    const commandsList = document.createElement('select');
    controlsContainer.appendChild(commandsList);
    const uploadButton = document.createElement('input');
    controlsContainer.appendChild(uploadButton);
    const pagesRange = document.createElement('input');
    controlsContainer.appendChild(pagesRange);
    const rotateAngle = document.createElement('select');
    window.rotateAngle = rotateAngle; // expose to global scope for function access 
    controlsContainer.appendChild(rotateAngle);
    const topLabel = document.createElement('label');
    topLabel.textContent = 'Top';
    controlsContainer.appendChild(topLabel);
    const cropTop = document.createElement('input');
    controlsContainer.appendChild(cropTop);
    const bottomLabel = document.createElement('label');
    bottomLabel.textContent = 'Bottom';
    controlsContainer.appendChild(bottomLabel);
    const cropBottom = document.createElement('input');
    controlsContainer.appendChild(cropBottom);
    const leftLabel = document.createElement('label');
    leftLabel.textContent = 'Left';
    controlsContainer.appendChild(leftLabel);
    const cropLeft = document.createElement('input');
    controlsContainer.appendChild(cropLeft);
    const rightLabel = document.createElement('label');
    rightLabel.textContent = 'Right';
    controlsContainer.appendChild(rightLabel);
    const cropRight = document.createElement('input');
    controlsContainer.appendChild(cropRight);
    cropTop.type = cropBottom.type = cropLeft.type = cropRight.type = 'number';
    cropTop.className = cropBottom.className = cropLeft.className = cropRight.className = 'elements-style';
    cropTop.value = cropBottom.value = cropLeft.value = cropRight.value = 50;

    const pageInput = document.createElement('input');
    controlsContainer.appendChild(pageInput);
    const locationInput = document.createElement('input');
    controlsContainer.appendChild(locationInput);
    const runCommandButton = document.createElement('button');
    controlsContainer.appendChild(runCommandButton);
    const br = document.createElement('br');
    controlsContainer.appendChild(br);
    const promptLabel = document.createElement('label');
    controlsContainer.appendChild(promptLabel);
    controlsContainer.className = 'control-container';

    uploadButton.type = 'file';
    uploadButton.accept = '.pdf,.jpg,.jpeg,.png';
    uploadButton.onchange = async (e) => {
      const file = e.target.files[0];
      const split = file.name.split('.');
      const ext = split[split.length - 1];
      newDoc = await instance.Core.createDocument(file, {
        extension: ext,
        filename: file.name,
      });
      
      // Update the global reference so it's available for merge operations
      window.newDoc = newDoc;
      console.log('File uploaded and newDoc updated:', file.name);
    }

    rotateAngle.className = commandsList.className = 'list-style';
    pagesRange.className = pageInput.className = locationInput.className = 'elements-style';
    uploadButton.className = runCommandButton.className = 'btn';
    pagesRange.type = 'text';
    pagesRange.placeholder = '1,2,3-5';
    [90, 180, 270].forEach(deg => { // create rotate angle UI elements
      const option = document.createElement('option');
      //option.value will be set after WebViewer is initialized because values are in instance.Core.PageRotation
      option.textContent = deg.toString()+'\u00b0'; // degree symbol °
      rotateAngle.appendChild(option);
    });
    pageInput.type = 'text';
    pageInput.placeholder = 'Page #';
    locationInput.type = 'text';
    locationInput.placeholder = 'to page #';
    runCommandButton.textContent = 'Run Command';
    


    runCommandButton.onclick = () => commandsArray[commandsList.selectedIndex].executeCommand();
    const commandsArray = [
      { value: 'Select Command', executeCommand: () => alert('Select a command from the list'), visibleItems: [],
        text: 'Select a command from the list' },
      { value: 'Rotate pages',  executeCommand: () => window.rotatePages(), visibleItems: [pagesRange, rotateAngle],
        text: 'Enter a comma or dash separated list of page numbers to rotate (leave empty for all pages)' },
      { value: 'Delete pages',  executeCommand: () => window.deletePages(), visibleItems: [pagesRange],
        text: 'Enter a comma or dash separated list of page numbers to delete' },
      { value: 'Move page', executeCommand: () => window.movePage(), visibleItems: [pageInput, locationInput],
      text: 'Enter  page number to move then location to move it to' },
      { value: 'Insert blank page', executeCommand: () => window.insertBlankPage(), visibleItems: [pageInput],
        text: 'Enter a page number to add a blank page at (-1 to append at end)' },
      { value: 'Split / extract pages', executeCommand: () => window.extractPages(), visibleItems: [pagesRange],
        text: 'Enter a comma or dash separated list of page numbers to extract (leave empty for all pages)' },
      { value: 'Crop pages', executeCommand: () => window.cropPage(), visibleItems: [pageInput, cropTop, cropBottom, cropLeft, cropRight, topLabel, bottomLabel, leftLabel, rightLabel],
        text: 'Enter amount of pixels to crop, and then a page number (cropping cannot be undone)' },
      { value: 'Merge documents', executeCommand: () => window.mergeDocuments(), visibleItems: [uploadButton, pagesRange, locationInput],
        text: 'Upload document to merge then enter list of pages to insert (leave empty for all pages) and position to insert the pages at' },
    ];
    commandsArray.forEach(cmd => { // create a UI element in the list for each command
      const option = document.createElement('option');
      option.value = cmd.value;
      option.textContent = cmd.value;
      commandsList.appendChild(option);
    });
    const hideAllItems = () => [uploadButton, pagesRange, rotateAngle, pageInput, locationInput, cropTop, cropBottom, cropLeft, cropRight, topLabel, bottomLabel, leftLabel, rightLabel].forEach(item => item.style.display = 'none');
    commandsList.onchange = (e) => {
      const selectedIndex = e.target.selectedIndex;
      promptLabel.textContent = commandsArray[selectedIndex].text;
      hideAllItems();
      commandsArray[selectedIndex].visibleItems.forEach(item => item.style.display = '');
    }
    commandsList.selectedIndex = 0;
    promptLabel.textContent = commandsArray[0].text;
    hideAllItems();
    controlsContainer.id = 'controls-container';// set the id for CSS styling
    element.insertBefore(controlsContainer, element.firstChild);

        // Store elements globally for function access
    window.pagesRange = pagesRange;
    window.rotateAngle = rotateAngle;
    window.pageInput = pageInput;
    window.locationInput = locationInput;
    window.cropTop = cropTop;
    window.cropBottom = cropBottom;
    window.cropLeft = cropLeft;
    window.cropRight = cropRight;
    window.newDoc = newDoc;
  }
}

window.UIElements = UIElements; // Expose the class to the global scope

```

{% endcode %}
{% endtab %}

{% tab title="index.css" %}
{% code title="index.css" lineNumbers="true" %}

```css
/* Controls Container */
.control-container {
    align-items: center;
    gap: 1px;
    margin: 5px;
    padding-bottom: 5px;
    border-bottom: 1px solid #e0e0e0;
    background-color: rgba(112, 198, 255, 0.2   /* Light blue background for contrast */);
}

.elements-style {
    margin-right: 7px;
    padding: 5px;
    border: 1px solid #ccc;
    border-radius: 4px;
    font-size: 13px;
    width: 70px;
}

.list-style {
    margin-right: 7px;
    padding: 5px;
    border: 1px solid #ccc;
    border-radius: 4px;
    font-size: 13px;
}

/* General Button Styles */
.btn {
    background-color: #007bff;
    margin: 0 10px;
    padding: 5px 10px;
    border: 1px solid #ccc;
    border-radius: 4px;
    cursor: pointer;
    font-size: 14px;
    transition: all 0.2s ease;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    color: white;
}

.btn:hover {
    background-color: #0056b3;
    transform: translateY(-1px);
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}

.btn:active {
    transform: translateY(1px);
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
}

.btn:disabled {
    background-color: #ccc;
    cursor: not-allowed;
    box-shadow: none;
}

/* Responsive Design */
@media (max-width: 768px) {
    .btn {
        width: 100%;
        margin: 5px 0;
    }
}

```

{% endcode %}
{% endtab %}
{% endtabs %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.apryse.com/web/get-started/samples/showcase-demo-pdf-page-manipulation-api.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
