Compress PDFs - Optimizer - Java Sample Code

Sample 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. Samples provided in Python, C++, C#, Java, Node.js (JavaScript), PHP, Ruby and VB. 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
6import com.pdftron.pdf.*;
7import com.pdftron.sdf.SDFDoc;
8
9public class OptimizerTest {
10 //---------------------------------------------------------------------------------------
11 // The following sample illustrates how to reduce PDF file size using 'pdftron.PDF.Optimizer'.
12 // The sample also shows how to simplify and optimize PDF documents for viewing on mobile devices
13 // and on the Web using 'pdftron.PDF.Flattener'.
14 //
15 // @note Both 'Optimizer' and 'Flattener' are separately licensable add-on options to the core PDFNet license.
16 //
17 // ----
18 //
19 // 'pdftron.PDF.Optimizer' can be used to optimize PDF documents by reducing the file size, removing
20 // redundant information, and compressing data streams using the latest in image compression technology.
21 //
22 // PDF Optimizer can compress and shrink PDF file size with the following operations:
23 // - Remove duplicated fonts, images, ICC profiles, and any other data stream.
24 // - Optionally convert high-quality or print-ready PDF files to small, efficient and web-ready PDF.
25 // - Optionally down-sample large images to a given resolution.
26 // - Optionally compress or recompress PDF images using JBIG2 and JPEG2000 compression formats.
27 // - Compress uncompressed streams and remove unused PDF objects.
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 public static void main(String[] args) {
38 String input_path = "../../TestFiles/";
39 String output_path = "../../TestFiles/Output/";
40 String input_filename = "newsletter.pdf";
41 String input_filename2 = "newsletter_opt1.pdf";
42 String input_filename3 = "newsletter_opt2.pdf";
43 String input_filename4 = "newsletter_opt3.pdf";
44 String input_filename5 = "newsletter_SaveViewerOptimized.pdf";
45
46 PDFNet.initialize(PDFTronLicense.Key());
47
48 //--------------------------------------------------------------------------------
49 // Example 1) Optimize a PDF.
50 try (PDFDoc doc = new PDFDoc(input_path + input_filename)) {
51 doc.initSecurityHandler();
52 Optimizer.optimize(doc);
53 doc.save(output_path + input_filename2, SDFDoc.SaveMode.LINEARIZED, null);
54 } catch (Exception e) {
55 e.printStackTrace();
56 return;
57 }
58
59 //--------------------------------------------------------------------------------
60 // Example 2) Reduce image quality and use jpeg compression for
61 // non monochrome images.
62 try (PDFDoc doc = new PDFDoc(input_path + input_filename)) {
63 doc.initSecurityHandler();
64
65 Optimizer.ImageSettings image_settings = new Optimizer.ImageSettings();
66
67 // low quality jpeg compression
68 image_settings.setCompressionMode(Optimizer.ImageSettings.e_jpeg);
69 image_settings.setQuality(1);
70
71 // Set the output dpi to be standard screen resolution
72 image_settings.setImageDPI(144, 96);
73
74 // this option will recompress images not compressed with
75 // jpeg compression and use the result if the new image
76 // is smaller.
77 image_settings.forceRecompression(true);
78
79
80 // this option is not commonly used since it can
81 // potentially lead to larger files. It should be enabled
82 // only if the output compression specified should be applied
83 // to every image of a given type regardless of the output image size
84 //image_settings.forceChanges(true);
85
86 Optimizer.OptimizerSettings opt_settings = new Optimizer.OptimizerSettings();
87 opt_settings.setColorImageSettings(image_settings);
88 opt_settings.setGrayscaleImageSettings(image_settings);
89
90 Optimizer.optimize(doc, opt_settings);
91
92 doc.save(output_path + input_filename3, SDFDoc.SaveMode.LINEARIZED, null);
93 } catch (Exception e) {
94 e.printStackTrace();
95 return;
96 }
97
98 //--------------------------------------------------------------------------------
99 // Example 3) Use monochrome image settings and default settings
100 // for color and grayscale images.
101 try (PDFDoc doc = new PDFDoc(input_path + input_filename)) {
102 doc.initSecurityHandler();
103
104 Optimizer.MonoImageSettings mono_image_settings = new Optimizer.MonoImageSettings();
105 mono_image_settings.setCompressionMode(Optimizer.MonoImageSettings.e_jbig2);
106 mono_image_settings.forceRecompression(true);
107 Optimizer.OptimizerSettings opt_settings = new Optimizer.OptimizerSettings();
108 opt_settings.setMonoImageSettings(mono_image_settings);
109
110 Optimizer.optimize(doc, opt_settings);
111
112 doc.save(output_path + input_filename4, SDFDoc.SaveMode.LINEARIZED, null);
113 } catch (Exception e) {
114 e.printStackTrace();
115 return;
116 }
117
118 // ----------------------------------------------------------------------
119 // Example 4) Use Flattener to simplify content in this document
120 // using default settings
121 try (PDFDoc doc = new PDFDoc(input_path + "TigerText.pdf")) {
122 doc.initSecurityHandler();
123
124 Flattener fl = new Flattener();
125
126 // The following lines can increase the resolution of background
127 // images.
128 //fl.setDPI(300);
129 //fl.setMaximumImagePixels(5000000);
130
131 // This line can be used to output Flate compressed background
132 // images rather than DCTDecode compressed images which is the default
133 //fl.setPreferJPG(false);
134
135 // In order to adjust thresholds for when text is Flattened
136 // the following function can be used.
137 //fl.setThreshold(Flattener.e_keep_most);
138
139 // We use e_fast option here since it is usually preferable
140 // to avoid Flattening simple pages in terms of size and
141 // rendering speed. If the desire is to simplify the
142 // document for processing such that it contains only text and
143 // a background image e_simple should be used instead.
144 fl.Process(doc, Flattener.e_fast);
145
146 doc.save(output_path + "TigerText_flatten.pdf", SDFDoc.SaveMode.LINEARIZED, null);
147 } catch (Exception e) {
148 e.printStackTrace();
149 return;
150 }
151
152 // ----------------------------------------------------------------------
153 // Example 5) Optimize a PDF for viewing using SaveViewerOptimized.
154 try (PDFDoc doc = new PDFDoc(input_path + input_filename)) {
155 doc.initSecurityHandler();
156
157 ViewerOptimizedOptions opts = new ViewerOptimizedOptions();
158
159 // set the maximum dimension (width or height) that thumbnails will have.
160 opts.setThumbnailSize(1500);
161
162 // set thumbnail rendering threshold. A number from 0 (include all thumbnails) to 100 (include only the first thumbnail)
163 // representing the complexity at which SaveViewerOptimized would include the thumbnail.
164 // By default it only produces thumbnails on the first and complex pages.
165 // The following line will produce thumbnails on every page.
166 // opts.setThumbnailRenderingThreshold(0);
167
168 doc.saveViewerOptimized(output_path + input_filename5 , opts);
169 } catch (Exception e) {
170 e.printStackTrace();
171 return;
172 }
173 PDFNet.terminate();
174 }
175}

Did you find this helpful?

Trial setup questions?

Ask experts on Discord

Need other help?

Contact Support

Pricing or product questions?

Contact Sales