> 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/ios/get-started/samples/logicalstructuretest.md).

# LogicalStructure

Sample code in Swift and Obj-C for using Apryse iOS SDK to explore the logical structure and content of a tagged PDF file, then dumps the information to the console window. In tagged PDF files, Struct

Sample code in Swift and Obj-C for using Apryse iOS SDK to explore the logical structure and content of a tagged PDF file, then dumps the information to the console window. In tagged PDF files, StructTree acts as a central repository for information related to a PDF document's logical structure. The tree consists of StructElement-s and ContentItem-s which are leaf nodes of the structure tree.

Learn more about our full [PDF Data Extraction SDK Capabilities](https://apryse.com/capabilities/extraction).

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

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

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

#import <OBJC/PDFNetOBJC.h>
#import <Foundation/Foundation.h>

//---------------------------------------------------------------------------------------
// This sample explores the structure and content of a tagged PDF document and dumps 
// the structure information to the console window.
//
// In tagged PDF documents StructTree acts as a central repository for information 
// related to a PDF document's logical structure. The tree consists of StructElement-s
// and ContentItem-s which are leaf nodes of the structure tree.
//
// The sample can be extended to access and extract the marked-content elements such 
// as text and images.
//---------------------------------------------------------------------------------------


NSString *PrintIdent(int ident) { 
    int i;
    NSString * str= @"\n";
    for (i=0; i<ident; ++i) {
        str = [str stringByAppendingString: @"  "]; 
    }
    return str;
}

// Used in code snippet 1.
NSString* ProcessStructElement(PTSElement *element, int ident)
{
    if (![element IsValid]) {
        return @"";
    }

    NSString *result = @"";
    // Print out the type and title info, if any.
    result = [result stringByAppendingFormat: @"%@Type: %@", PrintIdent(ident++), [element GetType]];
    if ([element HasTitle]) {
        result = [result stringByAppendingFormat: @". Title: %@", [element GetTitle]];
    }

    int num = [element GetNumKids];
    int i;
    for (i=0; i<num; ++i) 
    {
        // Check is the kid is a leaf node (i.e. it is a ContentItem).
        if ([element IsContentItem: i]) { 
            PTContentItem *cont = [element GetAsContentItem: i]; 
            PTContentItemType type = [cont GetType];

            PTPage *page = [cont GetPage];

            result = [result stringByAppendingFormat: @"%@Content Item. Part of page #%d%@", PrintIdent(ident), [page GetIndex], PrintIdent(ident)];
            
            switch (type) {
                case e_ptMCID:
                case e_ptMCR:
                    result = [result stringByAppendingFormat: @"MCID: %d", [cont GetMCID]];
                    break;
                case e_ptOBJR:
                    {
                        result = [result stringByAppendingString: @"OBJR "];
                        PTObj *ref_obj;
                        if ((ref_obj = [cont GetRefObj]) != NULL)
                            result = [result stringByAppendingFormat: @"- Referenced Object#: %u", [ref_obj GetObjNum]];
                    }
                    break;
                default: 
                    break;
            }
        }
        else {  // the kid is another StructElement node.
            result = [result stringByAppendingString: ProcessStructElement([element GetAsStructElem: i], ident)];
        }
    }
    return result;
}

// Used in code snippet 2.
NSString* ProcessLogicalStructureTestElements(PTElementReader *reader)
{
    PTElement *element;
    NSString *result = @"";
    while ((element = [reader Next]) != NULL)     // Read page contents
    {
        // In this sample we process only paths & text, but the code can be 
        // extended to handle any element type.
        PTElementType type = [element GetType];
        if (type == e_ptpath || type == e_pttext_obj || type == e_ptpath) 
        {   
            switch (type)    {
            case e_ptpath:                // Process path ...
                result = [result stringByAppendingString: @"\nPATH: "];
                break; 
            case e_pttext_obj:                 // Process text ...
                result = [result stringByAppendingFormat: @"\nTEXT: %@\n", [element GetTextString]];
                break;
            case e_ptform:                // Process form XObjects
                result = [result stringByAppendingString: @"\nFORM XObject: "];
                //reader.FormBegin(); 
                //ProcessLogicalStructureTestElements(reader);
                //reader.End(); 
                break;
            default:
                break;
            }

            // Check if the element is associated with any structural element.
            // Content items are leaf nodes of the structure tree.
            PTSElement *struct_parent = [element GetParentStructElement];
            if ([struct_parent IsValid]) {
                // Print out the parent structural element's type, title, and object number.
                result = [result stringByAppendingFormat: @" Type: %@, MCID: %d", [struct_parent GetType], [element GetStructMCID]];
                if ([struct_parent HasTitle]) {
                    result = [result stringByAppendingFormat: @". Title: %@", [struct_parent GetTitle]];
                }
                result = [result stringByAppendingFormat: @", Obj#: %u", [[struct_parent GetSDFObj] GetObjNum]];
            }
        }
    }
    return result;
}

// Used in code snippet 3.
//typedef map<int, string> MCIDPageMap;
NSMutableDictionary *MCIDPageMap;
NSMutableDictionary *MCIDDocMap;
//typedef map<int, MCIDPageMap> MCIDDocMap;

// Used in code snippet 3.
void ProcessLogicalStructureTestElements2(PTElementReader *reader, NSMutableDictionary *mcid_page_map)
{
    PTElement *element;
    while ((element = [reader Next]) != NULL) // Read page contents
    {
        // In this sample we process only text, but the code can be extended 
        // to handle paths, images, or any other Element type.
        int mcid = [element GetStructMCID];
        if (mcid>= 0 && [element GetType] == e_pttext_obj) {
            NSString *val = [element GetTextString];
            id key = @(mcid);
            BOOL exist = [mcid_page_map.allKeys containsObject: key];
            if (exist) {
                NSString *str = mcid_page_map[key];
                mcid_page_map[key] = [str stringByAppendingString: val];
            } 
            else {
                mcid_page_map[key] = val;
            }
        }
    }
}

// Used in code snippet 3.
NSString* ProcessStructElement2(PTSElement *element, NSMutableDictionary *mcid_doc_map, int ident) 
{
    if (![element IsValid]) {
        return @"";
    }
    NSString *result = @"";
    // Print out the type and title info, if any.
    result = [result stringByAppendingString: PrintIdent(ident)];
    result = [result stringByAppendingFormat: @"<%@", [element GetType]];
    if ([element HasTitle]) {
        result = [result stringByAppendingFormat: @" title=\"%@\"", [element GetTitle]];
    }
    result = [result stringByAppendingString: @">"];

    int num = [element GetNumKids];
    int i;
    for (i=0; i<num; ++i) 
    {        
        if ([element IsContentItem: i]) { 
            PTContentItem *cont = [element GetAsContentItem: i]; 
            if ([cont GetType] == e_ptMCID) {
                int page_num = [[cont GetPage] GetIndex];
                id key = @(page_num);
                BOOL exist = [mcid_doc_map.allKeys containsObject: key];
                
                if (exist) {
                    NSMutableDictionary *mcid_page_map = mcid_doc_map[key];
                    id key2 = @([cont GetMCID]);
                    BOOL exist2 = [mcid_page_map.allKeys containsObject: key2];
                    if (exist2) {
                        NSString *str = mcid_page_map[key2];
                        result = [result stringByAppendingString: str]; 
                    }                    
                }
            }
        }
        else {  // the kid is another StructElement node.
            result = [result stringByAppendingString: ProcessStructElement2([element GetAsStructElem :i], mcid_doc_map, ident+1)];
        }
    }

    result = [result stringByAppendingString: PrintIdent(ident)];
    result = [result stringByAppendingFormat: @"</%@>", [element GetType]];
    return result;
}


int main(int argc, char *argv[])
{
    @autoreleasepool {
        int ret = 0;
        [PTPDFNet Initialize: 0];

        @try    // Extract logical structure from a PDF document
        {
            PTPDFDoc *doc = [[PTPDFDoc alloc] initWithFilepath: @"../../TestFiles/tagged.pdf"];
            [doc InitSecurityHandler];

            NSLog(@"____________________________________________________________");
            NSLog(@"Sample 1 - Traverse logical structure tree...");
            {
                PTSTree *tree = [doc GetStructTree];
                if ([tree IsValid]) {
                    NSLog(@"Document has a StructTree root.");

                int i;
                    for (i=0; i<[tree GetNumKids]; ++i) {
                        // Recursively get structure info for all child elements.
                        NSLog(@"%@", ProcessStructElement([tree GetKid: i], 0));
                    }
                }
                else {
                    NSLog(@"This document does not contain any logical structure.");
                }
            }
            NSLog(@"Done 1.");

            NSLog(@"____________________________________________________________");
            NSLog(@"Sample 2 - Get parent logical structure elements from");
            NSLog(@"layout elements.");
            {
                PTElementReader *reader = [[PTElementReader alloc] init];
            PTPageIterator *itr;
                for (itr = [doc GetPageIterator: 1]; [itr HasNext]; [itr Next]) {
                    [reader Begin: [itr Current]];
                    NSLog(@"%@", ProcessLogicalStructureTestElements(reader));
                    [reader End];
                }
            }
            NSLog(@"Done 2.");

            NSLog(@"____________________________________________________________");
            NSLog(@"Sample 3 - 'XML style' extraction of PDF logical structure and page content.");
            {
                NSMutableDictionary *mcid_doc_map = [[NSMutableDictionary alloc] init];
                PTElementReader *reader = [[PTElementReader alloc] init];
                PTPageIterator *itr;
                for (itr = [doc GetPageIterator: 1]; [itr HasNext]; [itr Next]) {
                    [reader Begin: [itr Current]];
                    NSMutableDictionary *arr = [[NSMutableDictionary alloc] init];
                id key = @([[itr Current] GetIndex]);
                mcid_doc_map[key] = arr;
                    ProcessLogicalStructureTestElements2(reader, mcid_doc_map[key]);
                    [reader End];
                }

                PTSTree *tree = [doc GetStructTree];
                if ([tree IsValid]) {
                    int i;
                    for (i=0; i<[tree GetNumKids]; ++i) {
                        NSLog(@"%@", ProcessStructElement2([tree GetKid: i], mcid_doc_map, 0));
                    }
                }
            }
            NSLog(@"Done 3.");
            [doc SaveToFile: @"../../TestFiles/Output/LogicalStructure.pdf" flags: e_ptlinearized];
        }
        @catch(NSException *e) 
        {
            NSLog(@"%@", e.reason);
            ret = 1;
        }
        [PTPDFNet Terminate: 0];
        return ret;
    }
}
```

{% endcode %}
{% endtab %}

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

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

import PDFNet
import Foundation

//---------------------------------------------------------------------------------------
// This sample explores the structure and content of a tagged PDF document and dumps
// the structure information to the console window.
//
// In tagged PDF documents StructTree acts as a central repository for information
// related to a PDF document's logical structure. The tree consists of StructElement-s
// and ContentItem-s which are leaf nodes of the structure tree.
//
// The sample can be extended to access and extract the marked-content elements such
// as text and images.
//---------------------------------------------------------------------------------------

func PrintIndent(_ indent: Int) -> String {
    var str = "\n"
    for _ in 0..<indent {
        str += "  "
    }
    return str
}

// Used in code snippet 1.
func ProcessStructElement(element: PTSElement, indent: Int) -> String {
    if !element.isValid() {
        return ""
    }
    
    // Print out the type and title info, if any.
    var result = ("\(PrintIndent(indent))Type: \(String(describing: element.getType()))")
    let nestedIndent = indent + 1
    if element.hasTitle() {
        result = result + (". Title: \(String(describing: element.getTitle()))")
    }
    
    let num = element.getNumKids()
    for i in 0..<num {
        // Check if the kid is a leaf node (i.e. it is a ContentItem).
        if element.isContentItem(i) {
            let cont: PTContentItem = element.getAsContentItem(i)
            let type: PTContentItemType = cont.getType()
            
            let page: PTPage = cont.getPage()
            result += ("\(PrintIndent(nestedIndent))Content Item. Part of page #\(page.getIndex())\(PrintIndent(nestedIndent))")
            switch type {
            case e_ptMCID, e_ptMCR:
                result += ("MCID: \(cont.getMCID())")
            case e_ptOBJR:
                result += ("OBJR ")
                if let ref_obj = cont.getRefObj() {
                    result += ("- Referenced Object#: \(ref_obj.getNum())")
                }
            default:
                break
            }
        }
        else {
            // the kid is another StructElement node.
            result = result + (ProcessStructElement(element: element.getAsStructElem(i), indent: nestedIndent))
        }
    }
    return result
}

// Used in code snippet 2.
func ProcessLogicalStructureTestElements(reader: PTElementReader) -> String {
    var result = ""
    while let element = reader.next() { // Read page contents
        // In this sample we process only paths & text, but the code can be
        // extended to handle any element type.
        let type: PTElementType = element.getType()
        if type == e_ptpath || type == e_pttext_obj || type == e_ptpath {
            switch type {
            case e_ptpath:  // Process path ...
                result = result + ("\nPATH: ")
            case e_pttext_obj:  // Process text ...
                result = result + ("\nTEXT: \(String(describing: element.getTextString()))")
            case e_ptform:  // Process form XObjects
                result = result + ("\nFORM XObject:")
                //reader.FormBegin();
                //ProcessLogicalStructureTestElements(reader);
                //reader.End();
            default:
                break
            }
            
            // Check if the element is associated with any structural element.
            // Content items are leaf nodes of the structure tree.
            let struct_parent: PTSElement = element.getParentStructElement()
            if struct_parent.isValid() {
                // Print out the parent structural element's type, title, and object number.
                result = result + (" Type: \(String(describing: struct_parent.getType())), MCID: \(element.getStructMCID())")
                if struct_parent.hasTitle() {
                    result = result + (". Title: \(String(describing: struct_parent.getTitle()))")
                }
                result = result + (", Obj#: \(struct_parent.getSDFObj().getNum())")
            }
        }
    }
    return result
}


// Used in code snippet 3.
//typedef map<int, string> MCIDPageMap;
//var MCIDPageMap = [AnyHashable: Any]()
//var MCIDDocMap = [AnyHashable: Any]()
//typedef map<int, MCIDPageMap> MCIDDocMap;

// Used in code snippet 3.
func ProcessLogicalStructureTestElements2(reader: PTElementReader, mcid_page_map: NSMutableDictionary) {
    while let element = reader.next() {    // Read page contents
        // In this sample we process only text, but the code can be extended
        // to handle paths, images, or any other Element type.
        let mcid = element.getStructMCID()
        if mcid >= 0 && element.getType() == e_pttext_obj {
            let val = element.getTextString()
            let key = mcid
            if let str = mcid_page_map[key] as? String {
                mcid_page_map[key] = str + (val ?? "")
            } else {
                mcid_page_map[key] = val ?? ""
            }
        }
    }
}

// Used in code snippet 3.
func ProcessStructElement2(element: PTSElement, mcid_doc_map: NSMutableDictionary, indent: Int) -> String {
    if !element.isValid() {
        return ""
    }
    var result = ""
    // Print out the type and title info, if any.
    result += (PrintIndent(indent))
    result += ("<\(String(describing: element.getType()))")
    if element.hasTitle() {
        result += (" title=\"\(String(describing: element.getTitle()))\"")
    }
    result += (">")
    
    let num = element.getNumKids()
    for i in 0..<num {
        if element.isContentItem(i) {
            let cont: PTContentItem = element.getAsContentItem(i)
            if cont.getType() == e_ptMCID {
                let page_num = cont.getPage().getIndex()
                let key = page_num
                if let mcid_page_map = mcid_doc_map[key] as? NSMutableDictionary {
                    let key2 = cont.getMCID()
                    if let str = mcid_page_map[key2] as? String {
                        result += (str)
                    }
                }
            }
        }
        else {  // the kid is another StructElement node.
            result += (ProcessStructElement2(element: element.getAsStructElem(i), mcid_doc_map: mcid_doc_map, indent: indent + 1))
        }
    }
    
    result += (PrintIndent(indent))
    result += ("</\(String(describing: element.getType()))>")
    return result
}

func runLogicalStructureTest() -> Int {
    return autoreleasepool {
        var ret: Int = 0
        
        
        do {
            // Extract logical structure from a PDF document
            try PTPDFNet.catchException {
                let doc: PTPDFDoc = PTPDFDoc(filepath: Bundle.main.path(forResource: "tagged", ofType: "pdf"))
                doc.initSecurityHandler()
                
                print("____________________________________________________________")
                print("Sample 1 - Traverse logical structure tree...")
                do {
                    let tree: PTSTree = doc.getStructTree()
                    if tree.isValid() {
                        print("Document has a StructTree root.")
                
                        for i in 0..<tree.getNumKids() {
                            // Recursively get structure info for all child elements.
                            print("\(ProcessStructElement(element: tree.getKid(i), indent: 0))")
                        }
                    }
                    else {
                        print("This document does not contain any logical structure.")
                    }
                }
                print("Done 1.")

                print("____________________________________________________________")
                print("Sample 2 - Get parent logical structure elements from")
                print("layout elements.")
                do {
                    let reader: PTElementReader = PTElementReader()
                    let itr: PTPageIterator = doc.getPageIterator(1)
                    while itr.hasNext() {
                        reader.begin(itr.current())
                        print("\(ProcessLogicalStructureTestElements(reader: reader))")
                        reader.end()
                        itr.next()
                    }
                }
                print("Done 2.")
                
                print("____________________________________________________________")
                print("Sample 3 - 'XML style' extraction of PDF logical structure and page content.")
                do {
                    let mcid_doc_map = NSMutableDictionary()
                    let reader: PTElementReader = PTElementReader()
                    let itr: PTPageIterator = doc.getPageIterator(1)
                    while itr.hasNext() {
                        reader.begin(itr.current())
                        let arr = NSMutableDictionary()
                        ProcessLogicalStructureTestElements2(reader: reader, mcid_page_map: arr)
                        let key = itr.current().getIndex()
                        mcid_doc_map[key] = arr
                        reader.end()
                        itr.next()
                    }
                    
                    let tree: PTSTree = doc.getStructTree()
                    if tree.isValid() {
                        for i in 0..<tree.getNumKids() {
                            print("\(ProcessStructElement2(element: tree.getKid(i), mcid_doc_map: mcid_doc_map, indent: 0))")
                        }
                    }
                }
                print("Done 3.")
            }
        } catch let e as NSError {
            print("Caught PDFNet exception: \(e)")
            ret = 1
        }
        return ret
    }
}
```

{% 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/ios/get-started/samples/logicalstructuretest.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.
