Sample Obj-C code for using Apryse SDK to create various patterns and shadings in PDF files. Learn more about our iOS SDK and PDF Editing & Manipulation Library.
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
9PTObj* CreateTilingPattern(PTPDFDoc* doc) 
10{
11    PTElementWriter *writer = [[PTElementWriter alloc] init];    
12    PTElementBuilder *eb = [[PTElementBuilder alloc] init];
13
14    // Create a new pattern content stream - a heart. ------------
15    [writer WriterBeginWithSDFDoc: [doc GetSDFDoc] compress: YES];
16    [eb PathBegin];
17    [eb MoveTo: 0 y: 0];
18    [eb CurveTo: 500 cy1: 500 cx2: 125 cy2: 625 x2: 0 y2: 500];
19    [eb CurveTo: -125 cy1: 625 cx2: -500 cy2: 500 x2: 0 y2: 0];
20    PTElement *heart = [eb PathEnd];
21    [heart SetPathFill: YES]; 
22    
23    // Set heart color to red.
24    [[heart GetGState] SetFillColorSpace: [PTColorSpace CreateDeviceRGB]]; 
25    [[heart GetGState] SetFillColorWithColorPt: [[PTColorPt alloc] initWithX: 1 y: 0 z: 0 w: 0]]; 
26    [writer WriteElement: heart];
27
28    PTObj * pattern_dict = [writer End];
29
30    // Initialize pattern dictionary. For details on what each parameter represents please 
31    // refer to Table 4.22 (Section '4.6.2 Tiling Patterns') in PDF Reference Manual.
32    [pattern_dict PutName: @"Type" name: @"Pattern"];
33    [pattern_dict PutNumber: @"PatternType" value: 1];
34
35    // TilingType - Constant spacing.
36    [pattern_dict PutNumber: @"TilingType" value: 1]; 
37
38    // This is a Type1 pattern - A colored tiling pattern.
39    [pattern_dict PutNumber: @"PaintType" value: 1];
40
41    // Set bounding box
42    [pattern_dict PutRect: @"BBox" x1: -253 y1: 0 x2: 253 y2: 545];
43
44    // Create and set the matrix
45    PTMatrix2D *pattern_mtx = [[PTMatrix2D alloc] initWithA: 0.04 b: 0 c: 0 d: 0.04 h: 0 v: 0];
46    [pattern_dict PutMatrix: @"Matrix" value: pattern_mtx];
47
48    // Set the desired horizontal and vertical spacing between pattern cells, 
49    // measured in the pattern coordinate system.
50    [pattern_dict PutNumber: @"XStep" value: 1000];
51    [pattern_dict PutNumber: @"YStep" value: 1000];
52    
53    return pattern_dict; // finished creating the Pattern resource
54}
55
56PTObj * CreateImageTilingPattern(PTPDFDoc* doc) 
57{
58    PTElementWriter *writer = [[PTElementWriter alloc] init];    
59    PTElementBuilder *eb = [[PTElementBuilder alloc] init];
60
61    // Create a new pattern content stream - a single bitmap object ----------
62    [writer WriterBeginWithSDFDoc: [doc GetSDFDoc] compress: YES];
63    PTImage *image = [PTImage Create: [doc GetSDFDoc] filename: @"../../TestFiles/dice.jpg"];
64    PTElement *img_element = [eb CreateImageWithCornerAndScale: image x: 0 y: 0 hscale: [image GetImageWidth] vscale: [image GetImageHeight]];
65    [writer WritePlacedElement: img_element];
66    PTObj * pattern_dict = [writer End];
67
68    // Initialize pattern dictionary. For details on what each parameter represents please 
69    // refer to Table 4.22 (Section '4.6.2 Tiling Patterns') in PDF Reference Manual.
70    [pattern_dict PutName: @"Type" name: @"Pattern"];
71    [pattern_dict PutNumber: @"PatternType" value: 1];
72
73    // TilingType - Constant spacing.
74    [pattern_dict PutNumber: @"TilingType" value: 1]; 
75
76    // This is a Type1 pattern - A colored tiling pattern.
77    [pattern_dict PutNumber: @"PaintType" value: 1];
78
79    // Set bounding box
80    [pattern_dict PutRect: @"BBox" x1: -253 y1: 0 x2: 253 y2: 545];
81
82    // Create and set the matrix
83    PTMatrix2D *pattern_mtx = [[PTMatrix2D alloc] initWithA: 0.3 b: 0 c: 0 d: 0.3 h: 0 v:0];
84    [pattern_dict PutMatrix: @"Matrix" value: pattern_mtx];
85
86    // Set the desired horizontal and vertical spacing between pattern cells, 
87    // measured in the pattern coordinate system.
88    [pattern_dict PutNumber: @"XStep" value: 300];
89    [pattern_dict PutNumber: @"YStep" value: 300];
90    
91    return pattern_dict; // finished creating the Pattern resource
92}
93
94PTObj * CreateAxialShading(PTPDFDoc* doc) 
95{
96    // Create a new Shading object ------------
97    PTObj * pattern_dict = [doc CreateIndirectDict];
98
99    // Initialize pattern dictionary. For details on what each parameter represents 
100    // please refer to Tables 4.30 and 4.26 in PDF Reference Manual
101    [pattern_dict PutName: @"Type" name: @"Pattern"];
102    [pattern_dict PutNumber: @"PatternType" value: 2]; // 2 stands for shading
103    
104    PTObj * shadingDict = [pattern_dict PutDict: @"Shading"];
105    [shadingDict PutNumber: @"ShadingType" value: 2];
106    [shadingDict PutName: @"ColorSpace" name: @"DeviceCMYK"];
107    
108    // pass the coordinates of the axial shading to the output
109    PTObj * shadingCoords = [shadingDict PutArray: @"Coords"];
110    [shadingCoords PushBackNumber: 0];
111    [shadingCoords PushBackNumber: 0];
112    [shadingCoords PushBackNumber: 612];
113    [shadingCoords PushBackNumber: 794];
114
115    // pass the function to the axial shading
116    PTObj * function = [shadingDict PutDict: @"Function"];
117    PTObj * C0 = [function PutArray: @"C0"];
118    [C0 PushBackNumber: 1];
119    [C0 PushBackNumber: 0];
120    [C0 PushBackNumber: 0];
121    [C0 PushBackNumber: 0];
122
123    PTObj * C1 = [function PutArray: @"C1"];
124    [C1 PushBackNumber: 0];
125    [C1 PushBackNumber: 1];
126    [C1 PushBackNumber: 0];
127    [C1 PushBackNumber: 0];
128    
129    PTObj * domain = [function PutArray: @"Domain"];
130    [domain PushBackNumber: 0];
131    [domain PushBackNumber: 1];
132
133    [function PutNumber: @"FunctionType" value: 2];
134    [function PutNumber: @"N" value: 1];
135
136    return pattern_dict;
137}
138
139
140int main(int argc, char *argv[])
141{
142    @autoreleasepool {
143        [PTPDFNet Initialize: 0];
144
145        @try  
146        {     
147            PTPDFDoc *doc = [[PTPDFDoc alloc] init];
148            PTElementWriter *writer = [[PTElementWriter alloc] init];    
149            PTElementBuilder *eb = [[PTElementBuilder alloc] init];
150
151            // The following sample illustrates how to create and use tiling patterns
152            PTPage *page = [doc PageCreate: [[PTPDFRect alloc] initWithX1: 0 y1: 0 x2: 612 y2: 792]];
153            [writer WriterBeginWithPage: page placement: e_ptoverlay page_coord_sys: YES compress: YES resources: NULL];
154
155            PTElement *element = [eb CreateTextBeginWithFont: [PTFont Create: [doc GetSDFDoc] type: e_pttimes_bold embed: NO] font_sz: 1];
156            [writer WriteElement: element];  // Begin the text block
157
158            element = [eb CreateTextRun: @"G"];
159            [element SetTextMatrix: 720 b: 0 c: 0 d: 720 h: 20 v: 240];
160            PTGState *gs = [element GetGState];
161            [gs SetTextRenderMode: e_ptfill_stroke_text];
162            [gs SetLineWidth: 4];
163
164            // Set the fill color space to the Pattern color space. 
165            [gs SetFillColorSpace: [PTColorSpace CreatePattern]];
166            [gs SetFillColorWithPattern: [[PTPatternColor alloc] initWithPattern: CreateTilingPattern(doc)]];
167
168            [writer WriteElement: element];
169            [writer WriteElement: [eb CreateTextEnd]]; // Finish the text block
170
171            [writer End];    // Save the page
172            [doc PagePushBack: page];
173            //-----------------------------------------------
174
175            /// The following sample illustrates how to create and use image tiling pattern
176            page = [doc PageCreate: [[PTPDFRect alloc] initWithX1: 0 y1: 0 x2: 612 y2: 792]];
177            [writer WriterBeginWithPage: page placement: e_ptoverlay page_coord_sys: YES compress: YES resources: NULL];
178
179            [eb Reset: [[PTGState alloc] init]];
180            element = [eb CreateRect: 0 y: 0 width: 612 height: 794];
181
182            // Set the fill color space to the Pattern color space. 
183            gs = [element GetGState];
184            [gs SetFillColorSpace: [PTColorSpace CreatePattern]];
185            [gs SetFillColorWithPattern: [[PTPatternColor alloc] initWithPattern: CreateImageTilingPattern(doc)]];
186            [element SetPathFill: YES];        
187
188            [writer WriteElement: element];
189
190            [writer End];    // Save the page
191            [doc PagePushBack: page];
192            //-----------------------------------------------
193
194            /// The following sample illustrates how to create and use PDF shadings
195            page = [doc PageCreate: [[PTPDFRect alloc] initWithX1: 0 y1: 0 x2: 612 y2: 792]];
196            [writer WriterBeginWithPage: page placement: e_ptoverlay page_coord_sys: YES compress: YES resources: NULL];
197
198            [eb Reset: [[PTGState alloc] init]];
199            element = [eb CreateRect: 0 y: 0 width: 612 height: 794];
200
201            // Set the fill color space to the Pattern color space. 
202            gs = [element GetGState];
203            [gs SetFillColorSpace: [PTColorSpace CreatePattern]];
204            [gs SetFillColorWithPattern: [[PTPatternColor alloc] initWithPattern: CreateAxialShading(doc)]];
205            [element SetPathFill: YES];        
206        
207            [writer WriteElement: element];
208        
209            [writer End];    // Save the page
210            [doc PagePushBack: page];
211            //-----------------------------------------------
212
213            [doc SaveToFile: @"../../TestFiles/Output/patterns.pdf" flags: e_ptremove_unused];
214            NSLog(@"Done. Result saved in patterns.pdf...");
215        }
216        @catch(NSException *e)
217        {
218            NSLog(@"%@", e.reason);
219        }
220        [PTPDFNet Terminate: 0];
221    }
222}
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
9func CreateTilingPattern(doc: PTPDFDoc) -> PTObj {
10    let writer: PTElementWriter = PTElementWriter()
11    let eb: PTElementBuilder = PTElementBuilder()
12    
13    // Create a new pattern content stream - a heart. ------------
14    writer.writerBegin(with: doc.getSDFDoc(), compress: true)
15    eb.pathBegin()
16    eb.move(to: 0, y: 0)
17    eb.curve(to: 500, cy1: 500, cx2: 125, cy2: 625, x2: 0, y2: 500)
18    eb.curve(to: -125, cy1: 625, cx2: -500, cy2: 500, x2: 0, y2: 0)
19    let heart: PTElement = eb.pathEnd()
20    heart.setPathFill(true)
21    
22    // Set heart color to red.
23    heart.getGState().setFill(PTColorSpace.createDeviceRGB())
24    heart.getGState().setFillColor(with: PTColorPt(x: 1, y: 0, z: 0, w: 0))
25    writer.write(heart)
26    
27    let pattern_dict: PTObj = writer.end()
28    
29    // Initialize pattern dictionary. For details on what each parameter represents please
30    // refer to Table 4.22 (Section '4.6.2 Tiling Patterns') in PDF Reference Manual.
31    pattern_dict.putName("Type", name: "Pattern")
32    pattern_dict.putNumber("PatternType", value: 1)
33    
34    // TilingType - Constant spacing.
35    pattern_dict.putNumber("TilingType", value: 1)
36    
37    // This is a Type1 pattern - A colored tiling pattern.
38    pattern_dict.putNumber("PaintType", value: 1)
39    
40    // Set bounding box
41    pattern_dict.putRect("BBox", x1: -253, y1: 0, x2: 253, y2: 545)
42    
43    // Create and set the matrix
44    let pattern_mtx: PTMatrix2D = PTMatrix2D(a: 0.04, b: 0, c: 0, d: 0.04, h: 0, v: 0)
45    pattern_dict.putMatrix("Matrix", value: pattern_mtx)
46    
47    // Set the desired horizontal and vertical spacing between pattern cells,
48    // measured in the pattern coordinate system.
49    pattern_dict.putNumber("XStep", value: 1000)
50    pattern_dict.putNumber("YStep", value: 1000)
51
52    return pattern_dict  // finished creating the Pattern resource
53}
54
55func CreateImageTilingPattern(doc: PTPDFDoc) -> PTObj {
56    let writer: PTElementWriter = PTElementWriter()
57    let eb: PTElementBuilder = PTElementBuilder()
58    
59    // Create a new pattern content stream - a single bitmap object ----------
60    writer.writerBegin(with: doc.getSDFDoc(), compress: true)
61    let image: PTImage = PTImage.create(doc.getSDFDoc(), filename: Bundle.main.path(forResource: "dice", ofType: "jpg"))
62    let img_element: PTElement = eb.createImage(withCornerAndScale: image, x: 0, y: 0, hscale: Double(image.getWidth()), vscale: Double(image.getHeight()))
63    writer.writePlacedElement(img_element)
64    let pattern_dict: PTObj = writer.end()
65    
66    // Initialize pattern dictionary. For details on what each parameter represents please
67    // refer to Table 4.22 (Section '4.6.2 Tiling Patterns') in PDF Reference Manual.
68    pattern_dict.putName("Type", name: "Pattern")
69    pattern_dict.putNumber("PatternType", value: 1)
70    
71    // TilingType - Constant spacing.
72    pattern_dict.putNumber("TilingType", value: 1)
73    
74    // This is a Type1 pattern - A colored tiling pattern.
75    pattern_dict.putNumber("PaintType", value: 1)
76    
77    // Set bounding box
78    pattern_dict.putRect("BBox", x1: -253, y1: 0, x2: 253, y2: 545)
79    
80    // Create and set the matrix
81    let pattern_mtx = PTMatrix2D(a: 0.3, b: 0, c: 0, d: 0.3, h: 0, v: 0)
82    pattern_dict.putMatrix("Matrix", value: pattern_mtx)
83
84    // Set the desired horizontal and vertical spacing between pattern cells,
85    // measured in the pattern coordinate system.
86    pattern_dict.putNumber("XStep", value: 300)
87    pattern_dict.putNumber("YStep", value: 300)
88    return pattern_dict // finished creating the Pattern resource
89}
90
91func CreateAxialShading(doc: PTPDFDoc) -> PTObj {
92    // Create a new Shading object ------------
93    let pattern_dict: PTObj = doc.createIndirectDict()
94
95    // Initialize pattern dictionary. For details on what each parameter represents
96    // please refer to Tables 4.30 and 4.26 in PDF Reference Manual
97    pattern_dict.putName("Type", name: "Pattern")
98    pattern_dict.putNumber("PatternType", value: 2)
99    
100    // 2 stands for shading
101    let shadingDict: PTObj = pattern_dict.putDict("Shading")
102    shadingDict.putNumber("ShadingType", value: 2)
103    shadingDict.putName("ColorSpace", name: "DeviceCMYK")
104    
105    // pass the coordinates of the axial shading to the output
106    let shadingCoords: PTObj = shadingDict.putArray("Coords")
107    shadingCoords.pushBackNumber(0)
108    shadingCoords.pushBackNumber(0)
109    shadingCoords.pushBackNumber(612)
110    shadingCoords.pushBackNumber(794)
111    
112    // pass the function to the axial shading
113    let function: PTObj = shadingDict.putDict("Function")
114    let C0: PTObj = function.putArray("C0")
115    C0.pushBackNumber(1)
116    C0.pushBackNumber(0)
117    C0.pushBackNumber(0)
118    C0.pushBackNumber(0)
119    
120    let C1: PTObj = function.putArray("C1")
121    C1.pushBackNumber(0)
122    C1.pushBackNumber(1)
123    C1.pushBackNumber(0)
124    C1.pushBackNumber(0)
125    
126    let domain: PTObj = function.putArray("Domain")
127    domain.pushBackNumber(0)
128    domain.pushBackNumber(1)
129    function.putNumber("FunctionType", value: 2)
130    function.putNumber("N", value: 1)
131    
132    return pattern_dict
133}
134
135func runPatternTest() -> Int {
136    return autoreleasepool {
137        var ret = 0
138        
139        
140        do {
141            try PTPDFNet.catchException {
142                let doc: PTPDFDoc = PTPDFDoc()
143                let writer: PTElementWriter = PTElementWriter()
144                let eb: PTElementBuilder = PTElementBuilder()
145                
146                // The following sample illustrates how to create and use tiling patterns
147                var page: PTPage = doc.pageCreate(PTPDFRect(x1: 0, y1: 0, x2: 612, y2: 792))
148                writer.begin(page, placement: e_ptoverlay, page_coord_sys: true, compress:true)
149                
150                var element: PTElement = eb.createTextBegin(with: PTFont.create(doc.getSDFDoc(), type: e_pttimes_bold, embed: false), font_sz: 1)
151                writer.write(element)   // Begin the text block
152
153                element = eb.createTextRun("G")
154                element.setTextMatrix(720, b: 0, c: 0, d: 720, h: 20, v: 240)
155                var gs: PTGState = element.getGState()
156                gs.setTextRenderMode(e_ptfill_stroke_text)
157                gs.setLineWidth(4)
158                
159                // Set the fill color space to the Pattern color space.
160                gs.setFill(PTColorSpace.createPattern())
161                gs.setFillColor(withPattern: PTPatternColor(pattern: CreateTilingPattern(doc: doc)))
162                writer.write(element)
163                writer.write(eb.createTextEnd()) // Finish the text block
164
165                writer.end()    // Save the page
166                doc.pagePushBack(page)
167                //-----------------------------------------------
168                
169                /// The following sample illustrates how to create and use image tiling pattern
170                page = doc.pageCreate(PTPDFRect(x1: 0, y1: 0, x2: 612, y2: 792))
171                writer.begin(page, placement: e_ptoverlay, page_coord_sys: true, compress: true)
172                
173                eb.reset(PTGState())
174                element = eb.createRect(0, y: 0, width: 612, height: 794)
175                
176                // Set the fill color space to the Pattern color space.
177                gs = element.getGState()
178                gs.setFill(PTColorSpace.createPattern())
179                gs.setFillColor(withPattern: PTPatternColor(pattern: CreateImageTilingPattern(doc: doc)))
180                element.setPathFill(true)
181                writer.write(element)
182                writer.end()    // Save the page
183                doc.pagePushBack(page)
184                //-----------------------------------------------
185
186                /// The following sample illustrates how to create and use PDF shadings
187                page = doc.pageCreate(PTPDFRect(x1: 0, y1: 0, x2: 612, y2: 792))
188                writer.begin(page, placement: e_ptoverlay, page_coord_sys: true, compress: true)
189                
190                eb.reset(PTGState())
191                element = eb.createRect(0, y: 0, width: 612, height: 794)
192                
193                // Set the fill color space to the Pattern color space.
194                gs = element.getGState()
195                gs.setFill(PTColorSpace.createPattern())
196                gs.setFillColor(withPattern: PTPatternColor(pattern: CreateAxialShading(doc: doc)))
197                element.setPathFill(true)
198
199                writer.write(element)
200                
201                writer.end()    // Save the page
202                doc.pagePushBack(page)
203                //-----------------------------------------------
204                
205                doc.save(toFile: URL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]).appendingPathComponent("patterns.pdf").path, flags: e_ptremove_unused.rawValue)
206                print("Done. Result saved in patterns.pdf...")
207            }
208        } catch let e as NSError {
209            print("\(e)")
210            ret = 1
211        }
212        
213        return ret
214    }
215}
Did you find this helpful?
Trial setup questions?
Ask experts on DiscordNeed other help?
Contact SupportPricing or product questions?
Contact Sales