Some test text!

platform
search
< iOS samples

PDF Packages (Portfolios) in Swift

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

Step 1: Get your free trial license key, or sign in

Start Trial
Sign in

Step 2: Add the code:

//---------------------------------------------------------------------------------------
// Copyright (c) 2001-2017 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)
    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
    }
}