> 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/page-operations.md).

# Page operations

Manipulate PDF with JavaScript library. You can crop, rotate, add, move, merge and export PDF pages directly in the browser.

{% 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 %}

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.

Learn more about our [Web SDK](/web/get-started/guides.md).

### **Implementation steps**

To manipulate files with WebViewer:

Step 1: Follow [get started in your preferred web stack for WebViewer](/web/get-started/readme.md) Step 2: Add the 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" %}

<pre class="language-js" data-line-numbers><code class="lang-js">// eslint-disable-next-line
/* global saveAs */
// eslint-disable-next-line no-undef
const WebViewerConstructor = isWebComponent() ? WebViewer.WebComponent : WebViewer;

WebViewerConstructor(
  {
    path: '../../../lib',
    useDownloader: false,
    initialDoc: '../../../samples/files/demo.pdf',
  },
  document.getElementById('viewer')
).then(instance => {
  samplesSetup(instance);
  const { documentViewer, PageRotation, annotationManager, createDocument } = instance.Core;

  documentViewer.addEventListener('documentLoaded', () => {
    const doc = documentViewer.getDocument();

    const editDropdown = document.getElementById('edit');
    const moveFromDropdown = document.getElementById('move-from');
    const moveToDropdown = document.getElementById('move-to');
    const insertAtDropdown = document.getElementById('insert-at');
    const extractAtList = document.getElementById('extract-list');
    const rotateButton = document.getElementById('rotate');
    const cropButton = document.getElementById('crop');
    const deleteButton = document.getElementById('delete');
    const moveButton = document.getElementById('move');
    const insertButton = document.getElementById('insert');
    const extractButton = document.getElementById('extract');
    const filePickerButton = document.getElementById('file-picker');

    // Updates page dropdowns when page count changes
    const updatePages = pageCount => {
      editDropdown.innerHTML = '';
      moveFromDropdown.innerHTML = '';
      moveToDropdown.innerHTML = '';
      insertAtDropdown.innerHTML = '';
      extractAtList.value = pageCount > 1 ? `1-${pageCount}` : 1;

      let i;
      let option;
      for (i = 0; i &#x3C; pageCount; i++) {
        option = document.createElement('option');
        option.innerHTML = i + 1;
        editDropdown.appendChild(option);
        moveFromDropdown.appendChild(option.cloneNode(true));
        moveToDropdown.appendChild(option.cloneNode(true));
        insertAtDropdown.appendChild(option.cloneNode(true));
      }

      const clonedOption = option.cloneNode(true);
      clonedOption.innerHTML = i + 1;
      insertAtDropdown.appendChild(clonedOption);
    };

    rotateButton.onclick = () => {
      // Rotate pages
      doc.rotatePages([Number(editDropdown.value)], PageRotation.E_90);
    };

    cropButton.onclick = () => {
      // Crop pages
      doc.cropPages([Number(editDropdown.value)], 40, 40, 40, 40);
    };

    deleteButton.onclick = () => {
      const newPageCount = doc.getPageCount() - 1;
      // Delete pages
      doc.removePages([Number(editDropdown.value)]);
      updatePages(newPageCount);
    };

    moveButton.onclick = () => {
      const pageFrom = Number(moveFromDropdown.value);
      let pageTo = Number(moveToDropdown.value);
      if (pageFrom &#x3C; pageTo) {
        pageTo++;
      }

      // Move pages
      doc.movePages([pageFrom], pageTo);
    };

    insertButton.onclick = () => {
      const info = doc.getPageInfo(1);
      const width = info.width;
      const height = info.height;
      const newPageCount = doc.getPageCount() + 1;
      // Insert blank pages
      doc.insertBlankPages([Number(insertAtDropdown.value)], width, height);
      updatePages(newPageCount);
    };

    extractButton.onclick = async function() {
      extractAtList.setCustomValidity('');
      if (!extractAtList.checkValidity()) {
        extractAtList.reportValidity();
        return; // exit since invalid input
      }
      const pagesToExtract = [];
      const pageCount = doc.getPageCount();
      extractAtList.value.split(',').forEach(group => {
        const range = group.split('-');
        const start = Number(range[0]);
        let end = Number(range.length === 1 ? range[0] : range[1]);
        if (end > pageCount) {
          end = pageCount;
        }
        for (let i = start; i &#x3C;= end; i++) {
          pagesToExtract.push(i);
        }
      });
      const annotationList = annotationManager.getAnnotationsList().filter(annot => pagesToExtract.indexOf(annot.PageNumber) > -1);
      const xfdfString = await annotationManager.exportAnnotations({ annotationList });
      const data = await doc.extractPages(pagesToExtract, xfdfString);
      const arr = new Uint8Array(data);
      const blob = new Blob([arr], { type: 'application/pdf' });
      saveAs(blob, 'extracted.pdf');
    };

    extractAtList.oninvalid = function() {
      extractAtList.setCustomValidity('Should only contain valid page numbers, commas, or dashes ex 1,2,3-5');
    };

    filePickerButton.onchange = e => {
      const file = e.target.files[0];
      createDocument(file, {}, '<code class="expression">visitor.claims.wvKey || "YOUR_LICENSE_KEY"</code>').then(newDoc => {
        const pages = [];
        for (let i = 0; i &#x3C; newDoc.getPageCount(); i++) {
          pages.push(i + 1);
        }
        const newPageCount = doc.getPageCount() + newDoc.getPageCount();
        // Insert (merge) pages
        doc.insertPages(newDoc, pages, doc.getPageCount() + 1);
        updatePages(newPageCount);
      });
    };

    updatePages(doc.getPageCount());
  });
});
</code></pre>


---

# 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/page-operations.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.
