Sample Obj-C code to use Apryse SDK for creating, extracting, and manipulating PDF packages (also known as PDF portfolios). Learn more about our iOS SDK and PDF Data Extraction SDK Capabilities.
1//---------------------------------------------------------------------------------------
2// Copyright (c) 2001-2024 by Apryse Software Inc. All Rights Reserved.
3// Consult legal.txt regarding legal and license information.
4//---------------------------------------------------------------------------------------
5
6#import <OBJC/PDFNetOBJC.h>
7#import <Foundation/Foundation.h>
8
9//-----------------------------------------------------------------------------------
10/// This sample illustrates how to create, extract, and manipulate PDF Portfolios
11/// (a.k.a. PDF Packages) using PDFNet SDK.
12//-----------------------------------------------------------------------------------
13
14
15void AddPackage(PTPDFDoc *doc, NSString *file, NSString* desc)
16{
17 PTNameTree *files = [PTNameTree Create: [doc GetSDFDoc] name: @"EmbeddedFiles"];
18 PTFileSpec *fs = [PTFileSpec Create: [doc GetSDFDoc] path: file embed: true];
19 [files Put: [file dataUsingEncoding: NSUTF8StringEncoding] key_sz:(int)file.length value: [fs GetSDFObj]];
20 [fs SetDesc: desc];
21
22 PTObj * collection = [[doc GetRoot] FindObj: @"Collection"];
23 if (!collection) collection = [[doc GetRoot] PutDict: @"Collection"];
24
25 // You could here manipulate any entry in the Collection dictionary.
26 // For example, the following line sets the tile mode for initial view mode
27 // Please refer to section '2.3.5 Collections' in PDF Reference for details.
28 [collection PutName: @"View" name: @"T"];
29}
30
31void AddCoverPage(PTPDFDoc *doc)
32{
33 // Here we dynamically generate cover page (please see ElementBuilder
34 // sample for more extensive coverage of PDF creation API).
35 PTPDFRect * rect = [[PTPDFRect alloc] init];
36 [rect Set: 0 y1: 0 x2: 200 y2: 200];
37 PTPage *page = [doc PageCreate: rect];
38
39 PTElementBuilder *b = [[PTElementBuilder alloc] init];
40 PTElementWriter *w = [[PTElementWriter alloc] init];
41 [w WriterBeginWithPage: page placement: e_ptoverlay page_coord_sys: YES compress: YES resources: NULL];
42 PTFont *font = [PTFont Create: [doc GetSDFDoc] type: e_pthelvetica embed: NO];
43 [w WriteElement: [b CreateTextBeginWithFont: font font_sz: 12]];
44 PTElement *e = [b CreateTextRun: @"My PDF Collection"];
45 PTMatrix2D *mtx = [[PTMatrix2D alloc] initWithA: 1 b: 0 c: 0 d: 1 h: 50 v: 96];
46 [e SetTextMatrixWithMatrix2D: mtx];
47 [[e GetGState] SetFillColorSpace: [PTColorSpace CreateDeviceRGB]];
48 [[e GetGState] SetFillColorWithColorPt: [[PTColorPt alloc] initWithX: 1 y: 0 z: 0 w: 0]];
49 [w WriteElement: e];
50 [w WriteElement: [b CreateTextEnd]];
51 [w End];
52 [doc PagePushBack: page];
53
54 // Alternatively we could import a PDF page from a template PDF document
55 // (for an example please see PDFPage sample project).
56 // ...
57}
58
59int main(int argc, char *argv[])
60{
61 @autoreleasepool {
62 int ret = 0;
63 [PTPDFNet Initialize: 0];
64
65 // Create a PDF Package.
66 @try
67 {
68 PTPDFDoc *doc = [[PTPDFDoc alloc] init];
69 AddPackage(doc, @"../../TestFiles/numbered.pdf", @"My File 1");
70 AddPackage(doc, @"../../TestFiles/newsletter.pdf", @"My Newsletter...");
71 AddPackage(doc, @"../../TestFiles/peppers.jpg", @"An image");
72 AddCoverPage(doc);
73 [doc SaveToFile: @"../../TestFiles/Output/package.pdf" flags: e_ptlinearized];
74 NSLog(@"Done.");
75 }
76 @catch(NSException *e)
77 {
78 NSLog(@"%@", e.reason);
79 ret = 1;
80 }
81
82 // Extract parts from a PDF Package.
83 @try
84 {
85 PTPDFDoc *doc = [[PTPDFDoc alloc] initWithFilepath: @"../../TestFiles/Output/package.pdf"];
86 [doc InitSecurityHandler];
87
88 PTNameTree *files = [PTNameTree Find: [doc GetSDFDoc] name: @"EmbeddedFiles"];
89 if([files IsValid])
90 {
91 // Traverse the list of embedded files.
92 PTDictIterator *i = [files GetIterator];
93 int counter = 0;
94 for (; [i HasNext]; [i Next], ++counter)
95 {
96 NSString *entry_name = [[i Key] GetAsPDFText];
97 NSLog(@"Part: %@", entry_name);
98 PTFileSpec *file_spec = [[PTFileSpec alloc] initWithF: [i Value]];
99 PTFilter *stm = [file_spec GetFileData];
100 if (stm)
101 {
102 NSString *str = [NSString stringWithFormat: @"../../TestFiles/Output/extract_%d.%@", counter, [entry_name pathExtension]];
103 [stm WriteToFile: str append: NO];
104 }
105 }
106 }
107
108 NSLog(@"Done.");
109 }
110 @catch(NSException *e)
111 {
112 NSLog(@"%@", e.reason);
113 ret = 1;
114 }
115 [PTPDFNet Terminate: 0];
116 return ret;
117 }
118}
1//---------------------------------------------------------------------------------------
2// Copyright (c) 2001-2019 by PDFTron Systems Inc. All Rights Reserved.
3// Consult legal.txt regarding legal and license information.
4//---------------------------------------------------------------------------------------
5
6import PDFNet
7import Foundation
8
9//-----------------------------------------------------------------------------------
10/// This sample illustrates how to create, extract, and manipulate PDF Portfolios
11/// (a.k.a. PDF Packages) using PDFNet SDK.
12//-----------------------------------------------------------------------------------
13
14func AddPackage(doc: PTPDFDoc, file: String, desc: String) {
15 let files: PTNameTree = PTNameTree.create(doc.getSDFDoc(), name: "EmbeddedFiles")
16 let fs: PTFileSpec = PTFileSpec.create(doc.getSDFDoc(), path: file, embed: true)
17 let data: Data! = file.data(using: .utf8)
18 files.put(data, key_sz: Int32(data.count), value: fs.getSDFObj())
19 fs.setDesc(desc)
20
21 let collection: PTObj
22 if let optCollection: PTObj = doc.getRoot().find("Collection") {
23 collection = optCollection
24 } else {
25 collection = doc.getRoot().putDict("Collection")
26 }
27
28 // You could here manipulate any entry in the Collection dictionary.
29 // For example, the following line sets the tile mode for initial view mode
30 // Please refer to section '2.3.5 Collections' in PDF Reference for details.
31 collection.putName("View", name: "T")
32}
33
34func AddCoverPage(doc: PTPDFDoc) {
35 // Here we dynamically generate cover page (please see ElementBuilder
36 // sample for more extensive coverage of PDF creation API).
37 let rect: PTPDFRect = PTPDFRect(x1: 0, y1: 0, x2: 200, y2: 200)
38 let page: PTPage = doc.pageCreate(rect)
39
40 let b: PTElementBuilder = PTElementBuilder()
41 let w: PTElementWriter = PTElementWriter()
42 w.writerBegin(with: page, placement: e_ptoverlay, page_coord_sys: true, compress: true, resources: nil)
43 let font = PTFont.create(doc.getSDFDoc(), type: e_pthelvetica, embed: false)
44 w.write(b.createTextBegin(with: font, font_sz: 12))
45 let e: PTElement = b.createTextRun("My PDF Collection")
46 let mtx = PTMatrix2D(a: 1, b: 0, c: 0, d: 1, h: 50, v: 96)
47 e.setTextMatrix(with: mtx)
48 e.getGState().setFill(PTColorSpace.createDeviceRGB())
49 e.getGState().setFillColor(with: PTColorPt(x: 1, y: 0, z: 0, w: 0))
50 w.write(e)
51 w.write(b.createTextEnd())
52 w.end()
53 doc.pagePushBack(page)
54
55 // Alternatively we could import a PDF page from a template PDF document
56 // (for an example please see PDFPage sample project).
57 // ...
58}
59
60func runPDFPackageTest() -> Int {
61 return autoreleasepool {
62 var ret: Int = 0
63
64
65 // Create a PDF Package.
66 do {
67 try PTPDFNet.catchException {
68 let doc: PTPDFDoc = PTPDFDoc()
69 AddPackage(doc: doc, file: Bundle.main.path(forResource: "numbered", ofType: "pdf")!, desc: "My File 1")
70 AddPackage(doc: doc, file: Bundle.main.path(forResource: "newsletter", ofType: "pdf")!, desc: "My Newsletter...")
71 AddPackage(doc: doc, file: Bundle.main.path(forResource: "peppers", ofType: "jpg")!, desc: "An image")
72 AddCoverPage(doc: doc)
73 doc.save(toFile: URL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]).appendingPathComponent("package.pdf").path, flags: e_ptlinearized.rawValue)
74 print("Done.")
75 }
76 } catch let e as NSError {
77 print("\(e)")
78 ret = 1
79 }
80
81 // Extract parts from a PDF Package.
82 do {
83 try PTPDFNet.catchException {
84 let doc: PTPDFDoc = PTPDFDoc(filepath: URL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]).appendingPathComponent("package.pdf").path)
85 doc.initSecurityHandler()
86
87 let files: PTNameTree = PTNameTree.find(doc.getSDFDoc(), name: "EmbeddedFiles")
88 if files.isValid() {
89 // Traverse the list of embedded files.
90 let i: PTDictIterator = files.getIterator()
91 var counter: Int = 0
92 while i.hasNext() {
93 let entry_name: String = i.key().getAsPDFText()
94 print("Part: \(entry_name)")
95 let file_spec: PTFileSpec = PTFileSpec(f: i.value())
96 if let stm: PTFilter = file_spec.getFileData() {
97 let str: String = URL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]).appendingPathComponent("extract_\(counter)").path
98 stm.write(toFile: str, append: false)
99 }
100 i.next()
101 counter += 1
102 }
103 }
104 print("Done.")
105 }
106 } catch let e as NSError {
107 print("\(e)")
108 ret = 1
109 }
110
111 return ret
112 }
113}
Did you find this helpful?
Trial setup questions?
Ask experts on DiscordNeed other help?
Contact SupportPricing or product questions?
Contact Sales