> 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/core/get-started/samples/elementedittest.md).

# Edit PDF - ElementEdit

Here is a complete PDF and DOCX editing guide, provided in Python, C++, C#, Java, Node.js (JavaScript), PHP, Ruby, Go and VB. Modify properties, edit text, bookmarks, annotation and lot more using COS

Sample 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, provided in Python, C++, C#, Java, Node.js (JavaScript), PHP, Ruby, Go and VB. You can also build a GUI with [interactive PDF editor widgets](/core/get-started/samples/pdfviewform.md). Some of Apryse SDK's other functions for programmatically editing PDFs include the [Cos/SDF low-level API](/core/get-started/samples/sdftest.md), [page manipulation](/core/get-started/samples/pdfpagetest.md), and more. Learn more about our [Server SDK](/core/get-started/get-started.md) and [PDF Editing & Manipulation Library](/core/page-manipulation/manipulation.md).

{% tabs %}
{% tab title="C#" %}
{% code lineNumbers="true" %}

```csharp
//
// Copyright (c) 2001-2024 by Apryse Software Inc. All Rights Reserved.
//

using System;
using System.Collections.Generic;

using pdftron;
using pdftron.Common;
using pdftron.Filters;
using pdftron.SDF;
using pdftron.PDF;

using XSet = System.Collections.Generic.List<int>;

namespace ElementEditTestCS
{
	/// <summary>
	/// The sample code shows how to edit the page display list and how to modify graphics state 
	/// attributes on existing Elements. In particular the sample program strips all images from 
	/// the page, changes path fill color to red, and changes text fill color to blue. 
	/// </summary>
	class Class1
	{
		private static pdftron.PDFNetLoader pdfNetLoader = pdftron.PDFNetLoader.Instance();
		static Class1() {}
		
		static void ProcessElements(ElementReader reader, ElementWriter writer, XSet visited)
		{
			Element element;
			while ((element = reader.Next()) != null) // Read page contents
			{
				switch (element.GetType())
				{
					case Element.Type.e_image:
					case Element.Type.e_inline_image:
							// remove all images by skipping them
							break;
					case Element.Type.e_path:
						{
							// Set all paths to red color.
							GState gs = element.GetGState();
							gs.SetFillColorSpace(ColorSpace.CreateDeviceRGB());
							gs.SetFillColor(new ColorPt(1, 0, 0));
							writer.WriteElement(element);
							break;
						}
					case Element.Type.e_text:
						{
							// Set all text to blue color.
							GState gs = element.GetGState();
							gs.SetFillColorSpace(ColorSpace.CreateDeviceRGB());
							gs.SetFillColor(new ColorPt(0, 0, 1));
							writer.WriteElement(element);
							break;
						}
					case Element.Type.e_form:
						{
							writer.WriteElement(element); // write Form XObject reference to current stream

							Obj form_obj = element.GetXObject();
							if (form_obj != null && !visited.Contains(form_obj.GetObjNum())) // if this XObject has not been processed
							{
								// recursively process the Form XObject
								visited.Add(form_obj.GetObjNum());
								ElementWriter new_writer = new ElementWriter();

								reader.FormBegin();
								new_writer.Begin(form_obj, true);

								reader.ClearChangeList();
								new_writer.SetDefaultGState(reader);

								ProcessElements(reader, new_writer, visited);
								new_writer.End();
								reader.End();
							}
							break;
						}
					default:
						writer.WriteElement(element);
						break;
				}
			}
		}

		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main(string[] args)
		{
			PDFNet.Initialize(PDFTronLicense.Key);

			// Relative path to the folder containing test files.
			string input_path = "../../../../TestFiles/";
			string output_path = "../../../../TestFiles/Output/";
			string input_filename = "newsletter.pdf";
			string output_filename = "newsletter_edited.pdf";

			try
			{
				Console.WriteLine("Opening the input file...");
				using (PDFDoc doc = new PDFDoc(input_path + input_filename))
				{
					doc.InitSecurityHandler();

					ElementWriter writer = new ElementWriter();
					ElementReader reader = new ElementReader();
					XSet visited = new XSet();

					PageIterator itr = doc.GetPageIterator();

					while (itr.HasNext())
					{
						try
						{
							Page page = itr.Current();
							visited.Add(page.GetSDFObj().GetObjNum());

							reader.Begin(page);
							writer.Begin(page, ElementWriter.WriteMode.e_replacement, false, true, page.GetResourceDict());

							ProcessElements(reader, writer, visited);
							writer.End();
							reader.End();

							itr.Next();
						}
						catch (PDFNetException e)
						{
							Console.WriteLine(e.Message);
						}
					}

					doc.Save(output_path + output_filename, SDFDoc.SaveOptions.e_remove_unused);
					Console.WriteLine("Done. Result saved in {0}...", output_filename);
				}
			}
			catch (PDFNetException e)
			{
				Console.WriteLine(e.Message);
			}
			PDFNet.Terminate();
		}
	}
}
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code lineNumbers="true" %}

```cpp
//---------------------------------------------------------------------------------------
// Copyright (c) 2001-2024 by Apryse Software Inc. All Rights Reserved.
// Consult legal.txt regarding legal and license information.
//---------------------------------------------------------------------------------------

#include <PDF/PDFNet.h>
#include <PDF/PDFDoc.h>
#include <PDF/ElementWriter.h>
#include <PDF/ElementReader.h>
#include <SDF/Obj.h>
#include <set>
#include <iostream>
#include "../../LicenseKey/CPP/LicenseKey.h"

using namespace pdftron;
using namespace std;
using namespace SDF;
using namespace PDF;


//---------------------------------------------------------------------------------------
// The sample code shows how to edit the page display list and how to modify graphics state 
// attributes on existing Elements. In particular the sample program strips all images from 
// the page, changes path fill color to red, and changes text fill color to blue. 
//---------------------------------------------------------------------------------------

// XObjects are guaranteed to have unique object numbers 
typedef set<pdftron::UInt32> XObjSet;


static void ProcessElements(ElementReader& reader, ElementWriter& writer, XObjSet& visited) 
{
	Element element;
	while (element = reader.Next()) // Read page contents
	{
		switch (element.GetType())
		{
		case Element::e_image: 
		case Element::e_inline_image: 
			// remove all images by skipping them			
			break;
		case Element::e_path:
			{
				// Set all paths to red color.
				GState gs = element.GetGState();
				gs.SetFillColorSpace(ColorSpace::CreateDeviceRGB());
				ColorPt cp(1, 0, 0);
				gs.SetFillColor(cp);
				writer.WriteElement(element);
				break;
			}
		case Element::e_text:
			{
				// Set all text to blue color.
				GState gs = element.GetGState();
				gs.SetFillColorSpace(ColorSpace::CreateDeviceRGB());
				ColorPt cp(0, 0, 1);
				gs.SetFillColor(cp);
				writer.WriteElement(element);
				break;
			}
		case Element::e_form:
			{
				writer.WriteElement(element); // write Form XObject reference to current stream

				Obj form_obj = element.GetXObject();
				if (visited.find(form_obj.GetObjNum()) == visited.end()) // if this XObject has not been processed
				{
					// recursively process the Form XObject
					visited.insert(form_obj.GetObjNum());
					ElementWriter new_writer;
					reader.FormBegin();
					new_writer.Begin(form_obj);

					reader.ClearChangeList();
					new_writer.SetDefaultGState(reader); 

					ProcessElements(reader, new_writer, visited);
					new_writer.End();
					reader.End();
				}
				break; 
			}
		default:
			writer.WriteElement(element);
		}
	}
}

int main(int argc, char *argv[])
{
	int ret = 0;
	PDFNet::Initialize(LicenseKey);

	// Relative path to the folder containing test files.
	string input_path =  "../../TestFiles/";
	string output_path = "../../TestFiles/Output/";
	string input_filename = "newsletter.pdf";
	string output_filename = "newsletter_edited.pdf";

	try 
	{
		cout << "Opening the input file..." << endl;
		PDFDoc doc(input_path + input_filename);
		doc.InitSecurityHandler();

		ElementWriter writer;
		ElementReader reader;
		XObjSet visited;
		
		// Process each page in the document
		for (PageIterator itr = doc.GetPageIterator();itr.HasNext();itr.Next())
		{
			try {
				Page page = itr.Current();
				visited.insert(page.GetSDFObj().GetObjNum());

				reader.Begin(page);
				writer.Begin(page, ElementWriter::e_replacement, false, true, page.GetResourceDict());
				ProcessElements(reader, writer, visited);
				writer.End();
				reader.End();
			}
			catch (Common::Exception& e)
			{
				cout << e << endl;
			}
		}

		// Save modified document
		doc.Save(output_path + output_filename, SDFDoc::e_remove_unused, 0);		
		cout << "Done. Result saved in " << output_filename <<"..." << endl;
	}
	catch(Common::Exception& e)
	{
		cout << e << endl;
		ret = 1;
	}
	catch(...)
	{
		cout << "Unknown Exception" << endl;
		ret = 1;
	}
	PDFNet::Terminate();
	return ret;
}
```

{% endcode %}
{% endtab %}

{% tab title="Go" %}
{% code lineNumbers="true" %}

```go
//---------------------------------------------------------------------------------------
// Copyright (c) 2001-2021 by PDFTron Systems Inc. All Rights Reserved.
// Consult LICENSE.txt regarding license information.
//---------------------------------------------------------------------------------------

package main
import (
	"fmt"
	. "pdftron"
)

import  "pdftron/Samples/LicenseKey/GO"

//---------------------------------------------------------------------------------------
// The sample code shows how to edit the page display list and how to modify graphics state 
// attributes on existing Elements. In particular the sample program strips all images from 
// the page, changes path fill color to red, and changes text color to blue. 
//---------------------------------------------------------------------------------------

func ProcessElements(reader ElementReader, writer ElementWriter, omap map[uint]Obj){
    element := reader.Next()     // Read page contents
    for element.GetMp_elem().Swigcptr() != 0{
        etype := element.GetType()
        if etype == ElementE_image{
            // remove all images by skipping them
        }else if etype == ElementE_inline_image{            
            // remove all images by skipping them
        }else if etype == ElementE_path{
            // Set all paths to red color.
            gs := element.GetGState()
            gs.SetFillColorSpace(ColorSpaceCreateDeviceRGB())
            gs.SetFillColor(NewColorPt(1.0, 0.0, 0.0))
            writer.WriteElement(element)
        }else if etype == ElementE_text{    // Process text strings...
            // Set all text to blue color.
            gs := element.GetGState()
            gs.SetFillColorSpace(ColorSpaceCreateDeviceRGB())
            cp := NewColorPt(0.0, 0.0, 1.0)
            gs.SetFillColor(cp)
            writer.WriteElement(element)
        }else if etype == ElementE_form{    // Recursively process form XObjects
            o := element.GetXObject()
            omap[o.GetObjNum()] = o
            writer.WriteElement(element)
        }else{
            writer.WriteElement(element)
		}
        element = reader.Next()
	}
}

func main(){
    PDFNetInitialize(PDFTronLicense.Key)
    
    // Relative path to the folder containing the test files.
    inputPath := "../../TestFiles/"
    outputPath := "../../TestFiles/Output/"
    inputFilename := "newsletter.pdf"
    outputFilename := "newsletter_edited.pdf"
    
    
    // Open the test file
    fmt.Println("Opening the input file...")
    doc := NewPDFDoc(inputPath + inputFilename)
    doc.InitSecurityHandler()
    
    writer := NewElementWriter()
    reader := NewElementReader()
    
    itr := doc.GetPageIterator()
    
    for itr.HasNext(){
        page := itr.Current()
        reader.Begin(page)
        writer.Begin(page, ElementWriterE_replacement, false)
        var map1 = make(map[uint]Obj)
        ProcessElements(reader, writer, map1)
        writer.End()
        reader.End()
		
        var map2 = make(map[uint]Obj)
        for !(len(map1) == 0 && len(map2) == 0){
            for k, v := range map1{
                obj := v
                writer.Begin(obj)
                reader.Begin(obj, page.GetResourceDict())
                ProcessElements(reader, writer, map2)
                reader.End()
                writer.End()
                delete(map1, k)
			}
            if (len(map1) == 0 && len(map2) != 0){
                //map1.update(map2)
				for key, value := range map2{         
					map1[key] = value 
				}
				//map2.clear()
				for k := range map2 {
					delete(map2, k)
				}
			}
		}
        itr.Next()
    }
	
    doc.Save(outputPath + outputFilename, uint(SDFDocE_remove_unused))
    doc.Close()
    PDFNetTerminate()
    fmt.Println("Done. Result saved in " + outputFilename +"...")
}
```

{% endcode %}
{% endtab %}

{% tab title="Java" %}
{% code lineNumbers="true" %}

```java
//---------------------------------------------------------------------------------------
// Copyright (c) 2001-2024 by Apryse Software Inc. All Rights Reserved.
// Consult legal.txt regarding legal and license information.
//---------------------------------------------------------------------------------------

import com.pdftron.pdf.*;
import com.pdftron.sdf.SDFDoc;
import com.pdftron.common.PDFNetException;

import java.util.*;

import com.pdftron.sdf.Obj;

//---------------------------------------------------------------------------------------
// The sample code shows how to edit the page display list and how to modify graphics state 
// attributes on existing Elements. In particular the sample program strips all images from 
// the page, changes path fill color to red, and changes text color to blue. 
//---------------------------------------------------------------------------------------
public class ElementEditTest {
    public static void processElements(ElementWriter writer, ElementReader reader, Set<Integer> visited)  throws PDFNetException {
        Element element;
		while ((element = reader.next()) != null) {
			switch (element.getType()) {
				case Element.e_image:
				case Element.e_inline_image:
					// remove all images by skipping them
					break;
				case Element.e_path: {
					// Set all paths to red color.
					GState gs = element.getGState();
					gs.setFillColorSpace(ColorSpace.createDeviceRGB());
					gs.setFillColor(new ColorPt(1, 0, 0));
					writer.writeElement(element);
				}
				break;
				case Element.e_text: {
					// Set all text to blue color.
					GState gs = element.getGState();
					gs.setFillColorSpace(ColorSpace.createDeviceRGB());
					gs.setFillColor(new ColorPt(0, 0, 1));
					writer.writeElement(element);
				}
				break;
				case Element.e_form: {
					writer.writeElement(element); // write Form XObject reference to current stream
					Obj form_obj = element.getXObject();
					if (!visited.contains((int) form_obj.getObjNum())) // if this XObject has not been processed
					{
						// recursively process the Form XObject
						visited.add((int) form_obj.getObjNum());
						ElementWriter new_writer = new ElementWriter();
						reader.formBegin();
						new_writer.begin(form_obj);

						reader.clearChangeList();
						new_writer.setDefaultGState(reader);  

						processElements(new_writer, reader, visited);
						new_writer.end();
						reader.end();
					}
				}
				break;
				default:
					writer.writeElement(element);
					break;
			}
		}
  
	}

	public static void main(String[] args) {

		PDFNet.initialize(PDFTronLicense.Key());

		// Relative path to the folder containing test files.
		String input_path = "../../TestFiles/";
		String output_path = "../../TestFiles/Output/";
		String input_filename = "newsletter.pdf";
		String output_filename = "newsletter_edited.pdf";

		System.out.println("Opening the input file...");
		try (PDFDoc doc = new PDFDoc((input_path + input_filename))) {
			doc.initSecurityHandler();

			ElementWriter writer = new ElementWriter();
			ElementReader reader = new ElementReader();
			Set<Integer> visited = new TreeSet<Integer>();

			PageIterator itr = doc.getPageIterator();
			while (itr.hasNext()) {
				try{
					Page page = itr.next();
					visited.add((int) page.getSDFObj().getObjNum());

					reader.begin(page);
					writer.begin(page, ElementWriter.e_replacement, false, true, page.getResourceDict());

					processElements(writer, reader, visited);
					writer.end();
					reader.end();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

			// Save modified document
			doc.save(output_path + output_filename, SDFDoc.SaveMode.REMOVE_UNUSED, null);
			System.out.println("Done. Result saved in " + output_filename + "...");
		} catch (Exception e) {
			e.printStackTrace();
		}

		PDFNet.terminate();
	}
}
```

{% endcode %}
{% endtab %}

{% tab title="JavaScript" %}
{% code lineNumbers="true" %}

```js
//---------------------------------------------------------------------------------------
// Copyright (c) 2001-2024 by Apryse Software Inc. All Rights Reserved.
// Consult legal.txt regarding legal and license information.
//---------------------------------------------------------------------------------------


const { PDFNet } = require('@pdftron/pdfnet-node');
const PDFTronLicense = require('../LicenseKey/LicenseKey');

((exports) => {

  exports.runElementEditTest = () => {

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

      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);
            await gs.setFillColorWithColorPt(redColor);
            await writer.writeElement(element);
            break;
          case PDFNet.Element.Type.e_text:
            // Set all text to blue
            gs = await element.getGState();
            gs.setFillColorSpace(colorspace);
            await gs.setFillColorWithColorPt(blueColor);
            await writer.writeElement(element);
            break;
          case PDFNet.Element.Type.e_form:
            await writer.writeElement(element);
            formObj = await element.getXObject();
            formObjNum = await 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();
              await reader.formBegin();
              await newWriter.beginOnObj(formObj);
              await ProcessElements(reader, newWriter, visited);
              await newWriter.end();
              await reader.end();
            }
            break;
          default:
            await writer.writeElement(element);
        }
      }
      await PDFNet.endDeallocateStack();
    }

    const main = async () => {
      // Relative path to the folder containing test files.
      const inputPath = '../TestFiles/';
      try {
        console.log('Opening the input file...');
        const doc = await PDFNet.PDFDoc.createFromFilePath(inputPath + 'newsletter.pdf');
        doc.initSecurityHandler();

        const writer = await PDFNet.ElementWriter.create();
        const reader = await PDFNet.ElementReader.create();
        const visited = [];

        const itr = await doc.getPageIterator(1);

        // Process each page in the document
        for (itr; await itr.hasNext(); itr.next()) {
          const page = await itr.current();
          const sdfObj = await page.getSDFObj();
          const insertedObj = await sdfObj.getObjNum();
          if (!visited.includes(insertedObj)) {
            visited.push(insertedObj);
          }
          await reader.beginOnPage(page);
          await writer.beginOnPage(page, PDFNet.ElementWriter.WriteMode.e_replacement, false, true, await page.getResourceDict());
          await ProcessElements(reader, writer, visited);
          await writer.end();
          await reader.end();
        }

        await doc.save(inputPath + 'Output/newsletter_edited.pdf', PDFNet.SDFDoc.SaveOptions.e_remove_unused);
        console.log('Done. Result saved in newsletter_edited.pdf...');
      } catch (err) {
        console.log(err);
      }
    };

    PDFNet.runWithCleanup(main, PDFTronLicense.Key).catch(function (error) { console.log('Error: ' + JSON.stringify(error)); }).then(function () { return PDFNet.shutdown(); });
  };
  exports.runElementEditTest();
})(exports);
// eslint-disable-next-line spaced-comment
//# sourceURL=ElementEditTest.js
```

{% endcode %}
{% endtab %}

{% tab title="PHP" %}
{% code lineNumbers="true" %}

```php
<?php
#---------------------------------------------------------------------------------------
# Copyright (c) 2001-2023 by Apryse Software Inc. All Rights Reserved.
# Consult LICENSE.txt regarding license information.
#---------------------------------------------------------------------------------------
if(file_exists("../../../PDFNetC/Lib/PDFNetPHP.php"))
include("../../../PDFNetC/Lib/PDFNetPHP.php");
include("../../LicenseKey/PHP/LicenseKey.php");

#---------------------------------------------------------------------------------------
# The sample code shows how to edit the page display list and how to modify graphics state 
# attributes on existing Elements. In particular the sample program strips all images from 
# the page and changes text color to blue. 
#---------------------------------------------------------------------------------------

# Relative path to the folder containing the test files.
$input_path = getcwd()."/../../TestFiles/";
$output_path = $input_path."Output/";
$input_filename = "newsletter.pdf";
$output_filename = "newsletter_edited.pdf";

function ProcessElements($reader, $writer, $map) {
	while (($element = $reader->Next()) != null) 	// Read page contents
	{
		switch ($element->GetType())
		{		
		case Element::e_image: 
		case Element::e_inline_image: 
			// remove all images by skipping them
			break;
		case Element::e_path:
			{
				// Set all paths to red color.
				$gs = $element->GetGState();
				$gs->SetFillColorSpace(ColorSpace::CreateDeviceRGB());
				$gs->SetFillColor(new ColorPt(1.0, 0.0, 0.0));
				$writer->WriteElement($element);
				break;
			}
		case Element::e_text:// Process text strings...
			{
				// Set all text to blue color.
				$gs = $element->GetGState();
				$gs->SetFillColorSpace(ColorSpace::CreateDeviceRGB());
				$cp = new ColorPt(0.0, 0.0, 1.0);
				$gs->SetFillColor($cp);
				$writer->WriteElement($element);
				break;
			}
		case Element::e_form:// Recursively process form XObjects
			{
				$o = $element->GetXObject();
				$objNum = $o->GetObjNum();
				$map[$objNum] = $o;
				$writer->WriteElement($element);
				break; 
			}
		default:
			$writer->WriteElement($element);
		}
	}
}

	PDFNet::Initialize($LicenseKey);
	PDFNet::GetSystemFontList();    // Wait for fonts to be loaded if they haven't already. This is done because PHP can run into errors when shutting down if font loading is still in progress.
	

	// Open the test file
	echo nl2br("Opening the input file...\n");
	$doc = new PDFDoc($input_path.$input_filename);
	$doc->InitSecurityHandler();

	$writer = new ElementWriter();
	$reader = new ElementReader();
	
	$itr = $doc->GetPageIterator();

	while ($itr->HasNext())
	{
		$page = $itr->Current();
		$reader->Begin($page);
		$writer->Begin($page, ElementWriter::e_replacement, false);
		$map1 = array();
		ProcessElements($reader, $writer, $map1);
		$writer->End();
		$reader->End();
		
		$map2 = array();
		while (!(empty($map1) && empty($map2)))
		{
			foreach ($map1 as $k=>$v)
			{
				$obj = $v;
				$writer->Begin($obj);
				$reader->Begin($obj, $page->GetResourceDict());
				ProcessElements($reader, $writer, $map2);
				$reader->End();
				$writer->End();

				unset($map1[$k]);
			}
			if (empty($map1) && !empty($map2))
			{
				$map1 = $map1 + $map2;
				$map2 = array();
			}
		}
		$itr->Next();
	}

	$doc->Save($output_path.$output_filename, SDFDoc::e_remove_unused);	
	PDFNet::Terminate();	
	echo nl2br("Done. Result saved in ".$output_filename."...\n");
?>
```

{% endcode %}
{% endtab %}

{% tab title="Python" %}
{% code lineNumbers="true" %}

```python
#---------------------------------------------------------------------------------------
# Copyright (c) 2001-2023 by Apryse Software Inc. All Rights Reserved.
# Consult LICENSE.txt regarding license information.
#---------------------------------------------------------------------------------------

import site
site.addsitedir("../../../PDFNetC/Lib")
import sys
from PDFNetPython import *

sys.path.append("../../LicenseKey/PYTHON")
from LicenseKey import *

#---------------------------------------------------------------------------------------
# The sample code shows how to edit the page display list and how to modify graphics state 
# attributes on existing Elements. In particular the sample program strips all images from 
# the page, changes path fill color to red, and changes text color to blue. 
#---------------------------------------------------------------------------------------

def ProcessElements(reader, writer, map):
    element = reader.Next()     # Read page contents
    while element != None:
        type = element.GetType()
        if type == Element.e_image:
            # remove all images by skipping them
            pass
        elif type == Element.e_inline_image:            
            # remove all images by skipping them
            pass
        elif type == Element.e_path:
            # Set all paths to red color.
            gs = element.GetGState()
            gs.SetFillColorSpace(ColorSpace.CreateDeviceRGB())
            gs.SetFillColor(ColorPt(1, 0, 0))
            writer.WriteElement(element)
        elif type == Element.e_text:    # Process text strings...
            # Set all text to blue color.
            gs = element.GetGState()
            gs.SetFillColorSpace(ColorSpace.CreateDeviceRGB())
            cp = ColorPt(0, 0, 1)
            gs.SetFillColor(cp)
            writer.WriteElement(element)
        elif type == Element.e_form:    # Recursively process form XObjects
            o = element.GetXObject()
            map[o.GetObjNum()] = o
            writer.WriteElement(element)
        else:
            writer.WriteElement(element)
        element = reader.Next()

def main():
    PDFNet.Initialize(LicenseKey)
    
    # Relative path to the folder containing the test files.
    input_path = "../../TestFiles/"
    output_path = "../../TestFiles/Output/"
    input_filename = "newsletter.pdf"
    output_filename = "newsletter_edited.pdf"
    
    
    # Open the test file
    print("Opening the input file...")
    doc = PDFDoc(input_path + input_filename)
    doc.InitSecurityHandler()
    
    writer = ElementWriter()
    reader = ElementReader()
    
    itr = doc.GetPageIterator()
    
    while itr.HasNext():
        page = itr.Current()
        reader.Begin(page)
        writer.Begin(page, ElementWriter.e_replacement, False)
        map1 = {}
        ProcessElements(reader, writer, map1)
        writer.End()
        reader.End()
		
        map2 = {}
        while (map1 or map2):
            for k in map1.keys():
                obj = map1[k]
                writer.Begin(obj)
                reader.Begin(obj, page.GetResourceDict())
                ProcessElements(reader, writer, map2)
                reader.End()
                writer.End()

                del map1[k]
            if (not map1 and map2):
                map1.update(map2)
                map2.clear()
        itr.Next()
        
    doc.Save(output_path + output_filename, SDFDoc.e_remove_unused)
    doc.Close()
    PDFNet.Terminate()
    print("Done. Result saved in " + output_filename +"...")
    
if __name__ == '__main__':
    main()
```

{% endcode %}
{% endtab %}

{% tab title="Ruby" %}
{% code lineNumbers="true" %}

```ruby
#---------------------------------------------------------------------------------------
# Copyright (c) 2001-2023 by Apryse Software Inc. All Rights Reserved.
# Consult LICENSE.txt regarding license information.
#---------------------------------------------------------------------------------------

require '../../../PDFNetC/Lib/PDFNetRuby'
include PDFNetRuby
require '../../LicenseKey/RUBY/LicenseKey'

$stdout.sync = true

#---------------------------------------------------------------------------------------
# The sample code shows how to edit the page display list and how to modify graphics state 
# attributes on existing Elements. In particular the sample program strips all images from 
# the page and changes text color to blue. 
#---------------------------------------------------------------------------------------

def ProcessElements(reader, writer, map)
	element = reader.Next()	 # Read page contents
	while !element.nil? do
		type = element.GetType()
		case type
		when Element::E_image
		# remove all images by skipping them
		when Element::E_inline_image	
			# remove all images by skipping them
		when Element::E_path
			# Set all paths to red color.
			gs = element.GetGState()
			gs.SetFillColorSpace(ColorSpace.CreateDeviceRGB())
			gs.SetFillColor(ColorPt.new(1, 0, 0))
			writer.WriteElement(element)
		when Element::E_text	# Process text strings...
			# Set all text to blue color.
			gs = element.GetGState()
			gs.SetFillColorSpace(ColorSpace.CreateDeviceRGB())
			cp = ColorPt.new(0, 0, 1)
			gs.SetFillColor(cp)
			writer.WriteElement(element)
		when Element::E_form	# Recursively process form XObjects
			o = element.GetXObject()
			map[o.GetObjNum()] = o
			writer.WriteElement(element)
		else
			writer.WriteElement(element)
		end
		element = reader.Next()
	end
end

	PDFNet.Initialize(PDFTronLicense.Key)
	
	# Relative path to the folder containing the test files.
	input_path = "../../TestFiles/"
	output_path = "../../TestFiles/Output/"
	input_filename = "newsletter.pdf"
	output_filename = "newsletter_edited.pdf"
	
	
	# Open the test file
	puts "Opening the input file..."
	doc = PDFDoc.new(input_path + input_filename)
	doc.InitSecurityHandler()
	
	writer = ElementWriter.new()
	reader = ElementReader.new()
	
	itr = doc.GetPageIterator()
	
	while itr.HasNext() do
		page = itr.Current()
		reader.Begin(page)
		writer.Begin(page, ElementWriter::E_replacement, false)
		map1 = {}
		ProcessElements(reader, writer, map1)
		writer.End()
		reader.End()
		
		map2 = {}
		while (not(map1.empty? and map2.empty?)) do
			map1.each do |k, v|
				obj = v
				writer.Begin(obj)
				reader.Begin(obj, page.GetResourceDict())
				ProcessElements(reader, writer, map2)
				reader.End()
				writer.End()

				map1.delete(k)
			end
			if (map1.empty? and not map2.empty?)
				map1.update(map2)
				map2.clear
			end
		end
		itr.Next()
	end
		
	doc.Save(output_path + output_filename, SDFDoc::E_remove_unused)
	doc.Close()
	PDFNet.Terminate
	puts "Done. Result saved in " + output_filename + "..."
```

{% endcode %}
{% endtab %}

{% tab title="VB" %}
{% code lineNumbers="true" %}

```vb
'
' Copyright (c) 2001-2024 by Apryse Software Inc. All Rights Reserved.
'

Imports System
Imports System.Collections.Generic

Imports pdftron
Imports pdftron.Common
Imports pdftron.Filters
Imports pdftron.SDF
Imports pdftron.PDF

Imports XSet = System.Collections.Generic.List(Of Integer)

Module ElementEditTestVB
    Dim pdfNetLoader As PDFNetLoader
    Sub New()
        pdfNetLoader = pdftron.PDFNetLoader.Instance()
    End Sub

    ' The sample code shows how to edit the page display list and how to modify graphics state 
    ' attributes on existing Elements. In particular the sample program strips all images from 
    ' the page, changes the path fill color to red, and changes text color to blue. 

    Sub ProcessElements(ByVal reader As ElementReader, ByVal writer As ElementWriter, ByVal visited As XSet)
        Dim element As Element = reader.Next()
        While Not IsNothing(element) ' Read page contents
            If element.GetType() = element.Type.e_image Then
                ' remove all images by skipping them
                element = reader.Next()
            ElseIf element.GetType() = element.Type.e_inline_image Then
                ' remove all images by skipping them
                element = reader.Next()
            ElseIf element.GetType() = element.Type.e_path Then
                ' Set all paths to red color.
                Dim gs As GState = element.GetGState()
                gs.SetFillColorSpace(ColorSpace.CreateDeviceRGB())
                gs.SetFillColor(New ColorPt(1, 0, 0))
                writer.WriteElement(element)
                element = reader.Next()
            ElseIf element.GetType() = element.Type.e_text Then
                ' Set all text to blue color.
                Dim gs As GState = element.GetGState()
                gs.SetFillColorSpace(ColorSpace.CreateDeviceRGB())
                gs.SetFillColor(New ColorPt(0, 0, 1))
                writer.WriteElement(element)
                element = reader.Next()
            ElseIf element.GetType() = element.Type.e_form Then
                writer.WriteElement(element) ' write Form XObject reference to current stream

                Dim form_obj As Obj = element.GetXObject()
                If Not visited.Contains(form_obj.GetObjNum()) Then ' if this XObject has not been processed
                    ' recursively process the Form XObject
                    visited.Add(form_obj.GetObjNum())
                    Dim new_writer As ElementWriter = New ElementWriter
                    reader.FormBegin()
                    new_writer.Begin(form_obj, True)

                    reader.ClearChangeList()
                    new_writer.SetDefaultGState(reader)

                    ProcessElements(reader, new_writer, visited)
                    new_writer.End()
                    reader.End()
                End If
            Else
                writer.WriteElement(element)
                element = reader.Next()
            End If
        End While
    End Sub

    Sub Main()

        PDFNet.Initialize(PDFTronLicense.Key)

        ' Relative path to the folder containing test files.
        Dim input_path As String = "../../../../TestFiles/"
        Dim output_path As String = "../../../../TestFiles/Output/"
        Dim input_filename As String = "newsletter.pdf"
        Dim output_filename As String = "newsletter_edited.pdf"

        Try

            Console.WriteLine("Opening the input file...")
            Using doc As PDFDoc = New PDFDoc(input_path + input_filename)
                doc.InitSecurityHandler()

                Dim writer As ElementWriter = New ElementWriter
                Dim reader As ElementReader = New ElementReader
                Dim visited As XSet = New XSet()

                Dim itr As PageIterator = doc.GetPageIterator()

                While itr.HasNext()
                    Try
                        Dim page As Page = itr.Current()
                        visited.Add(page.GetSDFObj().GetObjNum())

                        reader.Begin(page)
                        writer.Begin(page, ElementWriter.WriteMode.e_replacement, False, True, page.GetResourceDict())
                        
                        ProcessElements(reader, writer, visited)
                        writer.End()
                        reader.End()

                        itr.Next()
                    Catch e As PDFNetException
                        Console.WriteLine(e.Message)
                    End Try
                End While


                doc.Save(output_path + output_filename, SDF.SDFDoc.SaveOptions.e_remove_unused)
            End Using
            Console.WriteLine("Done. Result saved in {0}...", output_filename)
        Catch e As PDFNetException
            Console.WriteLine(e.Message)
        End Try
        PDFNet.Terminate()
    End Sub

End Module
```

{% 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/core/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.
