Optimizer

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}

Did you find this helpful?

Trial setup questions?

Ask experts on Discord

Need other help?

Contact Support

Pricing or product questions?

Contact Sales