Optimizer

Sample 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 Server 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
6using System;
7using System.IO;
8
9using pdftron;
10using pdftron.Common;
11using pdftron.Filters;
12using pdftron.SDF;
13using pdftron.PDF;
14
15namespace PDFNetSamples
16{
17 class Class1
18 {
19 private static pdftron.PDFNetLoader pdfNetLoader = pdftron.PDFNetLoader.Instance();
20 static Class1() {}
21
22 /// <summary>
23 /// The following sample illustrates how to reduce PDF file size using 'pdftron.PDF.Optimizer'.
24 /// The sample also shows how to simplify and optimize PDF documents for viewing on mobile devices
25 /// and on the Web using 'pdftron.PDF.Flattener'.
26 ///
27 /// @note Both 'Optimizer' and 'Flattener' are separately licensable add-on options to the core PDFNet license.
28 ///
29 /// ----
30 ///
31 /// 'pdftron.PDF.Optimizer' can be used to optimize PDF documents by reducing the file size, removing
32 /// redundant information, and compressing data streams using the latest in image compression technology.
33 ///
34 /// PDF Optimizer can compress and shrink PDF file size with the following operations:
35 /// - Remove duplicated fonts, images, ICC profiles, and any other data stream.
36 /// - Optionally convert high-quality or print-ready PDF files to small, efficient and web-ready PDF.
37 /// - Optionally down-sample large images to a given resolution.
38 /// - Optionally compress or recompress PDF images using JBIG2 and JPEG2000 compression formats.
39 /// - Compress uncompressed streams and remove unused PDF objects.
40 ///
41 /// ----
42 ///
43 /// 'pdftron.PDF.Flattener' can be used to speed-up PDF rendering on mobile devices and on the Web by
44 /// simplifying page content (e.g. flattening complex graphics into images) while maintaining vector text
45 /// whenever possible.
46 ///
47 /// Flattener can also be used to simplify process of writing custom converters from PDF to other formats.
48 /// In this case, Flattener can be used as first step in the conversion pipeline to reduce any PDF to a
49 /// very simple representation (e.g. vector text on top of a background image).
50 /// </summary>
51 static void Main(string[] args)
52 {
53 PDFNet.Initialize(PDFTronLicense.Key);
54
55 string input_path = "../../../../TestFiles/";
56 string output_path = "../../../../TestFiles/Output/";
57 string input_filename = "newsletter";
58
59
60 //--------------------------------------------------------------------------------
61 // Example 1) Simple optimization of a pdf with default settings.
62 //
63 try
64 {
65 using (PDFDoc doc = new PDFDoc(input_path + input_filename + ".pdf"))
66 {
67 doc.InitSecurityHandler();
68 Optimizer.Optimize(doc);
69 doc.Save(output_path + input_filename + "_opt1.pdf", SDFDoc.SaveOptions.e_linearized);
70 }
71 }
72 catch (PDFNetException e)
73 {
74 Console.WriteLine(e.Message);
75 }
76
77 //--------------------------------------------------------------------------------
78 // Example 2) Reduce image quality and use jpeg compression for
79 // non monochrome images.
80 try
81 {
82 using (PDFDoc doc = new PDFDoc(input_path + input_filename + ".pdf"))
83 {
84 doc.InitSecurityHandler();
85
86 Optimizer.ImageSettings image_settings = new Optimizer.ImageSettings();
87
88 // low quality jpeg compression
89 image_settings.SetCompressionMode(Optimizer.ImageSettings.CompressionMode.e_jpeg);
90 image_settings.SetQuality(1);
91
92 // Set the output dpi to be standard screen resolution
93 image_settings.SetImageDPI(144,96);
94
95 // this option will recompress images not compressed with
96 // jpeg compression and use the result if the new image
97 // is smaller.
98 image_settings.ForceRecompression(true);
99
100 // this option is not commonly used since it can
101 // potentially lead to larger files. It should be enabled
102 // only if the output compression specified should be applied
103 // to every image of a given type regardless of the output image size
104 //image_settings.ForceChanges(true);
105
106 // use the same settings for both color and grayscale images
107 Optimizer.OptimizerSettings opt_settings = new Optimizer.OptimizerSettings();
108 opt_settings.SetColorImageSettings(image_settings);
109 opt_settings.SetGrayscaleImageSettings(image_settings);
110
111
112 Optimizer.Optimize(doc, opt_settings);
113
114 doc.Save(output_path + input_filename + "_opt2.pdf", SDFDoc.SaveOptions.e_linearized);
115 }
116 }
117 catch (PDFNetException e)
118 {
119 Console.WriteLine(e.Message);
120 }
121
122
123 //--------------------------------------------------------------------------------
124 // Example 3) Use monochrome image settings and default settings
125 // for color and grayscale images.
126 try
127 {
128 using (PDFDoc doc = new PDFDoc(input_path + input_filename + ".pdf"))
129 {
130 doc.InitSecurityHandler();
131
132 Optimizer.MonoImageSettings mono_image_settings = new Optimizer.MonoImageSettings();
133
134 mono_image_settings.SetCompressionMode(Optimizer.MonoImageSettings.CompressionMode.e_jbig2);
135 mono_image_settings.ForceRecompression(true);
136
137 Optimizer.OptimizerSettings opt_settings = new Optimizer.OptimizerSettings();
138 opt_settings.SetMonoImageSettings(mono_image_settings);
139
140 Optimizer.Optimize(doc, opt_settings);
141
142 doc.Save(output_path + input_filename + "_opt3.pdf", SDFDoc.SaveOptions.e_linearized);
143 }
144 }
145 catch (PDFNetException e)
146 {
147 Console.WriteLine(e.Message);
148 }
149
150 //-------------------------------------------------------------------------------
151 // Example 4) Use Flattener to simplify content in this document
152 // using default settings
153
154 try
155 {
156 using (PDFDoc doc = new PDFDoc(input_path + "TigerText.pdf"))
157 {
158 doc.InitSecurityHandler();
159
160 Flattener fl = new Flattener();
161
162 // The following lines can increase the resolution of background
163 // images.
164 //fl.SetDPI(300);
165 //fl.SetMaximumImagePixels(5000000);
166
167 // This line can be used to output Flate compressed background
168 // images rather than DCTDecode compressed images which is the default
169 //fl.SetPreferJPG(false);
170
171 // In order to adjust thresholds for when text is Flattened
172 // the following function can be used.
173 //fl.SetThreshold(Flattener.Threshold.e_keep_most);
174
175 // We use e_fast option here since it is usually preferable
176 // to avoid Flattening simple pages in terms of size and
177 // rendering speed. If the desire is to simplify the
178 // document for processing such that it contains only text and
179 // a background image e_simple should be used instead.
180 fl.Process(doc,Flattener.FlattenMode.e_fast);
181
182 doc.Save(output_path + "TigerText_flatten.pdf", SDFDoc.SaveOptions.e_linearized);
183 }
184 }
185 catch (PDFNetException e)
186 {
187 Console.WriteLine(e.Message);
188 }
189
190 //-------------------------------------------------------------------------------
191 // Example 5) Optimize a PDF for viewing using SaveViewerOptimized.
192
193 try
194 {
195 using (PDFDoc doc = new PDFDoc(input_path + input_filename + ".pdf"))
196 {
197 doc.InitSecurityHandler();
198
199 ViewerOptimizedOptions opts = new ViewerOptimizedOptions();
200
201 // set the maximum dimension (width or height) that thumbnails will have.
202 opts.SetThumbnailSize(1500);
203
204 // set thumbnail rendering threshold. A number from 0 (include all thumbnails) to 100 (include only the first thumbnail)
205 // representing the complexity at which SaveViewerOptimized would include the thumbnail.
206 // By default it only produces thumbnails on the first and complex pages.
207 // The following line will produce thumbnails on every page.
208 // opts.SetThumbnailRenderingThreshold(0);
209
210 doc.SaveViewerOptimized(output_path + input_filename + "_SaveViewerOptimized.pdf", opts);
211 }
212 }
213 catch (PDFNetException e)
214 {
215 Console.WriteLine(e.Message);
216 }
217 PDFNet.Terminate();
218 }
219 }
220}

Did you find this helpful?

Trial setup questions?

Ask experts on Discord

Need other help?

Contact Support

Pricing or product questions?

Contact Sales