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