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

# Read PDF Elements - ElementReader

Sample code for using Apryse SDK to traverse the page display list using ElementReader.  Sample code provided in Python, C++, C#, Java, Node.js (JavaScript), PHP, Ruby and VB.

Sample code for using Apryse SDK to traverse the page display list using ElementReader; provided in Python, C++, C#, Java, Node.js (JavaScript), PHP, Ruby and VB. Learn more about our full [PDF Data Extraction SDK Capabilities](https://apryse.com/capabilities/extraction).

To start your free trial, [get stated with Server SDK](/core/get-started/get-started.md).

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

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

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

namespace ElementReaderTestCS
{
	/// <summary>
	/// Summary description for Class1.
	/// </summary>
	class Class1
	{
		private static pdftron.PDFNetLoader pdfNetLoader = pdftron.PDFNetLoader.Instance();
		static Class1() {}
		
		static void ProcessElements(ElementReader reader)
		{
			Element element;
			while ((element = reader.Next()) != null) 	// Read page contents
			{
				switch (element.GetType())
				{
			   
					case Element.Type.e_path:				// Process path data...
						{
							PathData data = element.GetPathData();
							double[] points = data.points;
							break;
						}
					
					case Element.Type.e_text: 				// Process text strings...
						{
							String str = element.GetTextString();
							Console.WriteLine(str);
							break;
						}

					case Element.Type.e_form:				// Process form XObjects
						{
							Console.WriteLine("Process Element.Type.e_form");
							reader.FormBegin();
							ProcessElements(reader);
							reader.End();
							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/";

			try
			{
				Console.WriteLine("-------------------------------------------------");
				Console.WriteLine("Sample 1 - Extract text data from all pages in the document.");

				// Open the test file
				Console.WriteLine("Opening the input pdf...");
				using (PDFDoc doc = new PDFDoc(input_path + "newsletter.pdf"))
				using (ElementReader page_reader = new ElementReader())
				{
					doc.InitSecurityHandler();

					PageIterator itr;
					for (itr = doc.GetPageIterator(); itr.HasNext(); itr.Next())		//  Read every page
					{
						page_reader.Begin(itr.Current());
						ProcessElements(page_reader);
						page_reader.End();
					}
					Console.WriteLine("Done.");
				}

			}
			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/ElementReader.h>
#include <PDF/Element.h>
#include <iostream>
#include "../../LicenseKey/CPP/LicenseKey.h"

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

void ProcessElements(ElementReader& reader) 
{
	for (Element element=reader.Next(); element; element = reader.Next()) 	// Read page contents
	{
		switch (element.GetType())
		{
			case Element::e_path:				 // Process path data...
			{
					PathData data = element.GetPathData();
					const std::vector<unsigned char>& operators = data.GetOperators();
					const std::vector<double>& points = data.GetPoints();
			}
			break; 
			
			case Element::e_text: 				// Process text strings...
			{
				const UString data = element.GetTextString();
				cout << data << endl;
			}
			break;
			
			case Element::e_form:				// Process form XObjects
			{
					reader.FormBegin(); 
					ProcessElements(reader);
					reader.End(); 
			}
			break; 
		}
	}
}


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

	// Relative path to the folder containing test files.
	string input_path =  "../../TestFiles/";

	try	// Extract text data from all pages in the document
	{
		cout << "-------------------------------------------------" << endl;
		cout << "Sample 1 - Extract text data from all pages in the document." << endl;
		cout << "Opening the input pdf..." << endl;

		PDFDoc doc((input_path + "newsletter.pdf").c_str());
		doc.InitSecurityHandler();

		int pgnum = doc.GetPageCount();
		
		PageIterator itr;
		ElementReader page_reader;

		for (itr = doc.GetPageIterator(); itr.HasNext(); itr.Next())		//  Read every page
		{				
			page_reader.Begin(itr.Current());
			ProcessElements(page_reader);
			page_reader.End();
		}

		cout << "Done." << 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"
// Relative path to the folder containing the test files.
var inputPath = "../../TestFiles/"

func ProcessElements(reader ElementReader){
    element := reader.Next()
    for element.GetMp_elem().Swigcptr() != 0{       // Read page contents
        if element.GetType() == ElementE_path{      // Process path data...
            //uncomment below if needed
            //data := element.GetPathData()
            //points := data.GetPoints()
        }else if element.GetType() == ElementE_text{        // Process text strings...
            data := element.GetTextString()
            fmt.Println(data)
        }else if element.GetType() == ElementE_form{        // Process form XObjects
            reader.FormBegin()
            ProcessElements(reader)
            reader.End()
        }
        element = reader.Next()
    }
}

func main(){
    PDFNetInitialize(PDFTronLicense.Key)
    
    // Extract text data from all pages in the document
    fmt.Println("-------------------------------------------------")
    fmt.Println("Sample 1 - Extract text data from all pages in the document.")
    fmt.Println("Opening the input pdf...")
    
    doc := NewPDFDoc(inputPath + "newsletter.pdf")
    doc.InitSecurityHandler()
    
    pageReader := NewElementReader()
    
    itr := doc.GetPageIterator()
    
    // Read every page
    for itr.HasNext(){
        pageReader.Begin(itr.Current())
        ProcessElements(pageReader)
        pageReader.End()
        itr.Next()
    }
    // Close the open document to free up document memory sooner.    
    doc.Close()
    PDFNetTerminate()
    fmt.Println("Done.")
}
```

{% 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.common.PDFNetException;
import com.pdftron.pdf.*;

public class ElementReaderTest {

    static void ProcessElements(ElementReader reader) throws PDFNetException {
        for (Element element = reader.next(); element != null; element = reader.next())    // Read page contents
        {
			switch (element.getType()) 
			{
				case Element.e_path:                 // Process path data...
				{
					PathData data = element.getPathData();
					byte[] operators = data.getOperators();
					double[] points = data.getPoints();
				}
				break;
				case Element.e_text:                // Process text strings...
				{
					String data = element.getTextString();
					System.out.println(data); 
				}
				break;
				case Element.e_form:                // Process form XObjects
				{
					reader.formBegin();
					ProcessElements(reader);
					reader.end();
				}
				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/";

        System.out.println("-------------------------------------------------");
        System.out.println("Sample 1 - Extract text data from all pages in the document.");
        System.out.println("Opening the input pdf...");

        try (PDFDoc doc = new PDFDoc(input_path + "newsletter.pdf"))    // Extract text data from all pages in the document
        {
            doc.initSecurityHandler();

            int pgnum = doc.getPageCount();

            PageIterator itr;
            ElementReader page_reader = new ElementReader();

            for (itr = doc.getPageIterator(); itr.hasNext(); )        //  Read every page
            {
                page_reader.begin(itr.next());
                ProcessElements(page_reader);
                page_reader.end();
            }
            System.out.println("Done.");
        } catch (Exception e) {
            System.out.println(e);
        }

        PDFNet.terminate();
    }
}
```

{% 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");

// Relative path to the folder containing the test files.
$input_path = getcwd()."/../../TestFiles/";


function ProcessElements($reader) {
	for ($element=$reader->Next(); $element != null; $element = $reader->Next()) 	// Read page contents
	{
		switch ($element->GetType())
		{
		case Element::e_path:						// Process path data...
			{
				$data = $element->GetPathData();
				$points = $data->GetPoints();
			}
 			break; 
		case Element::e_text: 				// Process text strings...
			{
				$data = $element->GetTextString();
				echo nl2br($data."\n");
			}
			break;
		case Element::e_form:				// Process form XObjects
			{
				$reader->FormBegin(); 
                		ProcessElements($reader);
				$reader->End(); 
			}
			break; 
		}
	}
}

	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.
	
	// Extract text data from all pages in the document

	echo nl2br("-------------------------------------------------\n");
	echo nl2br("Sample 1 - Extract text data from all pages in the document.\n");
	echo nl2br("Opening the input pdf...\n");
	
	$doc = new PDFDoc($input_path."newsletter.pdf");
	$doc->InitSecurityHandler();

	$pgnum = $doc->GetPageCount();
		
	$page_reader = new ElementReader();

	for ($itr = $doc->GetPageIterator(); $itr->HasNext(); $itr->Next())		//  Read every page
	{		
		$page_reader->Begin($itr->Current());
		ProcessElements($page_reader);
		$page_reader->End();
	}
	PDFNet::Terminate();
	echo nl2br("Done.\n");
?>
```

{% 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.runElementReaderTest = () => {

    const ProcessElements = async(reader) => {
      // Read page contents
      for (let element = await reader.next(); element !== null; element = await reader.next()) {
        const temp = await element.getType();
        switch (temp) {
          case PDFNet.Element.Type.e_path: // Process path data...
            {
              const data = await element.getPathData();
              /* eslint-disable no-unused-vars */
              const operators = data.operators;
              const points = data.points;
              /* eslint-enable no-unused-vars */
            }
            break;
          case PDFNet.Element.Type.e_text: // Process text strings...
            {
              const data = await element.getTextString();
              console.log(data);
            }
            break;
          case PDFNet.Element.Type.e_form: // Process form XObjects
            reader.formBegin();
            await ProcessElements(reader);
            reader.end();
            break;
          default:
        }
      }
    };

    const main = async() => {
      console.log('-------------------------------------------------');
      console.log('Sample 1 - Extract text data from all pages in the document.');
      console.log('Opening the input pdf...');
      const ret = 0;

      // Relative path to the folder containing test files.
      const inputUrl = '../TestFiles/';

      const doc = await PDFNet.PDFDoc.createFromFilePath(inputUrl + 'newsletter.pdf');// await if there is ret that we care about.
      doc.initSecurityHandler();

      // eslint-disable-next-line no-unused-vars
      const pgnum = await doc.getPageCount();
      const pageReader = await PDFNet.ElementReader.create();
      const itr = await doc.getPageIterator(1);

      // Read every page
      for (itr; await itr.hasNext(); itr.next()) {
        const curritr = await itr.current();
        pageReader.beginOnPage(curritr);
        await ProcessElements(pageReader);
        pageReader.end();
      }

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

{% 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 *
import unicodedata

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

# Relative path to the folder containing the test files.
input_path = "../../TestFiles/"

def ProcessElements(reader):
    element = reader.Next()
    while element != None:		# Read page contents
        if element.GetType() == Element.e_path:		# Process path data...
            data = element.GetPathData()
            points = data.GetPoints()
        elif element.GetType() == Element.e_text:		# Process text strings...
            data = element.GetTextString()
            if sys.version_info.major == 2:
                reload(sys)
                sys.setdefaultencoding("utf-8")
                data = unicodedata.normalize('NFKC', unicode(data)).encode('ascii','replace')
            print(data)
        elif element.GetType() == Element.e_form:		# Process form XObjects
            reader.FormBegin()
            ProcessElements(reader)
            reader.End()
        element = reader.Next()

def main():
    PDFNet.Initialize(LicenseKey)
    
    # Extract text data from all pages in the document
    print("-------------------------------------------------")
    print("Sample 1 - Extract text data from all pages in the document.")
    print("Opening the input pdf...")
    
    doc = PDFDoc(input_path + "newsletter.pdf")
    doc.InitSecurityHandler()
    
    page_reader = ElementReader()
    
    itr = doc.GetPageIterator()
    
    # Read every page
    while itr.HasNext():
        page_reader.Begin(itr.Current())
        ProcessElements(page_reader)
        page_reader.End()
        itr.Next()
    
    # Close the open document to free up document memory sooner.    
    doc.Close()
    PDFNet.Terminate()
    print("Done.")
    
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

# Relative path to the folder containing the test files.
input_path = "../../TestFiles/"

def ProcessElements(reader)
	element = reader.Next()
	while !element.nil? do	# Read page contents
		if element.GetType() == Element::E_path	# Process path data...
			data = element.GetPathData()
			points = data.GetPoints()
		elsif element.GetType() == Element::E_text	# Process text strings...
			data = element.GetTextString()
			puts data
		elsif element.GetType() == Element::E_form	# Process form XObjects
			reader.FormBegin()
			ProcessElements(reader)
			reader.End()
		end
		element = reader.Next()
	end
end

	PDFNet.Initialize(PDFTronLicense.Key)
	
	# Extract text data from all pages in the document
	puts "-------------------------------------------------"
	puts "Sample 1 - Extract text data from all pages in the document."
	puts "Opening the input pdf..."
	
	doc = PDFDoc.new(input_path + "newsletter.pdf")
	doc.InitSecurityHandler()
	
	page_reader = ElementReader.new()
	
	itr = doc.GetPageIterator()
	
	# Read every page
	while itr.HasNext() do
		page_reader.Begin(itr.Current())
		ProcessElements(page_reader)
		page_reader.End()
		itr.Next()
	end
	
	# Close the open document to free up document memory sooner.	
	doc.Close()
	PDFNet.Terminate
	puts "Done."
```

{% endcode %}
{% endtab %}

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

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

Imports System

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

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


    Sub ProcessElements(ByVal reader As ElementReader)
        Dim element As Element = reader.Next()
        While Not IsNothing(element)  ' Read page contents
            Select element.GetType()
                Case Element.Type.e_path
                    ' Process path data...
                    Dim pathData As PathData = element.GetPathData()
                    Dim data As Double() = pathData.points

                Case Element.Type.e_text
                    ' Process text strings...
                    Dim result As String = element.GetTextString()
                    Console.WriteLine(result)

                Case Element.Type.e_form
                    ' Process form XObjects
                    reader.FormBegin()
                    Console.WriteLine("Process Element.Type.e_form")
                    ProcessElements(reader)
                    reader.End()
            End Select
            element = reader.Next()
        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/"

        Console.WriteLine("-------------------------------------------------")
        Console.WriteLine("Sample 1 - Extract text data from all pages in the document.")

        ' Open the test file
        Console.WriteLine("Opening the input pdf...")
        Using doc As PDFDoc = New PDFDoc(input_path + "newsletter.pdf")
            Using page_reader As ElementReader = New ElementReader
                doc.InitSecurityHandler()
                Dim itr As PageIterator = doc.GetPageIterator()
                While itr.HasNext()  '  Read every page
                    page_reader.Begin(itr.Current())
                    ProcessElements(page_reader)
                    page_reader.End()
                    itr.Next()
                End While
            End Using
        End Using
        PDFNet.Terminate()
        Console.WriteLine("Done.")

    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/elementreadertest.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.
