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

# ElementEdit

Here is a complete PDF and DOCX editing guide using Java. Modify properties, edit text, bookmarks,annotation and lot more using COS API

Sample Java 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. You can also build a GUI with [interactive PDF editor widgets](/android/get-started/samples.md#pdfview). Some of Apryse SDK's other functions for programmatically editing PDFs include the [Cos/SDF low-level API](/android/get-started/samples.md#sdf), [page manipulation](/android/get-started/samples.md#pdfpage), and more. Learn more about our [Android SDK](/core/get-started/languages/java.md) and [PDF Editing & Manipulation Library](/core/page-manipulation/manipulation.md).

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

```java
//---------------------------------------------------------------------------------------
// Copyright (c) 2001-2019 by PDFTron Systems Inc. All Rights Reserved.
// Consult legal.txt regarding legal and license information.
//---------------------------------------------------------------------------------------

package com.pdftron.android.pdfnetsdksamples.samples;

import com.pdftron.android.pdfnetsdksamples.OutputListener;
import com.pdftron.android.pdfnetsdksamples.PDFNetSample;
import com.pdftron.android.pdfnetsdksamples.R;
import com.pdftron.android.pdfnetsdksamples.util.Utils;
import com.pdftron.common.PDFNetException;
import com.pdftron.pdf.ColorPt;
import com.pdftron.pdf.ColorSpace;
import com.pdftron.pdf.Element;
import com.pdftron.pdf.ElementReader;
import com.pdftron.pdf.ElementWriter;
import com.pdftron.pdf.GState;
import com.pdftron.pdf.PDFDoc;
import com.pdftron.pdf.Page;
import com.pdftron.pdf.PageIterator;
import com.pdftron.sdf.Obj;
import com.pdftron.sdf.SDFDoc;

import java.util.ArrayList;
import java.util.Set;
import java.util.TreeSet;

public class ElementEditTest extends PDFNetSample {

	private static OutputListener mOutputListener;

	private static ArrayList<String> mFileList = new ArrayList<>();

    public ElementEditTest() {
        setTitle(R.string.sample_elementedit_title);
        setDescription(R.string.sample_elementedit_description);
    }

	@Override
	public void run(OutputListener outputListener) {
		super.run(outputListener);
		mOutputListener = outputListener;
		mFileList.clear();
		printHeader(outputListener);

		String input_filename = "newsletter.pdf";
		String output_filename = "newsletter_edited.pdf";

		mOutputListener.println("Opening the input file...");
		try (PDFDoc doc = new PDFDoc((Utils.getAssetTempFile(INPUT_PATH + input_filename).getAbsolutePath()))) {
			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) {
					mOutputListener.printError(e.getStackTrace());
				}
			}

			// Save modified document
			doc.save(Utils.createExternalFile(output_filename, mFileList).getAbsolutePath(), SDFDoc.SaveMode.REMOVE_UNUSED, null);
			mOutputListener.println("Done. Result saved in " + output_filename + "...");
		} catch (Exception e) {
			mOutputListener.printError(e.getStackTrace());
		}

		for (String file : mFileList) {
			addToFileList(file);
		}
		printFooter(outputListener);
	}
    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;
			}
		}
  
	}

}
```

{% endcode %}
{% endtab %}

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

```kotlin
//---------------------------------------------------------------------------------------
// Copyright (c) 2001-2019 by PDFTron Systems Inc. All Rights Reserved.
// Consult legal.txt regarding legal and license information.
//---------------------------------------------------------------------------------------

package com.pdftron.android.pdfnetsdksamples.samples

import com.pdftron.android.pdfnetsdksamples.OutputListener
import com.pdftron.android.pdfnetsdksamples.PDFNetSample
import com.pdftron.android.pdfnetsdksamples.R
import com.pdftron.android.pdfnetsdksamples.util.Utils
import com.pdftron.common.PDFNetException
import com.pdftron.pdf.*
import com.pdftron.sdf.SDFDoc
import java.util.*

class ElementEditTest : PDFNetSample() {
    init {
        setTitle(R.string.sample_elementedit_title)
        setDescription(R.string.sample_elementedit_description)
    }

    override fun run(outputListener: OutputListener?) {
        super.run(outputListener)
        mOutputListener = outputListener
        mFileList.clear()
        printHeader(outputListener!!)

        val input_filename = "newsletter.pdf"
        val output_filename = "newsletter_edited.pdf"

        try {
            mOutputListener!!.println("Opening the input file...")
            PDFDoc(Utils.getAssetTempFile(INPUT_PATH + input_filename)!!.absolutePath).use { doc ->
                doc.initSecurityHandler()
                val writer = ElementWriter()
                val reader = ElementReader()
                val visited: MutableSet<Int?> = TreeSet()
                val itr = doc.pageIterator
                while (itr.hasNext()) {
                    try {
                        val page = itr.next()
                        visited.add(page!!.sdfObj.objNum.toInt())
                        reader.begin(page)
                        writer.begin(page, ElementWriter.e_replacement, false, true, page!!.resourceDict)
                        processElements(writer, reader, visited)
                        writer.end()
                        reader.end()
                    } catch (e: Exception) {
                        mOutputListener!!.printError(e.stackTrace)
                    }
                }

                // Save modified document
                doc.save(Utils.createExternalFile(output_filename, mFileList).absolutePath, SDFDoc.SaveMode.REMOVE_UNUSED, null)
                mOutputListener!!.println("Done. Result saved in $output_filename...")
            }
        } catch (e: Exception) {
            mOutputListener!!.printError(e.stackTrace)
        }

        for (file in mFileList) {
            addToFileList(file!!)
        }
        printFooter(outputListener!!)
    }

    companion object {

        private var mOutputListener: OutputListener? = null

        private val mFileList = ArrayList<String>()

        @Throws(PDFNetException::class)
        fun processElements(writer: ElementWriter, reader: ElementReader, visited: MutableSet<Int?>) {
            var element: Element?
            while (true) {
                element = reader.next()
                if (element == null) {
                    break
                }
                when (element.type) {
                    Element.e_image, Element.e_inline_image -> {
                    }
                    Element.e_path -> {

                        // Set all paths to red color.
                        val gs = element.gState
                        gs.fillColorSpace = ColorSpace.createDeviceRGB()
                        gs.fillColor = ColorPt(1.0, 0.0, 0.0)
                        writer.writeElement(element)
                    }
                    Element.e_text -> {

                        // Set all text to blue color.
                        val gs = element.gState
                        gs.fillColorSpace = ColorSpace.createDeviceRGB()
                        gs.fillColor = ColorPt(0.0, 0.0, 1.0)
                        writer.writeElement(element)
                    }
                    Element.e_form -> {
                        writer.writeElement(element) // write Form XObject reference to current stream
                        val form_obj = element.xObject
                        if (!visited.contains(form_obj.objNum.toInt())) // if this XObject has not been processed
                        {
                            // recursively process the Form XObject
                            visited.add(form_obj.objNum.toInt())
                            val new_writer = ElementWriter()
                            reader.formBegin()
                            new_writer.begin(form_obj)
                            reader.clearChangeList()
                            new_writer.setDefaultGState(reader)
                            processElements(new_writer, reader, visited)
                            new_writer.end()
                            reader.end()
                        }
                    }
                    else -> writer.writeElement(element)
                }
            }
        }
    }

}
```

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