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

# Edit PDF Elements - Sample Code

The sample code shows how to edit the page display list and how to modify graphics state attributes on existing PDF Elements using Apryse WebViewer in JavaScript. In particular the sample program stri

{% 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="/web/full-api/full-api-overview.md" class="button primary">Full API</a>
{% endhint %}

Sample JavaScript code for using Apryse SDK to programmatically edit an existing PDF document's page display list and the graphics state attributes on existing elements.

In particular, this sample strips all images from the page and changes the text color to blue. Some of Apryse SDK's other functions for programmatically editing PDFs include the [Cos/SDF low-level API](/web/get-started/samples/sdftest.md), [page manipulation](/web/get-started/samples/pdfpagetest.md), and more.

Learn more about our [Web SDK](/web/get-started/guides.md) and [PDF Editing & Manipulation Library](/core/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: [Enable the full API ](/web/full-api/full-api-overview.md)by passing the `fullAPI` option into the WebViewer constructor Step 3: Add the sample code provided in this guide

This full sample is one of many 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.runElementEditTest = () => {
    const PDFNet = exports.Core.PDFNet;

    async function ProcessElements(reader, writer, visited) {
      await PDFNet.startDeallocateStack();
      const colorspace = await PDFNet.ColorSpace.createDeviceRGB();
      const redColor = await PDFNet.ColorPt.init(1, 0, 0, 0);
      const blueColor = await PDFNet.ColorPt.init(0, 0, 1, 0);

      for (let element = await reader.next(); element !== null; element = await reader.next()) {
        const elementType = await element.getType();
        let gs;
        let formObj;
        let formObjNum = null;
        switch (elementType) {
          case PDFNet.Element.Type.e_image:
          case PDFNet.Element.Type.e_inline_image:
            // remove all images by skipping them
            break;
          case PDFNet.Element.Type.e_path:
            // Set all paths to red
            gs = await element.getGState();
            gs.setFillColorSpace(colorspace);
            gs.setFillColorWithColorPt(redColor);
            writer.writeElement(element);
            break;
          case PDFNet.Element.Type.e_text:
            // Set all text to blue
            gs = await element.getGState();
            gs.setFillColorSpace(colorspace);
            gs.setFillColorWithColorPt(blueColor);
            writer.writeElement(element);
            break;
          case PDFNet.Element.Type.e_form:
            writer.writeElement(element);
            formObj = await element.getXObject();
            formObjNum = formObj.getObjNum();
            // if XObject not yet processed
            if (visited.indexOf(formObjNum) === -1) {
              // Set Replacement
              const insertedObj = await formObj.getObjNum();
              if (!visited.includes(insertedObj)) {
                visited.push(insertedObj);
              }
              const newWriter = await PDFNet.ElementWriter.create();
              reader.formBegin();
              newWriter.beginOnObj(formObj, true);
              await ProcessElements(reader, newWriter, visited);
              newWriter.end();
              reader.end();
            }
            break;
          default:
            writer.writeElement(element);
        }
      }
      await PDFNet.endDeallocateStack();
    }

    const main = async () => {
      console.log('Beginning Test');
      const ret = 0;
      // Relative path to the folder containing test files.
      const inputUrl = '../TestFiles/';
      const doc = await PDFNet.PDFDoc.createFromURL(inputUrl + 'newsletter.pdf');
      doc.initSecurityHandler();
      doc.lock();

      console.log('PDF document initialized and locked');
      const writer = await PDFNet.ElementWriter.create();
      const reader = await PDFNet.ElementReader.create();
      const visited = [];

      const totalPageNumber = await doc.getPageCount();

      const itr = await doc.getPageIterator(1);

      // Read every page
      for (itr; await itr.hasNext(); itr.next()) {
        const page = await itr.current();
        const currentPageNumber = await page.getIndex();
        console.log('Processing elements on page ' + currentPageNumber + '/' + totalPageNumber);
        const sdfObj = await page.getSDFObj();
        // Set Replacement
        const insertedObj = await sdfObj.getObjNum();
        if (!visited.includes(insertedObj)) {
          visited.push(insertedObj);
        }
        reader.beginOnPage(page);
        writer.beginOnPage(page, PDFNet.ElementWriter.WriteMode.e_replacement, false);
        await ProcessElements(reader, writer, visited);
        writer.end();
        reader.end();
      }

      const docBuffer = await doc.saveMemoryBuffer(PDFNet.SDFDoc.SaveOptions.e_remove_unused);
      saveBufferAsPDFDoc(docBuffer, 'newsletter_edited.pdf');
      console.log('Done.');
      return ret;
    };

    // 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=ElementEditTest.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/elementedittest.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.
