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

# PDFPackage

Sample code in Swift and Obj-C for using Apryse iOS SDK for creating, extracting, and manipulating PDF packages (also known as PDF portfolios).

Sample code in Swift and Obj-C for using Apryse iOS SDK for creating, extracting, and manipulating PDF packages (also known as PDF portfolios).

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 illustrates how to create, extract, and manipulate PDF Portfolios
/// (a.k.a. PDF Packages) using PDFNet SDK.
//-----------------------------------------------------------------------------------


void AddPackage(PTPDFDoc *doc, NSString *file, NSString* desc) 
{
    PTNameTree *files = [PTNameTree Create: [doc GetSDFDoc] name: @"EmbeddedFiles"];
    PTFileSpec *fs = [PTFileSpec Create: [doc GetSDFDoc] path: file embed: true];
    [files Put: [file dataUsingEncoding: NSUTF8StringEncoding] key_sz:(int)file.length value: [fs GetSDFObj]];
    [fs SetDesc: desc];

    PTObj * collection = [[doc GetRoot] FindObj: @"Collection"];
    if (!collection) collection = [[doc GetRoot] PutDict: @"Collection"];

    // You could here manipulate any entry in the Collection dictionary. 
    // For example, the following line sets the tile mode for initial view mode
    // Please refer to section '2.3.5 Collections' in PDF Reference for details.
    [collection PutName: @"View" name: @"T"];
}

void AddCoverPage(PTPDFDoc *doc) 
{
    // Here we dynamically generate cover page (please see ElementBuilder 
    // sample for more extensive coverage of PDF creation API).
    PTPDFRect * rect = [[PTPDFRect alloc] init];
    [rect Set: 0 y1: 0 x2: 200 y2: 200];
    PTPage *page = [doc PageCreate: rect];

    PTElementBuilder *b = [[PTElementBuilder alloc] init];
    PTElementWriter *w = [[PTElementWriter alloc] init];
    [w WriterBeginWithPage: page placement: e_ptoverlay page_coord_sys: YES compress: YES resources: NULL];
    PTFont *font = [PTFont Create: [doc GetSDFDoc] type: e_pthelvetica embed: NO];
    [w WriteElement: [b CreateTextBeginWithFont: font font_sz: 12]];
    PTElement *e = [b CreateTextRun: @"My PDF Collection"];
    PTMatrix2D *mtx = [[PTMatrix2D alloc] initWithA: 1 b: 0 c: 0 d: 1 h: 50 v: 96];
    [e SetTextMatrixWithMatrix2D: mtx];
    [[e GetGState] SetFillColorSpace: [PTColorSpace CreateDeviceRGB]];
    [[e GetGState] SetFillColorWithColorPt: [[PTColorPt alloc] initWithX: 1 y: 0 z: 0 w: 0]];
    [w WriteElement: e];
    [w WriteElement: [b CreateTextEnd]];
    [w End];
    [doc PagePushBack: page];

    // Alternatively we could import a PDF page from a template PDF document
    // (for an example please see PDFPage sample project).
    // ...
}

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

        // Create a PDF Package.
        @try
        {
            PTPDFDoc *doc = [[PTPDFDoc alloc] init];
            AddPackage(doc, @"../../TestFiles/numbered.pdf", @"My File 1");
            AddPackage(doc, @"../../TestFiles/newsletter.pdf", @"My Newsletter...");
            AddPackage(doc, @"../../TestFiles/peppers.jpg", @"An image");
            AddCoverPage(doc);
            [doc SaveToFile: @"../../TestFiles/Output/package.pdf" flags: e_ptlinearized];
            NSLog(@"Done.");
        }
        @catch(NSException *e)
        {
            NSLog(@"%@", e.reason);
            ret = 1;
        }
        
    // Extract parts from a PDF Package.
        @try  
        { 
            PTPDFDoc *doc = [[PTPDFDoc alloc] initWithFilepath: @"../../TestFiles/Output/package.pdf"];
            [doc InitSecurityHandler];

            PTNameTree *files = [PTNameTree Find: [doc GetSDFDoc] name: @"EmbeddedFiles"];
            if([files IsValid]) 
            { 
                // Traverse the list of embedded files.
                PTDictIterator *i = [files GetIterator];
                int counter = 0;
                for (; [i HasNext]; [i Next], ++counter) 
                {
                    NSString *entry_name = [[i Key] GetAsPDFText];
                    NSLog(@"Part: %@", entry_name);
                    PTFileSpec *file_spec = [[PTFileSpec alloc] initWithF: [i Value]];
                    PTFilter *stm = [file_spec GetFileData];
                    if (stm) 
                    {
                        NSString *str = [NSString stringWithFormat: @"../../TestFiles/Output/extract_%d.%@", counter, [entry_name pathExtension]];
                        [stm WriteToFile: str append: NO];
                    }
                }
            }

            NSLog(@"Done.");
        }
        @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 illustrates how to create, extract, and manipulate PDF Portfolios
/// (a.k.a. PDF Packages) using PDFNet SDK.
//-----------------------------------------------------------------------------------

func AddPackage(doc: PTPDFDoc, file: String, desc: String) {
    let files: PTNameTree = PTNameTree.create(doc.getSDFDoc(), name: "EmbeddedFiles")
    let fs: PTFileSpec = PTFileSpec.create(doc.getSDFDoc(), path: file, embed: true)
    let data: Data! = file.data(using: .utf8)
    files.put(data, key_sz: Int32(data.count), value: fs.getSDFObj())
    fs.setDesc(desc)
    
    let collection: PTObj
    if let optCollection: PTObj = doc.getRoot().find("Collection") {
        collection = optCollection
    } else {
        collection = doc.getRoot().putDict("Collection")
    }
    
    // You could here manipulate any entry in the Collection dictionary.
    // For example, the following line sets the tile mode for initial view mode
    // Please refer to section '2.3.5 Collections' in PDF Reference for details.
    collection.putName("View", name: "T")
}

func AddCoverPage(doc: PTPDFDoc) {
    // Here we dynamically generate cover page (please see ElementBuilder
    // sample for more extensive coverage of PDF creation API).
    let rect: PTPDFRect = PTPDFRect(x1: 0, y1: 0, x2: 200, y2: 200)
    let page: PTPage = doc.pageCreate(rect)
    
    let b: PTElementBuilder = PTElementBuilder()
    let w: PTElementWriter = PTElementWriter()
    w.writerBegin(with: page, placement: e_ptoverlay, page_coord_sys: true, compress: true, resources: nil)
    let font = PTFont.create(doc.getSDFDoc(), type: e_pthelvetica, embed: false)
    w.write(b.createTextBegin(with: font, font_sz: 12))
    let e: PTElement = b.createTextRun("My PDF Collection")
    let mtx = PTMatrix2D(a: 1, b: 0, c: 0, d: 1, h: 50, v: 96)
    e.setTextMatrix(with: mtx)
    e.getGState().setFill(PTColorSpace.createDeviceRGB())
    e.getGState().setFillColor(with: PTColorPt(x: 1, y: 0, z: 0, w: 0))
    w.write(e)
    w.write(b.createTextEnd())
    w.end()
    doc.pagePushBack(page)
    
    // Alternatively we could import a PDF page from a template PDF document
    // (for an example please see PDFPage sample project).
    // ...
}

func runPDFPackageTest() -> Int {
    return autoreleasepool {
        var ret: Int = 0
        
        
        // Create a PDF Package.
        do {
            try PTPDFNet.catchException {
                let doc: PTPDFDoc = PTPDFDoc()
                AddPackage(doc: doc, file: Bundle.main.path(forResource: "numbered", ofType: "pdf")!, desc: "My File 1")
                AddPackage(doc: doc, file: Bundle.main.path(forResource: "newsletter", ofType: "pdf")!, desc: "My Newsletter...")
                AddPackage(doc: doc, file: Bundle.main.path(forResource: "peppers", ofType: "jpg")!, desc: "An image")
                AddCoverPage(doc: doc)
                doc.save(toFile: URL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]).appendingPathComponent("package.pdf").path, flags: e_ptlinearized.rawValue)
                print("Done.")
            }
        } catch let e as NSError {
            print("\(e)")
            ret = 1
        }
        
        // Extract parts from a PDF Package.
        do {
            try PTPDFNet.catchException {
                let doc: PTPDFDoc = PTPDFDoc(filepath: URL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]).appendingPathComponent("package.pdf").path)
                doc.initSecurityHandler()
                
                let files: PTNameTree = PTNameTree.find(doc.getSDFDoc(), name: "EmbeddedFiles")
                if files.isValid() {
                    // Traverse the list of embedded files.
                    let i: PTDictIterator = files.getIterator()
                    var counter: Int = 0
                    while i.hasNext() {
                        let entry_name: String = i.key().getAsPDFText()
                        print("Part: \(entry_name)")
                        let file_spec: PTFileSpec = PTFileSpec(f: i.value())
                        if let stm: PTFilter = file_spec.getFileData() {
                            let str: String = URL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]).appendingPathComponent("extract_\(counter)").path
                            stm.write(toFile: str, append: false)
                        }
                        i.next()
                        counter += 1
                    }
                }
                print("Done.")
            }
        } catch let e as NSError {
            print("\(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/pdfpackagetest.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.
