Sample Obj-C code for using Apryse SDK to reduce PDF file size by removing redundant information and compressing data streams using the latest in image compression technology. Learn more about our iOS SDK.
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// The following sample illustrates how to reduce PDF file size using 'pdftron.PDF.Optimizer'.
11// The sample also shows how to simplify and optimize PDF documents for viewing on mobile devices
12// and on the Web using 'pdftron.PDF.Flattener'.
13//
14// @note Both 'Optimizer' and 'Flattener' are separately licensable add-on options to the core PDFNet license.
15//
16// ----
17//
18// 'pdftron.PDF.Optimizer' can be used to optimize PDF documents by reducing the file size, removing
19// redundant information, and compressing data streams using the latest in image compression technology.
20//
21// PDF Optimizer can compress and shrink PDF file size with the following operations:
22// - Remove duplicated fonts, images, ICC profiles, and any other data stream.
23// - Optionally convert high-quality or print-ready PDF files to small, efficient and web-ready PDF.
24// - Optionally down-sample large images to a given resolution.
25// - Optionally compress or recompress PDF images using JBIG2 and JPEG2000 compression formats.
26// - Compress uncompressed streams and remove unused PDF objects.
27// ----
28//
29// 'pdftron.PDF.Flattener' can be used to speed-up PDF rendering on mobile devices and on the Web by
30// simplifying page content (e.g. flattening complex graphics into images) while maintaining vector text
31// whenever possible.
32//
33// Flattener can also be used to simplify process of writing custom converters from PDF to other formats.
34// In this case, Flattener can be used as first step in the conversion pipeline to reduce any PDF to a
35// very simple representation (e.g. vector text on top of a background image).
36//---------------------------------------------------------------------------------------
37int main(int argc, char * argv[])
38{
39 @autoreleasepool {
40
41 int ret = 0;
42
43 // The first step in every application using PDFNet is to initialize the
44 // library and set the path to common PDF resources. The library is usually
45 // initialized only once, but calling Initialize() multiple times is also fine.
46 [PTPDFNet Initialize: 0];
47
48 //--------------------------------------------------------------------------------
49 // Example 1) Simple optimization of a pdf with default settings.
50 //
51 @try
52 {
53 PTPDFDoc *doc = [[PTPDFDoc alloc] initWithFilepath: @"../../TestFiles/newsletter.pdf"];
54 [doc InitSecurityHandler];
55
56 [PTOptimizer Optimize: doc settings: [[PTOptimizerSettings alloc] init]];
57
58 [doc SaveToFile: @"../../TestFiles/Output/newsletter_opt1.pdf" flags: e_ptlinearized];
59 }
60 @catch (NSException *e)
61 {
62 NSLog(@"%@", e.reason);
63 ret = 1;
64 }
65
66 //--------------------------------------------------------------------------------
67 // Example 2) Reduce image quality and use jpeg compression for
68 // non monochrome images.
69 @try
70 {
71 PTPDFDoc *doc = [[PTPDFDoc alloc] initWithFilepath: @"../../TestFiles/newsletter.pdf"];
72 [doc InitSecurityHandler];
73
74 PTImageSettings *image_settings = [[PTImageSettings alloc] init];
75
76 // low quality jpeg compression
77 [image_settings SetCompressionMode: e_ptjpeg];
78 [image_settings SetQuality: 1];
79
80 // Set the output dpi to be standard screen resolution
81 [image_settings SetImageDPI: 144 resampling: 96];
82
83 // this option will recompress images not compressed with
84 // jpeg compression and use the result if the new image
85 // is smaller.
86 [image_settings ForceRecompression: YES];
87
88 // this option is not commonly used since it can
89 // potentially lead to larger files. It should be enabled
90 // only if the output compression specified should be applied
91 // to every image of a given type regardless of the output image size
92 //image_settings.ForceChanges(true);
93
94
95 PTOptimizerSettings *opt_settings = [[PTOptimizerSettings alloc] init];
96 [opt_settings SetColorImageSettings: image_settings];
97 [opt_settings SetGrayscaleImageSettings: image_settings];
98
99 // use the same settings for both color and grayscale images
100 [PTOptimizer Optimize: doc settings: opt_settings];
101
102 [doc SaveToFile: @"../../TestFiles/Output/newsletter_opt2.pdf" flags: e_ptlinearized];
103 }
104 @catch (NSException *e)
105 {
106 NSLog(@"%@", e.reason);
107 ret = 1;
108 }
109
110
111 //--------------------------------------------------------------------------------
112 // Example 3) Use monochrome image settings and default settings
113 // for color and grayscale images.
114 @try
115 {
116 PTPDFDoc *doc = [[PTPDFDoc alloc] initWithFilepath: @"../../TestFiles/newsletter.pdf"];
117 [doc InitSecurityHandler];
118
119 PTMonoImageSettings *mono_image_settings = [[PTMonoImageSettings alloc] init];
120
121 [mono_image_settings SetCompressionMode: e_ptmn_jbig2];
122 [mono_image_settings ForceRecompression: true];
123
124 PTOptimizerSettings *opt_settings = [[PTOptimizerSettings alloc] init];
125 [opt_settings SetMonoImageSettings: mono_image_settings];
126
127 [PTOptimizer Optimize: doc settings: opt_settings];
128
129 [doc SaveToFile: @"../../TestFiles/Output/newsletter_opt3.pdf" flags: e_ptlinearized];
130 }
131 @catch (NSException *e)
132 {
133 NSLog(@"%@", e.reason);
134 ret = 1;
135 }
136
137 // ----------------------------------------------------------------------
138 // Example 4) Use Flattener to simplify content in this document
139 // using default settings
140 @try
141 {
142 PTPDFDoc *doc = [[PTPDFDoc alloc] initWithFilepath: @"../../TestFiles/TigerText.pdf"];
143 [doc InitSecurityHandler];
144
145 PTFlattener *fl = [[PTFlattener alloc] init];
146 // The following lines can increase the resolution of background
147 // images.
148 //[fl SetDPI: 300];
149 //[fl SetMaximumImagePixels: 5000000];
150
151 // This line can be used to output Flate compressed background
152 // images rather than DCTDecode compressed images which is the default
153 //[fl SetPreferJPG: false];
154
155 // In order to adjust thresholds for when text is Flattened
156 // the following function can be used.
157 //[fl SetThreshold: e_threshold_keep_most];
158
159 // We use e_ptfast option here since it is usually preferable
160 // to avoid Flattening simple pages in terms of size and
161 // rendering speed. If the desire is to simplify the
162 // document for processing such that it contains only text and
163 // a background image e_simple should be used instead.
164 [fl Process: doc mode: e_ptfast];
165 [doc SaveToFile: @"../../TestFiles/Output/TigerText_flatten.pdf" flags: e_ptlinearized];
166 }
167 @catch (NSException *e)
168 {
169 NSLog(@"%@", e.reason);
170 ret = 1;
171 }
172
173 // ----------------------------------------------------------------------
174 // Example 5) Optimize a PDF for viewing using SaveViewerOptimized.
175 @try
176 {
177 PTPDFDoc *doc = [[PTPDFDoc alloc] initWithFilepath: @"../../TestFiles/newsletter.pdf"];
178 [doc InitSecurityHandler];
179
180 PTViewerOptimizedOptions *options = [[PTViewerOptimizedOptions alloc] init];
181
182 // set the maximum dimension (width or height) that thumbnails will have.
183 [options SetThumbnailSize: 1500];
184
185 // set thumbnail rendering threshold. A number from 0 (include all thumbnails) to 100 (include only the first thumbnail)
186 // representing the complexity at which SaveViewerOptimized would include the thumbnail.
187 // By default it only produces thumbnails on the first and complex pages.
188 // The following line will produce thumbnails on every page.
189 // [options SetThumbnailRenderingThreshold: 0];
190
191 [doc SaveViewerOptimized: @"../../TestFiles/Output/newsletter_SaveViewerOptimized.pdf" opts: options];
192 }
193 @catch (NSException *e)
194 {
195 NSLog(@"%@", e.reason);
196 ret = 1;
197 }
198
199 [PTPDFNet Terminate: 0];
200 //NSLog(@"Done");
201 return ret;
202 }
203}
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// The following sample illustrates how to reduce PDF file size using 'pdftron.PDF.Optimizer'.
11// The sample also shows how to simplify and optimize PDF documents for viewing on mobile devices
12// and on the Web using 'pdftron.PDF.Flattener'.
13//
14// @note Both 'Optimizer' and 'Flattener' are separately licensable add-on options to the core PDFNet license.
15//
16// ----
17//
18// 'pdftron.PDF.Optimizer' can be used to optimize PDF documents by reducing the file size, removing
19// redundant information, and compressing data streams using the latest in image compression technology.
20//
21// PDF Optimizer can compress and shrink PDF file size with the following operations:
22// - Remove duplicated fonts, images, ICC profiles, and any other data stream.
23// - Optionally convert high-quality or print-ready PDF files to small, efficient and web-ready PDF.
24// - Optionally down-sample large images to a given resolution.
25// - Optionally compress or recompress PDF images using JBIG2 and JPEG2000 compression formats.
26// - Compress uncompressed streams and remove unused PDF objects.
27// ----
28//
29// 'pdftron.PDF.Flattener' can be used to speed-up PDF rendering on mobile devices and on the Web by
30// simplifying page content (e.g. flattening complex graphics into images) while maintaining vector text
31// whenever possible.
32//
33// Flattener can also be used to simplify process of writing custom converters from PDF to other formats.
34// In this case, Flattener can be used as first step in the conversion pipeline to reduce any PDF to a
35// very simple representation (e.g. vector text on top of a background image).
36//---------------------------------------------------------------------------------------
37
38func runOptimizerTest() -> Int {
39 return autoreleasepool {
40 var ret: Int = 0
41
42 // The first step in every application using PDFNet is to initialize the
43 // library and set the path to common PDF resources. The library is usually
44 // initialized only once, but calling Initialize() multiple times is also fine.
45
46
47 //--------------------------------------------------------------------------------
48 // Example 1) Simple optimization of a pdf with default settings.
49 //
50 do {
51 try PTPDFNet.catchException {
52 let doc: PTPDFDoc = PTPDFDoc(filepath: Bundle.main.path(forResource: "newsletter", ofType: "pdf"))
53 doc.initSecurityHandler()
54
55 PTOptimizer.optimize(doc, settings: PTOptimizerSettings())
56
57 doc.save(toFile: URL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]).appendingPathComponent("newsletter_opt1.pdf").path, flags: e_ptlinearized.rawValue)
58 }
59 } catch let e as NSError {
60 print("\(e)")
61 ret = 1
62 }
63
64 //--------------------------------------------------------------------------------
65 // Example 2) Reduce image quality and use jpeg compression for
66 // non monochrome images.
67 do {
68 try PTPDFNet.catchException {
69 let doc: PTPDFDoc = PTPDFDoc(filepath: Bundle.main.path(forResource: "newsletter", ofType: "pdf"))
70 doc.initSecurityHandler()
71
72 let image_settings: PTImageSettings = PTImageSettings()
73
74 // low quality jpeg compression
75 image_settings.setCompressionMode(e_ptjpeg)
76 image_settings.setQuality(1)
77
78 // Set the output dpi to be standard screen resolution
79 image_settings.setImageDPI(144, resampling: 96)
80
81 // this option will recompress images not compressed with
82 // jpeg compression and use the result if the new image
83 // is smaller.
84 image_settings.forceRecompression(true)
85
86 // this option is not commonly used since it can
87 // potentially lead to larger files. It should be enabled
88 // only if the output compression specified should be applied
89 // to every image of a given type regardless of the output image size
90 //image_settings.ForceChanges(true);
91
92 let opt_settings: PTOptimizerSettings = PTOptimizerSettings()
93 opt_settings.setColorImageSettings(image_settings)
94 opt_settings.setGrayscaleImageSettings(image_settings)
95
96 // use the same settings for both color and grayscale images
97 PTOptimizer.optimize(doc, settings: opt_settings)
98
99 doc.save(toFile: URL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]).appendingPathComponent("newsletter_opt2.pdf").path, flags: e_ptlinearized.rawValue)
100 }
101 } catch let e as NSError {
102 print("\(e)")
103 ret = 1
104 }
105
106 //--------------------------------------------------------------------------------
107 // Example 3) Use monochrome image settings and default settings
108 // for color and grayscale images.
109 do {
110 try PTPDFNet.catchException {
111 let doc: PTPDFDoc = PTPDFDoc(filepath: Bundle.main.path(forResource: "newsletter", ofType: "pdf"))
112 doc.initSecurityHandler()
113
114 let mono_image_settings: PTMonoImageSettings = PTMonoImageSettings()
115
116 mono_image_settings.setCompressionMode(e_ptmn_jbig2)
117 mono_image_settings.forceRecompression(true)
118
119 let opt_settings: PTOptimizerSettings = PTOptimizerSettings()
120 opt_settings.setMonoImageSettings(mono_image_settings)
121
122 PTOptimizer.optimize(doc, settings: opt_settings)
123
124 doc.save(toFile: URL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]).appendingPathComponent("newsletter_opt3.pdf").path, flags: e_ptlinearized.rawValue)
125 }
126 } catch let e as NSError {
127 print("\(e)")
128 ret = 1
129 }
130
131 // ----------------------------------------------------------------------
132 // Example 4) Use Flattener to simplify content in this document
133 // using default settings
134 do {
135 try PTPDFNet.catchException {
136 let doc: PTPDFDoc = PTPDFDoc(filepath: Bundle.main.path(forResource: "TigerText", ofType: "pdf"))
137 doc.initSecurityHandler()
138
139 let fl: PTFlattener = PTFlattener()
140 // The following lines can increase the resolution of background
141 // images.
142 //fl.setDPI(300)
143 //fl.setMaximumImagePixels(5000000)
144
145 // This line can be used to output Flate compressed background
146 // images rather than DCTDecode compressed images which is the default
147 //fl.setPreferJPG(false)
148
149 // In order to adjust thresholds for when text is Flattened
150 // the following function can be used.
151 //fl.setThreshold(e_ptthreshold_keep_most)
152
153 // We use e_ptfast option here since it is usually preferable
154 // to avoid Flattening simple pages in terms of size and
155 // rendering speed. If the desire is to simplify the
156 // document for processing such that it contains only text and
157 // a background image e_simple should be used instead.
158 fl.process(doc, mode: e_ptfast)
159 doc.save(toFile: URL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]).appendingPathComponent("TigerText_flatten.pdf").path, flags: e_ptlinearized.rawValue)
160 }
161 } catch let e as NSError {
162 print("\(e)")
163 ret = 1
164 }
165
166 print("Done")
167 return ret
168 }
169}
Did you find this helpful?
Trial setup questions?
Ask experts on DiscordNeed other help?
Contact SupportPricing or product questions?
Contact Sales