Sample Java 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 Android SDK.
1//---------------------------------------------------------------------------------------
2// Copyright (c) 2001-2019 by PDFTron Systems Inc. All Rights Reserved.
3// Consult legal.txt regarding legal and license information.
4//---------------------------------------------------------------------------------------
5
6package com.pdftron.android.pdfnetsdksamples.samples;
7
8import com.pdftron.android.pdfnetsdksamples.OutputListener;
9import com.pdftron.android.pdfnetsdksamples.PDFNetSample;
10import com.pdftron.android.pdfnetsdksamples.R;
11import com.pdftron.android.pdfnetsdksamples.util.Utils;
12import com.pdftron.pdf.Flattener;
13import com.pdftron.pdf.Optimizer;
14import com.pdftron.pdf.PDFDoc;
15import com.pdftron.pdf.ViewerOptimizedOptions;
16import com.pdftron.sdf.SDFDoc;
17
18import java.util.ArrayList;
19
20/**
21 * The following sample illustrates how to reduce PDF file size using 'com.pdftron.pdf.Optimizer' class.
22 * The sample also shows how to simplify and optimize PDF documents for viewing on mobile devices
23 * and on the Web using 'com.pdftron.pdf.Flattener'.
24 *
25 * <p>
26 * Note: Both 'Optimizer' and 'Flattener' are separately licensable add-on options to the core
27 * PDFNet license.
28 *
29 * <p>
30 * 'com.pdftron.pdf.Optimizer' can be used to optimize PDF documents by reducing the file size, removing
31 * redundant information, and compressing data streams using the latest in image compression
32 * technology.
33 * <p>
34 * PDF Optimizer can compress and shrink PDF file size with the following operations:
35 * <ul>
36 * <li>Remove duplicated fonts, images, ICC profiles, and any other data stream.
37 * <li>Optionally convert high-quality or print-ready PDF files to small, efficient and web-ready PDF.
38 * <li>Optionally down-sample large images to a given resolution.
39 * <li>Optionally compress or recompress PDF images using JBIG2 and JPEG2000 compression formats.
40 * <li>Compress uncompressed streams and remove unused PDF objects.
41 * </ul>
42 *
43 * <p>
44 * 'com.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
46 * text whenever possible.
47 *
48 * <p>
49 * Flattener can also be used to simplify process of writing custom converters from PDF to other
50 * formats. In this case, Flattener can be used as first step in the conversion pipeline to reduce
51 * any PDF to a very simple representation (e.g. vector text on top of a background image).
52 */
53public class OptimizerTest extends PDFNetSample {
54
55 private static OutputListener mOutputListener;
56
57 private static ArrayList<String> mFileList = new ArrayList<>();
58
59 public OptimizerTest() {
60 setTitle(R.string.sample_optimizer_title);
61 setDescription(R.string.sample_optimizer_description);
62
63 // The standard library does not include the Optimizer and Flattener features.
64 // If using the full library, please comment out the following call to enable the sample.
65 // DisableRun();
66 }
67
68 @Override
69 public void run(OutputListener outputListener) {
70 super.run(outputListener);
71 mOutputListener = outputListener;
72 mFileList.clear();
73 printHeader(outputListener);
74 String input_filename = "newsletter.pdf";
75 String input_filename2 = "newsletter_opt1.pdf";
76 String input_filename3 = "newsletter_opt2.pdf";
77 String input_filename4 = "newsletter_opt3.pdf";
78 String input_filename5 = "newsletter_SaveViewerOptimized.pdf";
79
80 //--------------------------------------------------------------------------------
81 // Example 1) Optimize a PDF.
82 try (PDFDoc doc = new PDFDoc(Utils.getAssetTempFile(INPUT_PATH + input_filename).getAbsolutePath())) {
83 doc.initSecurityHandler();
84 Optimizer.optimize(doc);
85 doc.save(Utils.createExternalFile(input_filename2, mFileList).getAbsolutePath(), SDFDoc.SaveMode.LINEARIZED, null);
86 } catch (Exception e) {
87 mOutputListener.printError(e.getStackTrace());
88 return;
89 }
90
91 //--------------------------------------------------------------------------------
92 // Example 2) Reduce image quality and use jpeg compression for
93 // non monochrome images.
94 try (PDFDoc doc = new PDFDoc(Utils.getAssetTempFile(INPUT_PATH + input_filename).getAbsolutePath())) {
95 doc.initSecurityHandler();
96
97 Optimizer.ImageSettings image_settings = new Optimizer.ImageSettings();
98
99 // low quality jpeg compression
100 image_settings.setCompressionMode(Optimizer.ImageSettings.e_jpeg);
101 image_settings.setQuality(1);
102
103 // Set the output dpi to be standard screen resolution
104 image_settings.setImageDPI(144, 96);
105
106 // this option will recompress images not compressed with
107 // jpeg compression and use the result if the new image
108 // is smaller.
109 image_settings.forceRecompression(true);
110
111 // this option is not commonly used since it can
112 // potentially lead to larger files. It should be enabled
113 // only if the output compression specified should be applied
114 // to every image of a given type regardless of the output image size
115 //image_settings.forceChanges(true);
116
117 Optimizer.OptimizerSettings opt_settings = new Optimizer.OptimizerSettings();
118 opt_settings.setColorImageSettings(image_settings);
119 opt_settings.setGrayscaleImageSettings(image_settings);
120
121 Optimizer.optimize(doc, opt_settings);
122
123 doc.save(Utils.createExternalFile(input_filename3, mFileList).getAbsolutePath(), SDFDoc.SaveMode.LINEARIZED, null);
124 } catch (Exception e) {
125 mOutputListener.printError(e.getStackTrace());
126 return;
127 }
128
129 //--------------------------------------------------------------------------------
130 // Example 3) Use monochrome image settings and default settings
131 // for color and grayscale images.
132 try (PDFDoc doc = new PDFDoc(Utils.getAssetTempFile(INPUT_PATH + input_filename).getAbsolutePath())) {
133 doc.initSecurityHandler();
134
135 Optimizer.MonoImageSettings mono_image_settings = new Optimizer.MonoImageSettings();
136 mono_image_settings.setCompressionMode(Optimizer.MonoImageSettings.e_jbig2);
137 mono_image_settings.forceRecompression(true);
138 Optimizer.OptimizerSettings opt_settings = new Optimizer.OptimizerSettings();
139 opt_settings.setMonoImageSettings(mono_image_settings);
140
141 Optimizer.optimize(doc, opt_settings);
142
143 doc.save(Utils.createExternalFile(input_filename4, mFileList).getAbsolutePath(), SDFDoc.SaveMode.LINEARIZED, null);
144 } catch (Exception e) {
145 mOutputListener.printError(e.getStackTrace());
146 return;
147 }
148
149 // ----------------------------------------------------------------------
150 // Example 4) Use Flattener to simplify content in this document
151 // using default settings
152 try (PDFDoc doc = new PDFDoc(Utils.getAssetTempFile(INPUT_PATH + "TigerText.pdf").getAbsolutePath())) {
153 doc.initSecurityHandler();
154
155 Flattener fl = new Flattener();
156
157 // The following lines can increase the resolution of background
158 // images.
159 //fl.setDPI(300);
160 //fl.setMaximumImagePixels(5000000);
161
162 // This line can be used to output Flate compressed background
163 // images rather than DCTDecode compressed images which is the default
164 //fl.setPreferJPG(false);
165
166 // In order to adjust thresholds for when text is Flattened
167 // the following function can be used.
168 //fl.setThreshold(Flattener.e_keep_most);
169
170 // We use e_fast option here since it is usually preferable
171 // to avoid Flattening simple pages in terms of size and
172 // rendering speed. If the desire is to simplify the
173 // document for processing such that it contains only text and
174 // a background image e_simple should be used instead.
175 fl.Process(doc, Flattener.e_fast);
176
177 doc.save(Utils.createExternalFile("TigerText_flatten.pdf", mFileList).getAbsolutePath(), SDFDoc.SaveMode.LINEARIZED, null);
178 } catch (Exception e) {
179 mOutputListener.printError(e.getStackTrace());
180 return;
181 }
182
183 // ----------------------------------------------------------------------
184 // Example 5) Optimize a PDF for viewing using SaveViewerOptimized.
185 try (PDFDoc doc = new PDFDoc(Utils.getAssetTempFile(INPUT_PATH + input_filename).getAbsolutePath())) {
186 doc.initSecurityHandler();
187
188 ViewerOptimizedOptions opts = new ViewerOptimizedOptions();
189
190 // set the maximum dimension (width or height) that thumbnails will have.
191 opts.setThumbnailSize(1500);
192
193 // set thumbnail rendering threshold. A number from 0 (include all thumbnails) to 100 (include only the first thumbnail)
194 // representing the complexity at which SaveViewerOptimized would include the thumbnail.
195 // By default it only produces thumbnails on the first and complex pages.
196 // The following line will produce thumbnails on every page.
197 // opts.setThumbnailRenderingThreshold(0);
198
199 doc.saveViewerOptimized(Utils.createExternalFile(input_filename5 , mFileList).getAbsolutePath(), opts);
200 } catch (Exception e) {
201 mOutputListener.printError(e.getStackTrace());
202 return;
203 }
204
205 for (String file : mFileList) {
206 addToFileList(file);
207 }
208 printFooter(outputListener);
209 }
210 //---------------------------------------------------------------------------------------
211 // The following sample illustrates how to reduce PDF file size using 'pdftron.PDF.Optimizer'.
212 // The sample also shows how to simplify and optimize PDF documents for viewing on mobile devices
213 // and on the Web using 'pdftron.PDF.Flattener'.
214 //
215 // @note Both 'Optimizer' and 'Flattener' are separately licensable add-on options to the core PDFNet license.
216 //
217 // ----
218 //
219 // 'pdftron.PDF.Optimizer' can be used to optimize PDF documents by reducing the file size, removing
220 // redundant information, and compressing data streams using the latest in image compression technology.
221 //
222 // PDF Optimizer can compress and shrink PDF file size with the following operations:
223 // - Remove duplicated fonts, images, ICC profiles, and any other data stream.
224 // - Optionally convert high-quality or print-ready PDF files to small, efficient and web-ready PDF.
225 // - Optionally down-sample large images to a given resolution.
226 // - Optionally compress or recompress PDF images using JBIG2 and JPEG2000 compression formats.
227 // - Compress uncompressed streams and remove unused PDF objects.
228 //
229 // 'pdftron.PDF.Flattener' can be used to speed-up PDF rendering on mobile devices and on the Web by
230 // simplifying page content (e.g. flattening complex graphics into images) while maintaining vector text
231 // whenever possible.
232 //
233 // Flattener can also be used to simplify process of writing custom converters from PDF to other formats.
234 // In this case, Flattener can be used as first step in the conversion pipeline to reduce any PDF to a
235 // very simple representation (e.g. vector text on top of a background image).
236 //---------------------------------------------------------------------------------------
237
238}
1//---------------------------------------------------------------------------------------
2// Copyright (c) 2001-2019 by PDFTron Systems Inc. All Rights Reserved.
3// Consult legal.txt regarding legal and license information.
4//---------------------------------------------------------------------------------------
5
6package com.pdftron.android.pdfnetsdksamples.samples
7
8import com.pdftron.android.pdfnetsdksamples.OutputListener
9import com.pdftron.android.pdfnetsdksamples.PDFNetSample
10import com.pdftron.android.pdfnetsdksamples.R
11import com.pdftron.android.pdfnetsdksamples.util.Utils
12import com.pdftron.pdf.Flattener
13import com.pdftron.pdf.Optimizer
14import com.pdftron.pdf.PDFDoc
15import com.pdftron.pdf.ViewerOptimizedOptions
16import com.pdftron.sdf.SDFDoc
17
18import java.util.ArrayList
19
20/**
21 * The following sample illustrates how to reduce PDF file size using 'com.pdftron.pdf.Optimizer' class.
22 * The sample also shows how to simplify and optimize PDF documents for viewing on mobile devices
23 * and on the Web using 'com.pdftron.pdf.Flattener'.
24 *
25 *
26 *
27 * Note: Both 'Optimizer' and 'Flattener' are separately licensable add-on options to the core
28 * PDFNet license.
29 *
30 *
31 *
32 * 'com.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
34 * technology.
35 *
36 *
37 * PDF Optimizer can compress and shrink PDF file size with the following operations:
38 *
39 * * Remove duplicated fonts, images, ICC profiles, and any other data stream.
40 * * Optionally convert high-quality or print-ready PDF files to small, efficient and web-ready PDF.
41 * * Optionally down-sample large images to a given resolution.
42 * * Optionally compress or recompress PDF images using JBIG2 and JPEG2000 compression formats.
43 * * Compress uncompressed streams and remove unused PDF objects.
44 *
45 *
46 *
47 *
48 * 'com.pdftron.pdf.Flattener' can be used to speed-up PDF rendering on mobile devices and on the Web by
49 * simplifying page content (e.g. flattening complex graphics into images) while maintaining vector
50 * text whenever possible.
51 *
52 *
53 *
54 * Flattener can also be used to simplify process of writing custom converters from PDF to other
55 * formats. In this case, Flattener can be used as first step in the conversion pipeline to reduce
56 * any PDF to a very simple representation (e.g. vector text on top of a background image).
57 */
58class OptimizerTest : PDFNetSample() {
59 init {
60 setTitle(R.string.sample_optimizer_title)
61 setDescription(R.string.sample_optimizer_description)
62
63 // The standard library does not include the Optimizer and Flattener features.
64 // If using the full library, please comment out the following call to enable the sample.
65 // DisableRun();
66 }
67
68 override fun run(outputListener: OutputListener?) {
69 super.run(outputListener)
70 mOutputListener = outputListener
71 mFileList.clear()
72 printHeader(outputListener!!)
73 val input_filename = "newsletter.pdf"
74 val input_filename2 = "newsletter_opt1.pdf"
75 val input_filename3 = "newsletter_opt2.pdf"
76 val input_filename4 = "newsletter_opt3.pdf"
77 val input_filename5 = "newsletter_SaveViewerOptimized.pdf"
78
79 //--------------------------------------------------------------------------------
80 // Example 1) Optimize a PDF.
81 try {
82 PDFDoc(Utils.getAssetTempFile(PDFNetSample.INPUT_PATH + input_filename)!!.absolutePath).use { doc ->
83 doc.initSecurityHandler()
84 Optimizer.optimize(doc)
85 doc.save(Utils.createExternalFile(input_filename2, mFileList).absolutePath, SDFDoc.SaveMode.LINEARIZED, null)
86 }
87 } catch (e: Exception) {
88 mOutputListener!!.printError(e.stackTrace)
89 return
90 }
91
92 //--------------------------------------------------------------------------------
93 // Example 2) Reduce image quality and use jpeg compression for
94 // non monochrome images.
95 try {
96 PDFDoc(Utils.getAssetTempFile(PDFNetSample.INPUT_PATH + input_filename)!!.absolutePath).use { doc ->
97 doc.initSecurityHandler()
98
99 val image_settings = Optimizer.ImageSettings()
100
101 // low quality jpeg compression
102 image_settings.setCompressionMode(Optimizer.ImageSettings.e_jpeg)
103 image_settings.setQuality(1)
104
105 // Set the output dpi to be standard screen resolution
106 image_settings.setImageDPI(144.0, 96.0)
107
108 // this option will recompress images not compressed with
109 // jpeg compression and use the result if the new image
110 // is smaller.
111 image_settings.forceRecompression(true)
112
113 // this option is not commonly used since it can
114 // potentially lead to larger files. It should be enabled
115 // only if the output compression specified should be applied
116 // to every image of a given type regardless of the output image size
117 //image_settings.forceChanges(true);
118
119 val opt_settings = Optimizer.OptimizerSettings()
120 opt_settings.setColorImageSettings(image_settings)
121 opt_settings.setGrayscaleImageSettings(image_settings)
122
123 Optimizer.optimize(doc, opt_settings)
124
125 doc.save(Utils.createExternalFile(input_filename3, mFileList).absolutePath, SDFDoc.SaveMode.LINEARIZED, null)
126 }
127 } catch (e: Exception) {
128 mOutputListener!!.printError(e.stackTrace)
129 return
130 }
131
132 //--------------------------------------------------------------------------------
133 // Example 3) Use monochrome image settings and default settings
134 // for color and grayscale images.
135 try {
136 PDFDoc(Utils.getAssetTempFile(PDFNetSample.INPUT_PATH + input_filename)!!.absolutePath).use { doc ->
137 doc.initSecurityHandler()
138
139 val mono_image_settings = Optimizer.MonoImageSettings()
140 mono_image_settings.setCompressionMode(Optimizer.MonoImageSettings.e_jbig2)
141 mono_image_settings.forceRecompression(true)
142 val opt_settings = Optimizer.OptimizerSettings()
143 opt_settings.setMonoImageSettings(mono_image_settings)
144
145 Optimizer.optimize(doc, opt_settings)
146
147 doc.save(Utils.createExternalFile(input_filename4, mFileList).absolutePath, SDFDoc.SaveMode.LINEARIZED, null)
148 }
149 } catch (e: Exception) {
150 mOutputListener!!.printError(e.stackTrace)
151 return
152 }
153
154 // ----------------------------------------------------------------------
155 // Example 4) Use Flattener to simplify content in this document
156 // using default settings
157 try {
158 PDFDoc(Utils.getAssetTempFile(PDFNetSample.INPUT_PATH + "TigerText.pdf")!!.absolutePath).use { doc ->
159 doc.initSecurityHandler()
160
161 val fl = Flattener()
162
163 // The following lines can increase the resolution of background
164 // images.
165 //fl.setDPI(300);
166 //fl.setMaximumImagePixels(5000000);
167
168 // This line can be used to output Flate compressed background
169 // images rather than DCTDecode compressed images which is the default
170 //fl.setPreferJPG(false);
171
172 // In order to adjust thresholds for when text is Flattened
173 // the following function can be used.
174 //fl.setThreshold(Flattener.e_keep_most);
175
176 // We use e_fast option here since it is usually preferable
177 // to avoid Flattening simple pages in terms of size and
178 // rendering speed. If the desire is to simplify the
179 // document for processing such that it contains only text and
180 // a background image e_simple should be used instead.
181 fl.Process(doc, Flattener.e_fast)
182
183 doc.save(Utils.createExternalFile("TigerText_flatten.pdf", mFileList).absolutePath, SDFDoc.SaveMode.LINEARIZED, null)
184 }
185 } catch (e: Exception) {
186 mOutputListener!!.printError(e.stackTrace)
187 return
188 }
189
190 // ----------------------------------------------------------------------
191 // Example 5) Optimize a PDF for viewing using SaveViewerOptimized.
192 try {
193 PDFDoc(Utils.getAssetTempFile(PDFNetSample.INPUT_PATH + input_filename)!!.absolutePath).use { doc ->
194 doc.initSecurityHandler()
195
196 val opts = ViewerOptimizedOptions()
197
198 // set the maximum dimension (width or height) that thumbnails will have.
199 opts.setThumbnailSize(1500)
200
201 // set thumbnail rendering threshold. A number from 0 (include all thumbnails) to 100 (include only the first thumbnail)
202 // representing the complexity at which SaveViewerOptimized would include the thumbnail.
203 // By default it only produces thumbnails on the first and complex pages.
204 // The following line will produce thumbnails on every page.
205 // opts.setThumbnailRenderingThreshold(0);
206
207 doc.saveViewerOptimized(Utils.createExternalFile(input_filename5, mFileList).absolutePath, opts)
208 }
209 } catch (e: Exception) {
210 mOutputListener!!.printError(e.stackTrace)
211 return
212 }
213
214 for (file in mFileList) {
215 addToFileList(file)
216 }
217 printFooter(outputListener)
218 }
219
220 companion object {
221
222 private var mOutputListener: OutputListener? = null
223
224 private val mFileList = ArrayList<String>()
225 }
226 //---------------------------------------------------------------------------------------
227 // The following sample illustrates how to reduce PDF file size using 'pdftron.PDF.Optimizer'.
228 // The sample also shows how to simplify and optimize PDF documents for viewing on mobile devices
229 // and on the Web using 'pdftron.PDF.Flattener'.
230 //
231 // @note Both 'Optimizer' and 'Flattener' are separately licensable add-on options to the core PDFNet license.
232 //
233 // ----
234 //
235 // 'pdftron.PDF.Optimizer' can be used to optimize PDF documents by reducing the file size, removing
236 // redundant information, and compressing data streams using the latest in image compression technology.
237 //
238 // PDF Optimizer can compress and shrink PDF file size with the following operations:
239 // - Remove duplicated fonts, images, ICC profiles, and any other data stream.
240 // - Optionally convert high-quality or print-ready PDF files to small, efficient and web-ready PDF.
241 // - Optionally down-sample large images to a given resolution.
242 // - Optionally compress or recompress PDF images using JBIG2 and JPEG2000 compression formats.
243 // - Compress uncompressed streams and remove unused PDF objects.
244 //
245 // 'pdftron.PDF.Flattener' can be used to speed-up PDF rendering on mobile devices and on the Web by
246 // simplifying page content (e.g. flattening complex graphics into images) while maintaining vector text
247 // whenever possible.
248 //
249 // Flattener can also be used to simplify process of writing custom converters from PDF to other formats.
250 // In this case, Flattener can be used as first step in the conversion pipeline to reduce any PDF to a
251 // very simple representation (e.g. vector text on top of a background image).
252 //---------------------------------------------------------------------------------------
253
254}
Did you find this helpful?
Trial setup questions?
Ask experts on DiscordNeed other help?
Contact SupportPricing or product questions?
Contact Sales