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
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}
1//---------------------------------------------------------------------------------------
2// Copyright (c) 2001-2021 by PDFTron Systems Inc. All Rights Reserved.
3// Consult LICENSE.txt regarding license information.
4//---------------------------------------------------------------------------------------
5
6package main
7import (
8	. "pdftron"
9)
10
11import  "pdftron/Samples/LicenseKey/GO"
12//---------------------------------------------------------------------------------------
13// The following sample illustrates how to reduce PDF file size using 'pdftron.PDF.Optimizer'.
14// The sample also shows how to simplify and optimize PDF documents for viewing on mobile devices 
15// and on the Web using 'pdftron.PDF.Flattener'.
16//
17// @note Both 'Optimizer' and 'Flattener' are separately licensable add-on options to the core PDFNet license.
18//
19// ----
20//
21// 'pdftron.PDF.Optimizer' can be used to optimize PDF documents by reducing the file size, removing 
22// redundant information, and compressing data streams using the latest in image compression technology. 
23//
24// PDF Optimizer can compress and shrink PDF file size with the following operations:
25// - Remove duplicated fonts, images, ICC profiles, and any other data stream. 
26// - Optionally convert high-quality or print-ready PDF files to small, efficient and web-ready PDF. 
27// - Optionally down-sample large images to a given resolution. 
28// - Optionally compress or recompress PDF images using JBIG2 and JPEG2000 compression formats. 
29// - Compress uncompressed streams and remove unused PDF objects.
30// ----
31//
32// 'pdftron.PDF.Flattener' can be used to speed-up PDF rendering on mobile devices and on the Web by 
33// simplifying page content (e.g. flattening complex graphics into images) while maintaining vector text 
34// whenever possible.
35//
36// Flattener can also be used to simplify process of writing custom converters from PDF to other formats. 
37// In this case, Flattener can be used as first step in the conversion pipeline to reduce any PDF to a 
38// very simple representation (e.g. vector text on top of a background image). 
39//---------------------------------------------------------------------------------------
40
41func main(){
42    // Relative path to the folder containing the test files.
43    inputPath := "../../TestFiles/"
44    outputPath := "../../TestFiles/Output/"
45    inputFileName := "newsletter"
46    
47    // The first step in every application using PDFNet is to initialize the 
48    // library and set the path to common PDF resources. The library is usually 
49    // initialized only once, but calling Initialize() multiple times is also fine.
50    PDFNetInitialize(PDFTronLicense.Key)
51    
52    //--------------------------------------------------------------------------------
53    // Example 1) Simple optimization of a pdf with default settings.
54    
55    doc := NewPDFDoc(inputPath + inputFileName + ".pdf")
56    doc.InitSecurityHandler()
57    OptimizerOptimize(doc)
58    
59    doc.Save(outputPath + inputFileName + "_opt1.pdf", uint(SDFDocE_linearized))
60    doc.Close()
61    
62    //--------------------------------------------------------------------------------
63    // Example 2) Reduce image quality and use jpeg compression for
64    // non monochrome images.    
65    doc = NewPDFDoc(inputPath + inputFileName + ".pdf")
66    doc.InitSecurityHandler()
67    imageSettings := NewImageSettings()
68    
69    // low quality jpeg compression
70    imageSettings.SetCompressionMode(ImageSettingsE_jpeg)
71    imageSettings.SetQuality(1)
72    
73    // Set the output dpi to be standard screen resolution
74    imageSettings.SetImageDPI(144,96)
75    
76    // this option will recompress images not compressed with
77    // jpeg compression and use the result if the new image
78    // is smaller.
79    imageSettings.ForceRecompression(true)
80    
81    // this option is not commonly used since it can 
82    // potentially lead to larger files.  It should be enabled
83    // only if the output compression specified should be applied
84    // to every image of a given type regardless of the output image size
85    //imageSettings.ForceChanges(true)
86
87    optSettings := NewOptimizerSettings()
88    optSettings.SetColorImageSettings(imageSettings)
89    optSettings.SetGrayscaleImageSettings(imageSettings)
90
91    // use the same settings for both color and grayscale images
92    OptimizerOptimize(doc, optSettings)
93    
94    doc.Save(outputPath + inputFileName + "_opt2.pdf", uint(SDFDocE_linearized))
95    doc.Close()
96    
97    //--------------------------------------------------------------------------------
98    // Example 3) Use monochrome image settings and default settings
99    // for color and grayscale images. 
100    
101    doc = NewPDFDoc(inputPath + inputFileName + ".pdf")
102    doc.InitSecurityHandler()
103
104    monoImageSettings := NewMonoImageSettings()
105    
106    monoImageSettings.SetCompressionMode(MonoImageSettingsE_jbig2)
107    monoImageSettings.ForceRecompression(true)
108
109    optSettings = NewOptimizerSettings()
110    optSettings.SetMonoImageSettings(monoImageSettings)
111    
112    OptimizerOptimize(doc, optSettings)
113    doc.Save(outputPath + inputFileName + "_opt3.pdf", uint(SDFDocE_linearized))
114    doc.Close()
115	
116    // ----------------------------------------------------------------------
117    // Example 4) Use Flattener to simplify content in this document
118    // using default settings
119    
120    doc = NewPDFDoc(inputPath + "TigerText.pdf")
121    doc.InitSecurityHandler()
122    
123    fl := NewFlattener()
124    // The following lines can increase the resolution of background
125    // images.
126    //fl.SetDPI(300)
127    //fl.SetMaximumImagePixels(5000000)
128
129    // This line can be used to output Flate compressed background
130    // images rather than DCTDecode compressed images which is the default
131    //fl.SetPreferJPG(false)
132
133    // In order to adjust thresholds for when text is Flattened
134    // the following function can be used.
135    //fl.SetThreshold(FlattenerE_threshold_keep_most)
136
137    // We use e_fast option here since it is usually preferable
138    // to avoid Flattening simple pages in terms of size and 
139    // rendering speed. If the desire is to simplify the 
140    // document for processing such that it contains only text and
141    // a background image e_simple should be used instead.
142    fl.Process(doc, FlattenerE_fast)
143    doc.Save(outputPath + "TigerText_flatten.pdf", uint(SDFDocE_linearized))
144    doc.Close()
145
146    // ----------------------------------------------------------------------
147    // Example 5) Optimize a PDF for viewing using SaveViewerOptimized.
148    
149    doc = NewPDFDoc(inputPath + inputFileName + ".pdf")
150    doc.InitSecurityHandler()
151    
152    opts := NewViewerOptimizedOptions()
153
154    // set the maximum dimension (width or height) that thumbnails will have.
155    opts.SetThumbnailSize(1500)
156
157    // set thumbnail rendering threshold. A number from 0 (include all thumbnails) to 100 (include only the first thumbnail) 
158    // representing the complexity at which SaveViewerOptimized would include the thumbnail. 
159    // By default it only produces thumbnails on the first and complex pages. 
160    // The following line will produce thumbnails on every page.
161    // opts.SetThumbnailRenderingThreshold(0) 
162
163    doc.SaveViewerOptimized(outputPath + inputFileName + "_SaveViewerOptimized.pdf", opts)
164    doc.Close()
165    PDFNetTerminate()
166}
1//---------------------------------------------------------------------------------------
2// Copyright (c) 2001-2024 by Apryse Software Inc. All Rights Reserved.
3// Consult legal.txt regarding legal and license information.
4//---------------------------------------------------------------------------------------
5
6#include <PDF/PDFNet.h>
7#include <PDF/Optimizer.h>
8#include <iostream>
9#include <PDF/Flattener.h>
10#include "../../LicenseKey/CPP/LicenseKey.h"
11
12using namespace std;
13using namespace pdftron;
14using namespace Common;
15using namespace SDF;
16using namespace PDF;
17
18//---------------------------------------------------------------------------------------
19// The following sample illustrates how to reduce PDF file size using 'pdftron.PDF.Optimizer'.
20// The sample also shows how to simplify and optimize PDF documents for viewing on mobile devices 
21// and on the Web using 'pdftron.PDF.Flattener'.
22//
23// @note Both 'Optimizer' and 'Flattener' are separately licensable add-on options to the core PDFNet license.
24//
25// ----
26//
27// 'pdftron.PDF.Optimizer' can be used to optimize PDF documents by reducing the file size, removing 
28// redundant information, and compressing data streams using the latest in image compression technology. 
29//
30// PDF Optimizer can compress and shrink PDF file size with the following operations:
31// - Remove duplicated fonts, images, ICC profiles, and any other data stream. 
32// - Optionally convert high-quality or print-ready PDF files to small, efficient and web-ready PDF. 
33// - Optionally down-sample large images to a given resolution. 
34// - Optionally compress or recompress PDF images using JBIG2 and JPEG2000 compression formats. 
35// - Compress uncompressed streams and remove unused PDF objects. 
36//
37// ----
38//
39// 'pdftron.PDF.Flattener' can be used to speed-up PDF rendering on mobile devices and on the Web by 
40// simplifying page content (e.g. flattening complex graphics into images) while maintaining vector text 
41// whenever possible.
42//
43// Flattener can also be used to simplify process of writing custom converters from PDF to other formats. 
44// In this case, Flattener can be used as first step in the conversion pipeline to reduce any PDF to a 
45// very simple representation (e.g. vector text on top of a background image).
46//---------------------------------------------------------------------------------------
47
48int main(int argc, char * argv[])
49{
50	int ret = 0;
51	std::string input_path = "../../TestFiles/";
52	std::string output_path = "../../TestFiles/Output/";
53	std::string input_filename = "newsletter";	
54
55	// The first step in every application using PDFNet is to initialize the 
56	// library and set the path to common PDF resources. The library is usually 
57	// initialized only once, but calling Initialize() multiple times is also fine.
58	PDFNet::Initialize(LicenseKey);
59
60	//--------------------------------------------------------------------------------
61	// Example 1) Simple optimization of a pdf with default settings. 
62	//
63	try
64	{
65		pdftron::PDF::PDFDoc doc(input_path + input_filename + ".pdf");
66		doc.InitSecurityHandler();
67
68		Optimizer::Optimize(doc);
69
70		doc.Save(output_path + input_filename + "_opt1.pdf", SDFDoc::e_linearized, NULL);
71	}
72	catch (Common::Exception& e)
73	{
74		std::cout << e << endl;
75		ret = 1;		
76	}
77	catch (...)
78	{
79		cout << "Unknown Exception" << endl;
80		ret = 1;
81	}
82
83	//--------------------------------------------------------------------------------
84	// Example 2) Reduce image quality and use jpeg compression for
85	// non monochrome images.
86	try
87	{
88		PDFDoc doc(input_path + input_filename + ".pdf");
89		doc.InitSecurityHandler();
90
91		Optimizer::ImageSettings image_settings;
92
93		// low quality jpeg compression
94		image_settings.SetCompressionMode(Optimizer::ImageSettings::e_jpeg);
95		image_settings.SetQuality(1);
96
97		// Set the output dpi to be standard screen resolution
98		image_settings.SetImageDPI(144,96);
99
100		// this option will recompress images not compressed with
101		// jpeg compression and use the result if the new image
102		// is smaller.
103		image_settings.ForceRecompression(true);
104
105		// this option is not commonly used since it can 
106		// potentially lead to larger files.  It should be enabled
107		// only if the output compression specified should be applied
108		// to every image of a given type regardless of the output image size
109		//image_settings.ForceChanges(true);
110
111
112		Optimizer::OptimizerSettings opt_settings;
113		opt_settings.SetColorImageSettings(image_settings);
114		opt_settings.SetGrayscaleImageSettings(image_settings);
115
116		// use the same settings for both color and grayscale images
117		Optimizer::Optimize(doc, opt_settings);
118
119		doc.Save(output_path + input_filename + "_opt2.pdf", SDFDoc::e_linearized, NULL);
120	}
121	catch (Common::Exception& e)
122	{
123		std::cout << e << endl;
124		ret = 1;		
125	}
126	catch (...)
127	{
128		cout << "Unknown Exception" << endl;
129		ret = 1;
130	}
131
132	//--------------------------------------------------------------------------------
133	// Example 3) Use monochrome image settings and default settings
134	// for color and grayscale images. 
135	try
136	{
137		PDFDoc doc(input_path + input_filename + ".pdf");
138		doc.InitSecurityHandler();
139
140		Optimizer::MonoImageSettings mono_image_settings;
141
142		mono_image_settings.SetCompressionMode(Optimizer::MonoImageSettings::e_jbig2);
143		mono_image_settings.ForceRecompression(true);
144
145		Optimizer::OptimizerSettings opt_settings;
146		opt_settings.SetMonoImageSettings(mono_image_settings);
147
148		Optimizer::Optimize(doc, opt_settings);
149
150		doc.Save(output_path + input_filename + "_opt3.pdf", SDFDoc::e_linearized, NULL);
151	}
152	catch (Common::Exception& e)
153	{
154		std::cout << e << endl;
155		ret = 1;		
156	}
157	catch (...)
158	{
159		cout << "Unknown Exception" << endl;
160		ret = 1;
161	}
162
163	// ----------------------------------------------------------------------
164	// Example 4) Use Flattener to simplify content in this document
165	// using default settings
166	try
167	{
168		PDFDoc doc(input_path + "TigerText.pdf");
169		doc.InitSecurityHandler();
170
171		Flattener fl;
172
173		// The following lines can increase the resolution of background
174		// images.
175		//fl.SetDPI(300);
176		//fl.SetMaximumImagePixels(5000000);
177
178		// This line can be used to output Flate compressed background
179		// images rather than DCTDecode compressed images which is the default
180		//fl.SetPreferJPG(false);
181
182		// In order to adjust thresholds for when text is Flattened
183		// the following function can be used.
184		//fl.SetThreshold(Flattener::e_keep_most);
185
186		// We use e_fast option here since it is usually preferable
187		// to avoid Flattening simple pages in terms of size and 
188		// rendering speed. If the desire is to simplify the 
189		// document for processing such that it contains only text and
190		// a background image e_simple should be used instead.
191		fl.Process(doc,Flattener::e_fast);
192
193		doc.Save(output_path + "TigerText_flatten.pdf", SDFDoc::e_linearized, NULL);
194
195	}
196	catch (Common::Exception& e)
197	{
198		std::cout << e << endl;
199		ret = 1;		
200	}
201	catch (...)
202	{
203		cout << "Unknown Exception" << endl;
204		ret = 1;
205	}
206
207	//--------------------------------------------------------------------------------
208	// Example 5) Optimize a PDF for viewing using SaveViewerOptimized.
209	try
210	{
211		PDFDoc doc(input_path + input_filename + ".pdf");
212		doc.InitSecurityHandler();
213
214		ViewerOptimizedOptions opts;
215
216		// set the maximum dimension (width or height) that thumbnails will have.
217		opts.SetThumbnailSize(1500);
218
219		// set thumbnail rendering threshold. A number from 0 (include all thumbnails) to 100 (include only the first thumbnail) 
220		// representing the complexity at which SaveViewerOptimized would include the thumbnail. 
221		// By default it only produces thumbnails on the first and complex pages. 
222		// The following line will produce thumbnails on every page.
223		// opts.SetThumbnailRenderingThreshold(0); 
224	
225		doc.SaveViewerOptimized(output_path + input_filename + "_SaveViewerOptimized.pdf", opts);
226	}
227	catch (Common::Exception& e)
228	{
229		std::cout << e << endl;
230		ret = 1;
231	}
232	catch (...)
233	{
234		cout << "Unknown Exception" << endl;
235		ret = 1;
236	}
237
238	PDFNet::Terminate();
239	return ret;
240}
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}
1//---------------------------------------------------------------------------------------
2// Copyright (c) 2001-2024 by Apryse Software Inc. All Rights Reserved.
3// Consult legal.txt regarding legal and license information.
4//---------------------------------------------------------------------------------------
5
6//---------------------------------------------------------------------------------------
7// The following sample illustrates how to reduce PDF file size using 'pdftron.PDF.Optimizer'.
8// The sample also shows how to simplify and optimize PDF documents for viewing on mobile devices 
9// and on the Web using 'pdftron.PDF.Flattener'.
10//
11// @note Both 'Optimizer' and 'Flattener' are separately licensable add-on options to the core PDFNet license.
12//
13// ----
14//
15// 'pdftron.PDF.Optimizer' can be used to optimize PDF documents by reducing the file size, removing 
16// redundant information, and compressing data streams using the latest in image compression technology. 
17//
18// PDF Optimizer can compress and shrink PDF file size with the following operations:
19// - Remove duplicated fonts, images, ICC profiles, and any other data stream. 
20// - Optionally convert high-quality or print-ready PDF files to small, efficient and web-ready PDF. 
21// - Optionally down-sample large images to a given resolution. 
22// - Optionally compress or recompress PDF images using JBIG2 and JPEG2000 compression formats. 
23// - Compress uncompressed streams and remove unused PDF objects. 
24//
25// ----
26//
27// 'pdftron.PDF.Flattener' can be used to speed-up PDF rendering on mobile devices and on the Web by 
28// simplifying page content (e.g. flattening complex graphics into images) while maintaining vector text 
29// whenever possible.
30//
31// Flattener can also be used to simplify process of writing custom converters from PDF to other formats. 
32// In this case, Flattener can be used as first step in the conversion pipeline to reduce any PDF to a 
33// very simple representation (e.g. vector text on top of a background image).
34//---------------------------------------------------------------------------------------
35
36const { PDFNet } = require('@pdftron/pdfnet-node');
37const PDFTronLicense = require('../LicenseKey/LicenseKey');
38
39((exports) => {
40  'use strict';
41
42  exports.runOptimizerTest = () => {
43    const main = async () => {
44      const inputPath = '../TestFiles/';
45      const outputPath = inputPath + 'Output/';
46      const inputFilename = 'newsletter';
47
48      // The first step in every application using PDFNet is to initialize the 
49      // library and set the path to common PDF resources. The library is usually 
50      // initialized only once, but calling Initialize() multiple times is also fine.
51
52      //--------------------------------------------------------------------------------
53      // Example 1) Simple optimization of a pdf with default settings. 
54      //
55      try {
56        const doc = await PDFNet.PDFDoc.createFromFilePath(inputPath + inputFilename + '.pdf');
57        await doc.initSecurityHandler();
58        await PDFNet.Optimizer.optimize(doc);
59        doc.save(outputPath + inputFilename + '_opt1.pdf', PDFNet.SDFDoc.SaveOptions.e_linearized);
60      }
61      catch (err) {
62        console.log(err);
63      }
64
65      //--------------------------------------------------------------------------------
66      // Example 2) Reduce image quality and use jpeg compression for
67      // non monochrome images.
68      try {
69        const doc = await PDFNet.PDFDoc.createFromFilePath(inputPath + inputFilename + '.pdf');
70        await doc.initSecurityHandler();
71        const image_settings = new PDFNet.Optimizer.ImageSettings();
72
73        // low quality jpeg compression
74        image_settings.setCompressionMode(PDFNet.Optimizer.ImageSettings.CompressionMode.e_jpeg);
75        image_settings.setQuality(1);
76
77        // Set the output dpi to be standard screen resolution
78        image_settings.setImageDPI(144, 96);
79
80        // this option will recompress images not compressed with
81        // jpeg compression and use the result if the new image
82        // is smaller.
83        image_settings.forceRecompression(true);
84
85        // this option is not commonly used since it can 
86        // potentially lead to larger files.  It should be enabled
87        // only if the output compression specified should be applied
88        // to every image of a given type regardless of the output image size
89        //image_settings.forceChanges(true);
90
91        const opt_settings = new PDFNet.Optimizer.OptimizerSettings();
92        opt_settings.setColorImageSettings(image_settings);
93        opt_settings.setGrayscaleImageSettings(image_settings);
94
95        // use the same settings for both color and grayscale images
96        await PDFNet.Optimizer.optimize(doc, opt_settings);
97
98        doc.save(outputPath + inputFilename + '_opt2.pdf', PDFNet.SDFDoc.SaveOptions.e_linearized);
99      }
100      catch (err) {
101        console.log(err);
102      }
103
104      //--------------------------------------------------------------------------------
105      // Example 3) Use monochrome image settings and default settings
106      // for color and grayscale images. 
107      try {
108        const doc = await PDFNet.PDFDoc.createFromFilePath(inputPath + inputFilename + '.pdf');
109        await doc.initSecurityHandler();
110
111        const mono_image_settings = new PDFNet.Optimizer.MonoImageSettings();
112
113        mono_image_settings.setCompressionMode(PDFNet.Optimizer.MonoImageSettings.CompressionMode.e_jbig2);
114        mono_image_settings.forceRecompression(true);
115
116        const opt_settings = new PDFNet.Optimizer.OptimizerSettings();
117
118        opt_settings.setMonoImageSettings(mono_image_settings);
119
120        await PDFNet.Optimizer.optimize(doc, opt_settings);
121        doc.save(outputPath + inputFilename + '_opt3.pdf', PDFNet.SDFDoc.SaveOptions.e_linearized);
122      }
123      catch (err) {
124        console.log(err);
125      }
126
127      // ----------------------------------------------------------------------
128      // Example 4) Use Flattener to simplify content in this document
129      // using default settings
130      try {
131        const doc = await PDFNet.PDFDoc.createFromFilePath(inputPath + 'TigerText.pdf');
132        await doc.initSecurityHandler();
133
134        const fl = await PDFNet.Flattener.create();
135
136        // The following lines can increase the resolution of background
137        // images.
138        //fl.setDPI(300);
139        //fl.setMaximumImagePixels(5000000);
140
141        // This line can be used to output Flate compressed background
142        // images rather than DCTDecode compressed images which is the default
143        //fl.setPreferJPG(false);
144
145        // In order to adjust thresholds for when text is Flattened
146        // the following function can be used.
147        //fl.setThreshold(PDFNet.Flattener.Threshold.e_keep_most);
148
149        // We use e_fast option here since it is usually preferable
150        // to avoid Flattening simple pages in terms of size and 
151        // rendering speed. If the desire is to simplify the 
152        // document for processing such that it contains only text and
153        // a background image e_simple should be used instead.
154        await fl.process(doc, PDFNet.Flattener.Mode.e_fast);
155
156        doc.save(outputPath + 'TigerText_flatten.pdf', PDFNet.SDFDoc.SaveOptions.e_linearized);
157      }
158      catch (err) {
159        console.log(err);
160      }
161
162      //--------------------------------------------------------------------------------
163      // Example 5) Optimize a PDF for viewing using SaveViewerOptimized.
164      try {
165        const doc = await PDFNet.PDFDoc.createFromFilePath(inputPath + inputFilename + '.pdf');
166        doc.initSecurityHandler();
167
168        const opts = new PDFNet.PDFDoc.ViewerOptimizedOptions();
169
170        // set the maximum dimension (width or height) that thumbnails will have.
171        opts.setThumbnailSize(1500);
172
173        // set thumbnail rendering threshold. A number from 0 (include all thumbnails) to 100 (include only the first thumbnail) 
174        // representing the complexity at which SaveViewerOptimized would include the thumbnail. 
175        // By default it only produces thumbnails on the first and complex pages. 
176        // The following line will produce thumbnails on every page.
177        // opts.setThumbnailRenderingThreshold(0); 
178
179        await doc.saveViewerOptimized(outputPath + inputFilename + '_SaveViewerOptimized.pdf', opts);
180      }
181      catch (err) {
182        console.log(err);
183      }
184    };
185    PDFNet.runWithCleanup(main, PDFTronLicense.Key).catch(function (error) {
186      console.log('Error: ' + JSON.stringify(error));
187    }).then(function () { return PDFNet.shutdown(); });
188  };
189  exports.runOptimizerTest();
190})(exports);
191// eslint-disable-next-line spaced-comment
192//# sourceURL=OptimizerTest.js
1<?php
2//---------------------------------------------------------------------------------------
3// Copyright (c) 2001-2023 by Apryse Software Inc. All Rights Reserved.
4// Consult LICENSE.txt regarding license information.
5//---------------------------------------------------------------------------------------
6if(file_exists("../../../PDFNetC/Lib/PDFNetPHP.php"))
7include("../../../PDFNetC/Lib/PDFNetPHP.php");
8include("../../LicenseKey/PHP/LicenseKey.php");
9
10// Relative path to the folder containing the test files.
11$input_path = getcwd()."/../../TestFiles/";
12$output_path = $input_path."Output/";
13$input_filename = "newsletter";
14
15//---------------------------------------------------------------------------------------
16// The following sample illustrates how to reduce PDF file size using 'pdftron.PDF.Optimizer'.
17// The sample also shows how to simplify and optimize PDF documents for viewing on mobile devices 
18// and on the Web using 'pdftron.PDF.Flattener'.
19//
20// @note Both 'Optimizer' and 'Flattener' are separately licensable add-on options to the core PDFNet license.
21//
22// ----
23//
24// 'pdftron.PDF.Optimizer' can be used to optimize PDF documents by reducing the file size, removing 
25// redundant information, and compressing data streams using the latest in image compression technology. 
26//
27// PDF Optimizer can compress and shrink PDF file size with the following operations:
28// - Remove duplicated fonts, images, ICC profiles, and any other data stream. 
29// - Optionally convert high-quality or print-ready PDF files to small, efficient and web-ready PDF. 
30// - Optionally down-sample large images to a given resolution. 
31// - Optionally compress or recompress PDF images using JBIG2 and JPEG2000 compression formats. 
32// - Compress uncompressed streams and remove unused PDF objects.
33// ----
34//
35// 'pdftron.PDF.Flattener' can be used to speed-up PDF rendering on mobile devices and on the Web by 
36// simplifying page content (e.g. flattening complex graphics into images) while maintaining vector text 
37// whenever possible.
38//
39// Flattener can also be used to simplify process of writing custom converters from PDF to other formats. 
40// In this case, Flattener can be used as first step in the conversion pipeline to reduce any PDF to a 
41// very simple representation (e.g. vector text on top of a background image). 
42//---------------------------------------------------------------------------------------
43
44	// The first step in every application using PDFNet is to initialize the 
45	// library and set the path to common PDF resources. The library is usually 
46	// initialized only once, but calling Initialize() multiple times is also fine.
47	PDFNet::Initialize($LicenseKey);
48	PDFNet::GetSystemFontList();    // Wait for fonts to be loaded if they haven't already. This is done because PHP can run into errors when shutting down if font loading is still in progress.
49
50	//--------------------------------------------------------------------------------
51	// Example 1) Simple optimization of a pdf with default settings. 
52	//
53
54	$doc = new PDFDoc($input_path.$input_filename.".pdf");
55	$doc->InitSecurityHandler();
56
57	Optimizer::Optimize($doc);
58
59	$doc->Save($output_path.$input_filename."_opt1.pdf", SDFDoc::e_linearized);
60	$doc->Close();
61
62	//--------------------------------------------------------------------------------
63	// Example 2) Reduce image quality and use jpeg compression for
64	// non monochrome images.
65	
66	$doc = new PDFDoc($input_path.$input_filename.".pdf");
67	$doc->InitSecurityHandler();
68
69	$image_settings = new ImageSettings();
70
71	// low quality jpeg compression
72	$image_settings->SetCompressionMode(ImageSettings::e_jpeg);
73	$image_settings->SetQuality(1);
74
75	// Set the output dpi to be standard screen resolution
76	$image_settings->SetImageDPI(144,96);
77
78	// this option will recompress images not compressed with
79	// jpeg compression and use the result if the new image
80	// is smaller.
81	$image_settings->ForceRecompression(true);
82
83	// this option is not commonly used since it can 
84	// potentially lead to larger files.  It should be enabled
85	// only if the output compression specified should be applied
86	// to every image of a given type regardless of the output image size
87	//$image_settings->ForceChanges(true);
88
89	$opt_settings = new OptimizerSettings();
90	$opt_settings->SetColorImageSettings($image_settings);
91	$opt_settings->SetGrayScaleImageSettings($image_settings);
92
93	// use the same settings for both color and grayscale images
94	Optimizer::Optimize($doc, $opt_settings);
95
96	$doc->Save($output_path.$input_filename."_opt2.pdf", SDFDoc::e_linearized);
97	$doc->Close();
98
99	//--------------------------------------------------------------------------------
100	// Example 3) Use monochrome image settings and default settings
101	// for color and grayscale images. 
102	
103	$doc = new PDFDoc($input_path.$input_filename.".pdf");
104	$doc->InitSecurityHandler();
105
106	$mono_image_settings = new MonoImageSettings();
107
108	$mono_image_settings->SetCompressionMode(MonoImageSettings::e_jbig2);
109	$mono_image_settings->ForceRecompression(true);
110
111	$opt_settings = new OptimizerSettings();
112	$opt_settings->SetMonoImageSettings($mono_image_settings);
113
114	Optimizer::Optimize($doc, $opt_settings);
115
116	$doc->Save($output_path.$input_filename."_opt3.pdf", SDFDoc::e_linearized);
117	$doc->Close();
118	
119	// ----------------------------------------------------------------------
120	// Example 4) Use Flattener to simplify content in this document
121	// using default settings
122	
123	$doc = new PDFDoc($input_path."TigerText.pdf");
124	$doc->InitSecurityHandler();
125	
126	$fl = new Flattener();
127	// The following lines can increase the resolution of background
128	// images.
129	//$fl->SetDPI(300);
130	//$fl->SetMaximumImagePixels(5000000);
131
132	// This line can be used to output Flate compressed background
133	// images rather than DCTDecode compressed images which is the default
134	//$fl->SetPreferJPG(false);
135
136	// In order to adjust thresholds for when text is Flattened
137	// the following function can be used.
138	//$fl->SetThreshold(Flattener::e_threshold_keep_most);
139
140	// We use e_fast option here since it is usually preferable
141	// to avoid Flattening simple pages in terms of size and 
142	// rendering speed. If the desire is to simplify the 
143	// document for processing such that it contains only text and
144	// a background image e_simple should be used instead.
145	$fl->Process($doc, Flattener::e_fast);
146	$doc->Save($output_path."TigerText_flatten.pdf", SDFDoc::e_linearized);
147	$doc->Close();
148
149	// ----------------------------------------------------------------------
150	// Example 5) Optimize a PDF for viewing using SaveViewerOptimized.
151	
152	$doc = new PDFDoc($input_path.$input_filename.".pdf");
153	$doc->InitSecurityHandler();
154	
155	$opts = new ViewerOptimizedOptions();
156
157	// set the maximum dimension (width or height) that thumbnails will have.
158        $opts->SetThumbnailSize(1500);
159
160	// set thumbnail rendering threshold. A number from 0 (include all thumbnails) to 100 (include only the first thumbnail) 
161        // representing the complexity at which SaveViewerOptimized would include the thumbnail. 
162        // By default it only produces thumbnails on the first and complex pages. 
163        // The following line will produce thumbnails on every page.
164        // opts->SetThumbnailRenderingThreshold(0); 
165
166        $doc->SaveViewerOptimized($output_path.$input_filename."_SaveViewerOptimized.pdf", $opts);
167	$doc->Close();
168	PDFNet::Terminate();
169?>
1#---------------------------------------------------------------------------------------
2# Copyright (c) 2001-2023 by Apryse Software Inc. All Rights Reserved.
3# Consult LICENSE.txt regarding license information.
4#---------------------------------------------------------------------------------------
5
6require '../../../PDFNetC/Lib/PDFNetRuby'
7include PDFNetRuby
8require '../../LicenseKey/RUBY/LicenseKey'
9
10$stdout.sync = true
11
12#---------------------------------------------------------------------------------------
13# The following sample illustrates how to reduce PDF file size using 'pdftron.PDF.Optimizer'.
14# The sample also shows how to simplify and optimize PDF documents for viewing on mobile devices 
15# and on the Web using 'pdftron.PDF.Flattener'.
16#
17# @note Both 'Optimizer' and 'Flattener' are separately licensable add-on options to the core PDFNet license.
18#
19# ----
20#
21# 'pdftron.PDF.Optimizer' can be used to optimize PDF documents by reducing the file size, removing 
22# redundant information, and compressing data streams using the latest in image compression technology. 
23#
24# PDF Optimizer can compress and shrink PDF file size with the following operations:
25# - Remove duplicated fonts, images, ICC profiles, and any other data stream. 
26# - Optionally convert high-quality or print-ready PDF files to small, efficient and web-ready PDF. 
27# - Optionally down-sample large images to a given resolution. 
28# - Optionally compress or recompress PDF images using JBIG2 and JPEG2000 compression formats. 
29# - Compress uncompressed streams and remove unused PDF objects. 
30#
31# 'pdftron.PDF.Flattener' can be used to speed-up PDF rendering on mobile devices and on the Web by 
32# simplifying page content (e.g. flattening complex graphics into images) while maintaining vector text 
33# whenever possible.
34#
35# Flattener can also be used to simplify process of writing custom converters from PDF to other formats. 
36# In this case, Flattener can be used as first step in the conversion pipeline to reduce any PDF to a 
37# very simple representation (e.g. vector text on top of a background image).
38#---------------------------------------------------------------------------------------
39
40	# Relative path to the folder containing the test files.
41	input_path = "../../TestFiles/"
42	output_path = "../../TestFiles/Output/"
43	input_filename = "newsletter"
44	
45	# The first step in every application using PDFNet is to initialize the 
46	# library and set the path to common PDF resources. The library is usually 
47	# initialized only once, but calling Initialize multiple times is also fine.
48	PDFNet.Initialize(PDFTronLicense.Key)
49	
50	#--------------------------------------------------------------------------------
51	# Example 1) Simple optimization of a pdf with default settings.
52	
53	doc = PDFDoc.new(input_path + input_filename + ".pdf")
54	doc.InitSecurityHandler
55	Optimizer.Optimize(doc)
56	
57	doc.Save(output_path + input_filename + "_opt1.pdf", SDFDoc::E_linearized)
58	doc.Close
59	
60	#--------------------------------------------------------------------------------
61	# Example 2) Reduce image quality and use jpeg compression for
62	# non monochrome images.	
63	doc = PDFDoc.new(input_path + input_filename + ".pdf")
64	doc.InitSecurityHandler
65	image_settings = ImageSettings.new
66	
67	# low quality jpeg compression
68	image_settings.SetCompressionMode(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	# this option is not commonly used since it can 
80	# potentially lead to larger files.  It should be enabled
81	# only if the output compression specified should be applied
82	# to every image of a given type regardless of the output image size
83	#image_settings.ForceChanges(True)
84
85	opt_settings = OptimizerSettings.new
86	opt_settings.SetColorImageSettings(image_settings)
87	opt_settings.SetGrayscaleImageSettings(image_settings)
88	
89	# use the same settings for both color and grayscale images
90	Optimizer.Optimize(doc, opt_settings)
91	
92	doc.Save(output_path + input_filename + "_opt2.pdf", SDFDoc::E_linearized)
93	doc.Close
94	
95	#--------------------------------------------------------------------------------
96	# Example 3) Use monochrome image settings and default settings
97	# for color and grayscale images. 
98	
99	doc = PDFDoc.new(input_path + input_filename + ".pdf")
100	doc.InitSecurityHandler
101
102	mono_image_settings = MonoImageSettings.new
103	
104	mono_image_settings.SetCompressionMode(MonoImageSettings::E_jbig2)
105	mono_image_settings.ForceRecompression(true)
106
107	opt_settings = OptimizerSettings.new
108	opt_settings.SetMonoImageSettings(mono_image_settings)
109	
110	Optimizer.Optimize(doc, opt_settings)
111	doc.Save(output_path + input_filename + "_opt3.pdf", SDFDoc::E_linearized)
112	doc.Close
113	
114	#----------------------------------------------------------------------
115	# Example 4) Use Flattener to simplify content in this document
116	# using default settings
117	
118	doc = PDFDoc.new(input_path + "TigerText.pdf")
119	doc.InitSecurityHandler
120	
121	fl = Flattener.new
122	
123	# The following lines can increase the resolution of background
124	# images.
125	#fl.SetDPI(300)
126	#fl.SetMaximumImagePixels(5000000)
127
128	# This line can be used to output Flate compressed background
129	# images rather than DCTDecode compressed images which is the default
130	#fl.SetPreferJPG(false)
131
132	# In order to adjust thresholds for when text is Flattened
133	# the following function can be used.
134	#fl.SetThreshold(Flattener::E_threshold_keep_most)
135
136	# We use e_fast option here since it is usually preferable
137	# to avoid Flattening simple pages in terms of size and 
138	# rendering speed. If the desire is to simplify the 
139	# document for processing such that it contains only text and
140	# a background image e_simple should be used instead.
141	fl.Process(doc, Flattener::E_fast)
142	doc.Save(output_path + "TigerText_flatten.pdf", SDFDoc::E_linearized)
143	doc.Close
144
145
146	# ----------------------------------------------------------------------
147	# Example 5) Optimize a PDF for viewing using SaveViewerOptimized.
148
149	doc = PDFDoc.new(input_path + input_filename + ".pdf")
150	doc.InitSecurityHandler
151
152	opts = ViewerOptimizedOptions.new
153
154	# set the maximum dimension (width or height) that thumbnails will have.
155	opts.SetThumbnailSize(1500)
156
157	# set thumbnail rendering threshold. A number from 0 (include all thumbnails) to 100 (include only the first thumbnail) 
158	# representing the complexity at which SaveViewerOptimized would include the thumbnail. 
159	# By default it only produces thumbnails on the first and complex pages. 
160	# The following line will produce thumbnails on every page.
161	# opts.SetThumbnailRenderingThreshold(0) 
162
163	doc.SaveViewerOptimized(output_path + input_filename + "_SaveViewerOptimized.pdf", opts)
164	doc.Close
165	PDFNet.Terminate
1#---------------------------------------------------------------------------------------
2# Copyright (c) 2001-2023 by Apryse Software Inc. All Rights Reserved.
3# Consult LICENSE.txt regarding license information.
4#---------------------------------------------------------------------------------------
5
6import site
7site.addsitedir("../../../PDFNetC/Lib")
8import sys
9from PDFNetPython import *
10
11sys.path.append("../../LicenseKey/PYTHON")
12from LicenseKey import *
13
14#---------------------------------------------------------------------------------------
15# The following sample illustrates how to reduce PDF file size using 'pdftron.PDF.Optimizer'.
16# The sample also shows how to simplify and optimize PDF documents for viewing on mobile devices 
17# and on the Web using 'pdftron.PDF.Flattener'.
18#
19# @note Both 'Optimizer' and 'Flattener' are separately licensable add-on options to the core PDFNet license.
20#
21# ----
22#
23# 'pdftron.PDF.Optimizer' can be used to optimize PDF documents by reducing the file size, removing 
24# redundant information, and compressing data streams using the latest in image compression technology. 
25#
26# PDF Optimizer can compress and shrink PDF file size with the following operations:
27# - Remove duplicated fonts, images, ICC profiles, and any other data stream. 
28# - Optionally convert high-quality or print-ready PDF files to small, efficient and web-ready PDF. 
29# - Optionally down-sample large images to a given resolution. 
30# - Optionally compress or recompress PDF images using JBIG2 and JPEG2000 compression formats. 
31# - Compress uncompressed streams and remove unused PDF objects.
32# ----
33#
34# 'pdftron.PDF.Flattener' can be used to speed-up PDF rendering on mobile devices and on the Web by 
35# simplifying page content (e.g. flattening complex graphics into images) while maintaining vector text 
36# whenever possible.
37#
38# Flattener can also be used to simplify process of writing custom converters from PDF to other formats. 
39# In this case, Flattener can be used as first step in the conversion pipeline to reduce any PDF to a 
40# very simple representation (e.g. vector text on top of a background image). 
41#---------------------------------------------------------------------------------------
42
43def main():
44    
45    # Relative path to the folder containing the test files.
46    input_path = "../../TestFiles/"
47    output_path = "../../TestFiles/Output/"
48    input_filename = "newsletter"
49    
50    # The first step in every application using PDFNet is to initialize the 
51    # library and set the path to common PDF resources. The library is usually 
52    # initialized only once, but calling Initialize() multiple times is also fine.
53    PDFNet.Initialize(LicenseKey)
54    
55    #--------------------------------------------------------------------------------
56    # Example 1) Simple optimization of a pdf with default settings.
57    
58    doc = PDFDoc(input_path + input_filename + ".pdf")
59    doc.InitSecurityHandler()
60    Optimizer.Optimize(doc)
61    
62    doc.Save(output_path + input_filename + "_opt1.pdf", SDFDoc.e_linearized)
63    doc.Close()
64    
65    #--------------------------------------------------------------------------------
66    # Example 2) Reduce image quality and use jpeg compression for
67    # non monochrome images.    
68    doc = PDFDoc(input_path + input_filename + ".pdf")
69    doc.InitSecurityHandler()
70    image_settings = ImageSettings()
71    
72    # low quality jpeg compression
73    image_settings.SetCompressionMode(ImageSettings.e_jpeg)
74    image_settings.SetQuality(1)
75    
76    # Set the output dpi to be standard screen resolution
77    image_settings.SetImageDPI(144,96)
78    
79    # this option will recompress images not compressed with
80    # jpeg compression and use the result if the new image
81    # is smaller.
82    image_settings.ForceRecompression(True)
83    
84    # this option is not commonly used since it can 
85    # potentially lead to larger files.  It should be enabled
86    # only if the output compression specified should be applied
87    # to every image of a given type regardless of the output image size
88    #image_settings.ForceChanges(True)
89
90    opt_settings = OptimizerSettings()
91    opt_settings.SetColorImageSettings(image_settings)
92    opt_settings.SetGrayscaleImageSettings(image_settings)
93
94    # use the same settings for both color and grayscale images
95    Optimizer.Optimize(doc, opt_settings)
96    
97    doc.Save(output_path + input_filename + "_opt2.pdf", SDFDoc.e_linearized)
98    doc.Close()
99    
100    #--------------------------------------------------------------------------------
101    # Example 3) Use monochrome image settings and default settings
102    # for color and grayscale images. 
103    
104    doc = PDFDoc(input_path + input_filename + ".pdf")
105    doc.InitSecurityHandler()
106
107    mono_image_settings = MonoImageSettings()
108    
109    mono_image_settings.SetCompressionMode(MonoImageSettings.e_jbig2)
110    mono_image_settings.ForceRecompression(True)
111
112    opt_settings = OptimizerSettings()
113    opt_settings.SetMonoImageSettings(mono_image_settings)
114    
115    Optimizer.Optimize(doc, opt_settings)
116    doc.Save(output_path + input_filename + "_opt3.pdf", SDFDoc.e_linearized)
117    doc.Close()
118	
119    # ----------------------------------------------------------------------
120    # Example 4) Use Flattener to simplify content in this document
121    # using default settings
122    
123    doc = PDFDoc(input_path + "TigerText.pdf")
124    doc.InitSecurityHandler()
125    
126    fl = Flattener()
127    # The following lines can increase the resolution of background
128    # images.
129    #fl.SetDPI(300)
130    #fl.SetMaximumImagePixels(5000000)
131
132    # This line can be used to output Flate compressed background
133    # images rather than DCTDecode compressed images which is the default
134    #fl.SetPreferJPG(false)
135
136    # In order to adjust thresholds for when text is Flattened
137    # the following function can be used.
138    #fl.SetThreshold(Flattener.e_threshold_keep_most)
139
140    # We use e_fast option here since it is usually preferable
141    # to avoid Flattening simple pages in terms of size and 
142    # rendering speed. If the desire is to simplify the 
143    # document for processing such that it contains only text and
144    # a background image e_simple should be used instead.
145    fl.Process(doc, Flattener.e_fast)
146    doc.Save(output_path + "TigerText_flatten.pdf", SDFDoc.e_linearized)
147    doc.Close()
148
149    # ----------------------------------------------------------------------
150    # Example 5) Optimize a PDF for viewing using SaveViewerOptimized.
151    
152    doc = PDFDoc(input_path + input_filename + ".pdf")
153    doc.InitSecurityHandler()
154    
155    opts = ViewerOptimizedOptions()
156
157    # set the maximum dimension (width or height) that thumbnails will have.
158    opts.SetThumbnailSize(1500)
159
160    # set thumbnail rendering threshold. A number from 0 (include all thumbnails) to 100 (include only the first thumbnail) 
161    # representing the complexity at which SaveViewerOptimized would include the thumbnail. 
162    # By default it only produces thumbnails on the first and complex pages. 
163    # The following line will produce thumbnails on every page.
164    # opts.SetThumbnailRenderingThreshold(0) 
165
166    doc.SaveViewerOptimized(output_path + input_filename + "_SaveViewerOptimized.pdf", opts)
167    doc.Close()
168    PDFNet.Terminate()
169    
170if __name__ == '__main__':
171    main()
1'
2' Copyright (c) 2001-2024 by Apryse Software Inc. All Rights Reserved.
3'
4
5Imports System
6
7Imports pdftron
8Imports pdftron.Common
9Imports pdftron.Filters
10Imports pdftron.SDF
11Imports pdftron.PDF
12
13Module OptimizerTestVB
14    Dim pdfNetLoader As PDFNetLoader
15    Sub New()
16        pdfNetLoader = pdftron.PDFNetLoader.Instance()
17    End Sub
18
19
20    '---------------------------------------------------------------------------------------
21    ' The following sample illustrates how to reduce PDF file size using 'pdftron.PDF.Optimizer'.
22    ' The sample also shows how to simplify and optimize PDF documents for viewing on mobile devices 
23    ' and on the Web using 'pdftron.PDF.Flattener'.
24    '
25    ' @note Both 'Optimizer' and 'Flattener' are separately licensable add-on options to the core PDFNet license.
26    '
27    ' ----
28    '
29    ' 'pdftron.PDF.Optimizer' can be used to optimize PDF documents by reducing the file size, removing 
30    ' redundant information, and compressing data streams using the latest in image compression technology. 
31    '
32    ' PDF Optimizer can compress and shrink PDF file size with the following operations:
33    ' - Remove duplicated fonts, images, ICC profiles, and any other data stream. 
34    ' - Optionally convert high-quality or print-ready PDF files to small, efficient and web-ready PDF. 
35    ' - Optionally down-sample large images to a given resolution. 
36    ' - Optionally compress or recompress PDF images using JBIG2 and JPEG2000 compression formats. 
37    ' - Compress uncompressed streams and remove unused PDF objects.
38    ' ----
39    '
40    ' 'pdftron.PDF.Flattener' can be used to speed-up PDF rendering on mobile devices and on the Web by 
41    ' simplifying page content (e.g. flattening complex graphics into images) while maintaining vector text 
42    ' whenever possible.
43    '
44    ' Flattener can also be used to simplify process of writing custom converters from PDF to other formats. 
45    ' In this case, Flattener can be used as first step in the conversion pipeline to reduce any PDF to a 
46    ' very simple representation (e.g. vector text on top of a background image).
47    '---------------------------------------------------------------------------------------
48    Sub Main()
49        PDFNet.Initialize(PDFTronLicense.Key)
50
51        Dim input_path As String = "../../../../TestFiles/"
52        Dim output_path As String = "../../../../TestFiles/Output/"
53        Dim input_filename As String = "newsletter"
54
55        '--------------------------------------------------------------------------------
56        ' Example 1) Simple optimization of a pdf with default settings. 
57        '
58        Try
59            Using doc As PDFDoc = New PDFDoc(input_path & input_filename & ".pdf")
60                doc.InitSecurityHandler()
61                Optimizer.Optimize(doc)
62                doc.Save(output_path & input_filename & "_opt1.pdf", SDFDoc.SaveOptions.e_linearized)
63            End Using
64        Catch e As PDFNetException
65            Console.WriteLine(e.Message)
66        End Try
67
68        '--------------------------------------------------------------------------------
69        ' Example 2) Reduce image quality and use jpeg compression for
70        ' non monochrome images.
71        Try
72            Using doc As PDFDoc = New PDFDoc(input_path & input_filename & ".pdf")
73                doc.InitSecurityHandler()
74
75                Dim image_settings As New Optimizer.ImageSettings
76
77                ' low quality jpeg compression
78                image_settings.SetCompressionMode(Optimizer.ImageSettings.CompressionMode.e_jpeg)
79                image_settings.SetQuality(1)
80
81                ' Set the output dpi to be standard screen resolution
82                image_settings.SetImageDPI(144, 96)
83
84                ' this option will recompress images not compressed with
85                ' jpeg compression and use the result if the new image
86                ' is smaller.
87                image_settings.ForceRecompression(True)
88
89                ' this option is not commonly used since it can 
90                ' potentially lead to larger files.  It should be enabled
91                ' only if the output compression specified should be applied
92                ' to every image of a given type regardless of the output image size
93                'image_settings.ForceChanges(true);
94
95                ' use the same settings for both color and grayscale images
96                Dim opt_settings As New Optimizer.OptimizerSettings
97                opt_settings.SetColorImageSettings(image_settings)
98                opt_settings.SetGrayscaleImageSettings(image_settings)
99
100                Optimizer.Optimize(doc, opt_settings)
101
102                doc.Save(output_path & input_filename & "_opt2.pdf", SDFDoc.SaveOptions.e_linearized)
103            End Using
104        Catch e As PDFNetException
105            Console.WriteLine(e.Message)
106        End Try
107
108        '--------------------------------------------------------------------------------
109        ' Example 3) Use monochrome image settings and default settings
110        ' for color and grayscale images. 
111        Try
112            Using doc As PDFDoc = New PDFDoc(input_path & input_filename & ".pdf")
113                doc.InitSecurityHandler()
114
115                Dim mono_image_settings As New Optimizer.MonoImageSettings
116
117                mono_image_settings.SetCompressionMode(Optimizer.MonoImageSettings.CompressionMode.e_jbig2)
118                mono_image_settings.ForceRecompression(True)
119
120                Dim opt_settings As New Optimizer.OptimizerSettings
121                opt_settings.SetMonoImageSettings(mono_image_settings)
122
123                Optimizer.Optimize(doc, opt_settings)
124
125                doc.Save(output_path & input_filename & "_opt3.pdf", SDFDoc.SaveOptions.e_linearized)
126            End Using
127        Catch e As PDFNetException
128            Console.WriteLine(e.Message)
129        End Try
130
131        '-------------------------------------------------------------------------------
132        ' Example 4) Use Flattener to simplify content in this document
133        ' using default settings
134        Try
135            Using doc As PDFDoc = New PDFDoc(input_path & "TigerText.pdf")
136                doc.InitSecurityHandler()
137
138                Dim fl As New Flattener
139
140                ' The following lines can increase the resolution of background
141                ' images.
142                'fl.SetDPI(300)
143                'fl.SetMaximumImagePixels(5000000)
144
145                ' This line can be used to output Flate compressed background
146                ' images rather than DCTDecode compressed images which is the default
147                'fl.SetPreferJPG(false)
148
149                ' In order to adjust thresholds for when text is Flattened
150                ' the following function can be used.
151                'fl.SetThreshold(Flattener.Threshold.e_keep_most)
152
153                ' We use e_fast option here since it is usually preferable
154                ' to avoid Flattening simple pages in terms of size and 
155                ' rendering speed. If the desire is to simplify the 
156                ' document for processing such that it contains only text and
157                ' a background image e_simple should be used instead.
158                fl.Process(doc, Flattener.FlattenMode.e_fast)
159
160                doc.Save(output_path & "TigerText_flatten.pdf", SDFDoc.SaveOptions.e_linearized)
161            End Using
162        Catch e As PDFNetException
163            Console.WriteLine(e.Message)
164        End Try
165
166        '-------------------------------------------------------------------------------
167        ' Example 5)  Example 5) Optimize a PDF for viewing using SaveViewerOptimized.
168
169        Try
170            Using doc As PDFDoc = New PDFDoc(input_path & input_filename & ".pdf")
171                doc.InitSecurityHandler()
172
173                Dim opts As New ViewerOptimizedOptions
174
175                ' set the maximum dimension (width or height) that thumbnails will have.
176                opts.SetThumbnailSize(1500)
177
178                ' set thumbnail rendering threshold. A number from 0 (include all thumbnails) to 100 (include only the first thumbnail) 
179                ' representing the complexity at which SaveViewerOptimized would include the thumbnail. 
180                ' By default it only produces thumbnails on the first and complex pages. 
181                ' The following line will produce thumbnails on every page.
182                ' opts.SetThumbnailRenderingThreshold(0); 
183                doc.SaveViewerOptimized(output_path & input_filename & "_SaveViewerOptimized.pdf", opts)
184            End Using
185        Catch e As PDFNetException
186            Console.WriteLine(e.Message)
187        End Try
188        PDFNet.Terminate()
189
190    End Sub
191End Module
Did you find this helpful?
Trial setup questions?
Ask experts on DiscordNeed other help?
Contact SupportPricing or product questions?
Contact Sales