Some test text!


PDF packages (Portfolios) in Swift

More languages

More languages
Java (Android)
C# (.NET Core)
JS (Node.js)
C# (UWP)
C# (Xamarin)

Sample Swift code to use PDFTron SDK for creating, extracting, and manipulating PDF packages (also known as PDF portfolios). Learn more about our Swift PDF Library and PDF Parsing & Content Extraction Library.

Get StartedSamplesDownload

To run this sample, get started with a free trial of PDFTron SDK.

// 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! = .utf8)
    files.put(data, key_sz: Int32(data.count), value: fs.getSDFObj())
    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().setFillColor(with: PTColorPt(x: 1, y: 0, z: 0, w: 0))
    // 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)
       URL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]).appendingPathComponent("package.pdf").path, flags: e_ptlinearized.rawValue)
        } catch let e as NSError {
            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)
                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)
                        counter += 1
        } catch let e as NSError {
            ret = 1
        return ret

Free Trial

Get unlimited trial usage of PDFTron SDK to bring accurate, reliable, and fast document processing capabilities to any application or workflow.

Select a platform to get started with your free trial.

Unlimited usage. No email address required.

Join our live demo to learn about use cases & capabilities for WebViewer

Learn more