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

# Merge, copy, delete, rearrange PDF pages

Sample JavaScript code for using Apryse SDK to copy pages from one document to another, delete and rearrange pages, and use ImportPages() method for very efficient copy and merge operations.

{% 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="/web/full-api/full-api-overview.md" class="button primary">Full API</a><a href="https://showcase.apryse.com/pdf-page-manipulation-api" class="button primary">Live demo</a>
{% endhint %}

Sample JavaScript code for using Apryse SDK to copy pages from one document to another, delete and rearrange pages, and use ImportPages() method for very efficient copy and merge operations.

This sample is utilizing the option to [run code programmatically, without the Viewer.](/web/get-started/without-viewer.md)

Learn more about our [Web SDK](/web/get-started/guides.md) and [PDF Editing & Manipulation Library](/web/page-manipulation/manipulation.md).

### **Implementation steps**

Step 1: Follow [get started in your preferred web stack for WebViewer](/web/get-started/readme.md) Step 2: [Implement Full API code without viewer](/web/full-api/running-without-viewer.md) Step 3: Add the sample code provided in this guide

This full sample is included in the [manual download of WebViewer.](/web/get-started/manually.md#1-download-webviewer)

<pre class="language-js" data-line-numbers><code class="lang-js">//---------------------------------------------------------------------------------------
// Copyright (c) 2001-2023 by Apryse Software Inc. All Rights Reserved.
// Consult legal.txt regarding legal and license information.
//---------------------------------------------------------------------------------------
(exports => {
  exports.runPDFPageTest = () => {
    const PDFNet = exports.Core.PDFNet;

    const main = async () => {
      console.log('Beginning Test');
      const inputPath = '../TestFiles/';
      let docStoreArray = null;

      // split a pdf into multiple separate pdf pages
      try {
        const inDoc = await PDFNet.PDFDoc.createFromURL(inputPath + 'newsletter.pdf');
        inDoc.initSecurityHandler();
        inDoc.lock();

        console.log('PDF document initialized and locked');

        const pageCount = await inDoc.getPageCount();
        const pagesToSplit = Math.min(4, pageCount);

        // docStoreArray is used to leep track of the documents we have split up for later use.
        docStoreArray = [];
        for (let i = 1; i &#x3C;= pagesToSplit; ++i) {
          const newDoc = await PDFNet.PDFDoc.create();
          const filename = 'newsletter_split_page_' + i + '.pdf';
          newDoc.insertPages(0, inDoc, i, i, PDFNet.PDFDoc.InsertFlag.e_none);
          docStoreArray[i - 1] = newDoc;
          const docbuf = await newDoc.saveMemoryBuffer(PDFNet.SDFDoc.SaveOptions.e_linearized);
          saveBufferAsPDFDoc(docbuf, filename);
          console.log('Result saved as ' + filename);
        }
      } catch (err) {
        console.log(err.stack);
      }

      try {
        // start stack-based deallocation with startDeallocateStack. Later on when endDeallocateStack is called,
        // all objects in memory that were initialized since the most recent startDeallocateStack call will be
        // cleaned up. Doing this makes sure that memory growth does not get too high.
        await PDFNet.startDeallocateStack();
        const newDoc = await PDFNet.PDFDoc.create();
        newDoc.initSecurityHandler();
        newDoc.lock();

        console.log('Sample 2, merge several PDF documents into one:');

        for (let i = 1; i &#x3C;= docStoreArray.length; ++i) {
          const currDoc = docStoreArray[i - 1];
          const currDocPageCount = await currDoc.getPageCount();
          newDoc.insertPages(i, currDoc, 1, currDocPageCount, PDFNet.PDFDoc.InsertFlag.e_none);
        }
        const docbuf = await newDoc.saveMemoryBuffer(PDFNet.SDFDoc.SaveOptions.e_linearized);
        saveBufferAsPDFDoc(docbuf, 'newsletter_merged.pdf');
        await PDFNet.endDeallocateStack();
      } catch (err) {
        console.log(err.stack);
      }

      try {
        await PDFNet.startDeallocateStack();
        console.log('Sample 3, delete every second page');
        const inDoc = await PDFNet.PDFDoc.createFromURL(inputPath + 'newsletter.pdf');

        inDoc.initSecurityHandler();
        inDoc.lock();

        let pageNum = await inDoc.getPageCount();

        while (pageNum >= 1) {
          const itr = await inDoc.getPageIterator(pageNum);
          inDoc.pageRemove(itr);
          pageNum -= 2;
        }

        const docbuf = await inDoc.saveMemoryBuffer(PDFNet.SDFDoc.SaveOptions.e_linearized);
        saveBufferAsPDFDoc(docbuf, 'newsletter_page_removed.pdf');
        await PDFNet.endDeallocateStack();
      } catch (err) {
        console.log(err);
      }

      try {
        await PDFNet.startDeallocateStack();
        console.log('Sample 4, Insert a page at different locations');
        const in1Doc = await PDFNet.PDFDoc.createFromURL(inputPath + 'newsletter.pdf');
        in1Doc.initSecurityHandler();
        in1Doc.lock();

        const in2Doc = await PDFNet.PDFDoc.createFromURL(inputPath + 'fish.pdf');
        in2Doc.initSecurityHandler();
        in2Doc.lock();

        const srcPage = await in2Doc.getPageIterator(1);
        const dstPage = await in1Doc.getPageIterator(1);
        let pageNum = 1;
        while (await dstPage.hasNext()) {
          if (pageNum++ % 3 === 0) {
            in1Doc.pageInsert(dstPage, await srcPage.current());
          }
          dstPage.next();
        }

        const docbuf = await in1Doc.saveMemoryBuffer(PDFNet.SDFDoc.SaveOptions.e_linearized);
        saveBufferAsPDFDoc(docbuf, 'newsletter_page_insert.pdf');
        console.log('done');
        await PDFNet.endDeallocateStack();
      } catch (err) {
        console.log(err.stack);
      }

      try {
        await PDFNet.startDeallocateStack();
        console.log('Sample 5, replicate pages within a single document');
        const doc = await PDFNet.PDFDoc.createFromURL(inputPath + 'newsletter.pdf');
        doc.initSecurityHandler();

        // Replicate the cover page three times (copy page #1 and place it before the
        // seventh page in the document page sequence)
        const cover = await doc.getPage(1);
        const p7 = await doc.getPageIterator(7);
        doc.pageInsert(p7, cover);
        doc.pageInsert(p7, cover);
        doc.pageInsert(p7, cover);
        // replicate cover page two more times by placing it before and after existing pages
        doc.pagePushFront(cover);
        doc.pagePushBack(cover);

        const docbuf = await doc.saveMemoryBuffer(PDFNet.SDFDoc.SaveOptions.e_linearized);
        saveBufferAsPDFDoc(docbuf, 'newsletter_page_clone.pdf');
        console.log('done saving newsletter_page_clone.pdf');
        await PDFNet.endDeallocateStack();
      } catch (err) {
        console.log(err.stack);
      }
    };

    // add your own license key as the second parameter, e.g. PDFNet.runWithCleanup(main, '<code class="expression">visitor.claims.wvKey || "YOUR_LICENSE_KEY"</code>')
    PDFNet.runWithCleanup(main);
  };
})(window);
// eslint-disable-next-line spaced-comment
//# sourceURL=PDFPageTest.js
</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/pdfpagetest.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.
