> For the complete documentation index, see [llms.txt](https://docs.apryse.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.apryse.com/core/get-started/samples/optimizertest.md).

# Compress - Optimizer

This guide will walk you thorough how to compress PDF file using the Apryse Server SDK.  Easy to reduce images, unembed fonts, remove unused objects.  Samples provided in Python, C++, C#, Java, Node.j

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](/core/get-started/get-started.md).

{% tabs %}
{% tab title="C#" %}
{% code lineNumbers="true" %}

```csharp
//---------------------------------------------------------------------------------------
// Copyright (c) 2001-2024 by Apryse Software Inc. All Rights Reserved.
// Consult legal.txt regarding legal and license information.
//---------------------------------------------------------------------------------------

using System;
using System.IO;

using pdftron;
using pdftron.Common;
using pdftron.Filters;
using pdftron.SDF;
using pdftron.PDF;

namespace PDFNetSamples
{
	class Class1
	{
		private static pdftron.PDFNetLoader pdfNetLoader = pdftron.PDFNetLoader.Instance();
		static Class1() {}
		
		/// <summary>
		/// The following sample illustrates how to reduce PDF file size using 'pdftron.PDF.Optimizer'.
		/// The sample also shows how to simplify and optimize PDF documents for viewing on mobile devices 
		/// and on the Web using 'pdftron.PDF.Flattener'.
		///
		/// @note Both 'Optimizer' and 'Flattener' are separately licensable add-on options to the core PDFNet license.
		///
		/// ----
		///
		/// 'pdftron.PDF.Optimizer' can be used to optimize PDF documents by reducing the file size, removing 
		/// redundant information, and compressing data streams using the latest in image compression technology. 
		///
		/// PDF Optimizer can compress and shrink PDF file size with the following operations:
		/// - Remove duplicated fonts, images, ICC profiles, and any other data stream. 
		/// - Optionally convert high-quality or print-ready PDF files to small, efficient and web-ready PDF. 
		/// - Optionally down-sample large images to a given resolution. 
		/// - Optionally compress or recompress PDF images using JBIG2 and JPEG2000 compression formats. 
		/// - Compress uncompressed streams and remove unused PDF objects.
		/// 
		/// ----
		///
		/// 'pdftron.PDF.Flattener' can be used to speed-up PDF rendering on mobile devices and on the Web by 
		/// simplifying page content (e.g. flattening complex graphics into images) while maintaining vector text 
		/// whenever possible.
		///
		/// Flattener can also be used to simplify process of writing custom converters from PDF to other formats. 
		/// In this case, Flattener can be used as first step in the conversion pipeline to reduce any PDF to a 
		/// very simple representation (e.g. vector text on top of a background image).
		/// </summary>
		static void Main(string[] args)
		{
			PDFNet.Initialize(PDFTronLicense.Key);

			string input_path = "../../../../TestFiles/";
			string output_path = "../../../../TestFiles/Output/";
			string input_filename = "newsletter";


			//--------------------------------------------------------------------------------
			// Example 1) Simple optimization of a pdf with default settings. 
			//
			try
			{
				using (PDFDoc doc = new PDFDoc(input_path + input_filename + ".pdf"))
				{
					doc.InitSecurityHandler();
					Optimizer.Optimize(doc);
					doc.Save(output_path + input_filename + "_opt1.pdf", SDFDoc.SaveOptions.e_linearized);
				}
			}
			catch (PDFNetException e)
			{
				Console.WriteLine(e.Message);
			}
				
			//--------------------------------------------------------------------------------
			// Example 2) Reduce image quality and use jpeg compression for
			// non monochrome images.
			try
			{
				using (PDFDoc doc = new PDFDoc(input_path + input_filename + ".pdf"))
				{
					doc.InitSecurityHandler();

					Optimizer.ImageSettings image_settings = new Optimizer.ImageSettings();

					// low quality jpeg compression
					image_settings.SetCompressionMode(Optimizer.ImageSettings.CompressionMode.e_jpeg);
					image_settings.SetQuality(1);

					// Set the output dpi to be standard screen resolution
					image_settings.SetImageDPI(144,96);

					// this option will recompress images not compressed with
					// jpeg compression and use the result if the new image
					// is smaller.
					image_settings.ForceRecompression(true);

					// this option is not commonly used since it can 
					// potentially lead to larger files.  It should be enabled
					// only if the output compression specified should be applied
					// to every image of a given type regardless of the output image size
					//image_settings.ForceChanges(true);

					// use the same settings for both color and grayscale images
					Optimizer.OptimizerSettings opt_settings = new Optimizer.OptimizerSettings();
					opt_settings.SetColorImageSettings(image_settings);
					opt_settings.SetGrayscaleImageSettings(image_settings);

					
					Optimizer.Optimize(doc, opt_settings);

					doc.Save(output_path + input_filename + "_opt2.pdf", SDFDoc.SaveOptions.e_linearized);
				}
			}
			catch (PDFNetException e)
			{
				Console.WriteLine(e.Message);
			}


			//--------------------------------------------------------------------------------
			// Example 3) Use monochrome image settings and default settings
			// for color and grayscale images. 
			try
			{
				using (PDFDoc doc = new PDFDoc(input_path + input_filename + ".pdf"))
				{
					doc.InitSecurityHandler();

					Optimizer.MonoImageSettings mono_image_settings = new Optimizer.MonoImageSettings();

					mono_image_settings.SetCompressionMode(Optimizer.MonoImageSettings.CompressionMode.e_jbig2);
					mono_image_settings.ForceRecompression(true);

					Optimizer.OptimizerSettings opt_settings = new Optimizer.OptimizerSettings();
					opt_settings.SetMonoImageSettings(mono_image_settings);

					Optimizer.Optimize(doc, opt_settings);

					doc.Save(output_path + input_filename + "_opt3.pdf", SDFDoc.SaveOptions.e_linearized);
				}
			}
			catch (PDFNetException e)
			{
				Console.WriteLine(e.Message);
			}

			//-------------------------------------------------------------------------------
			// Example 4) Use Flattener to simplify content in this document
			// using default settings

			try
			{
				using (PDFDoc doc = new PDFDoc(input_path + "TigerText.pdf"))
				{
					doc.InitSecurityHandler();

					Flattener fl = new Flattener();

					// The following lines can increase the resolution of background
					// images.
					//fl.SetDPI(300);
					//fl.SetMaximumImagePixels(5000000);

					// This line can be used to output Flate compressed background
					// images rather than DCTDecode compressed images which is the default
					//fl.SetPreferJPG(false);

					// In order to adjust thresholds for when text is Flattened
					// the following function can be used.
					//fl.SetThreshold(Flattener.Threshold.e_keep_most);

					// We use e_fast option here since it is usually preferable
					// to avoid Flattening simple pages in terms of size and 
					// rendering speed. If the desire is to simplify the 
					// document for processing such that it contains only text and
					// a background image e_simple should be used instead.
					fl.Process(doc,Flattener.FlattenMode.e_fast);

					doc.Save(output_path + "TigerText_flatten.pdf", SDFDoc.SaveOptions.e_linearized);
				}
			}
			catch (PDFNetException e)
			{
				Console.WriteLine(e.Message);	
			}

			//-------------------------------------------------------------------------------
			// Example 5) Optimize a PDF for viewing using SaveViewerOptimized.

			try
			{
				using (PDFDoc doc = new PDFDoc(input_path + input_filename + ".pdf"))
				{
					doc.InitSecurityHandler();

					ViewerOptimizedOptions opts = new ViewerOptimizedOptions();

					// set the maximum dimension (width or height) that thumbnails will have.
					opts.SetThumbnailSize(1500);

					// set thumbnail rendering threshold. A number from 0 (include all thumbnails) to 100 (include only the first thumbnail) 
					// representing the complexity at which SaveViewerOptimized would include the thumbnail. 
					// By default it only produces thumbnails on the first and complex pages. 
					// The following line will produce thumbnails on every page.
					// opts.SetThumbnailRenderingThreshold(0); 

					doc.SaveViewerOptimized(output_path + input_filename + "_SaveViewerOptimized.pdf", opts);
				}
			}
			catch (PDFNetException e)
			{
				Console.WriteLine(e.Message);
			}
			PDFNet.Terminate();
		}
	}
}
```

{% endcode %}
{% endtab %}

{% tab title="Go" %}
{% code lineNumbers="true" %}

```go
//---------------------------------------------------------------------------------------
// Copyright (c) 2001-2021 by PDFTron Systems Inc. All Rights Reserved.
// Consult LICENSE.txt regarding license information.
//---------------------------------------------------------------------------------------

package main
import (
	. "pdftron"
)

import  "pdftron/Samples/LicenseKey/GO"
//---------------------------------------------------------------------------------------
// The following sample illustrates how to reduce PDF file size using 'pdftron.PDF.Optimizer'.
// The sample also shows how to simplify and optimize PDF documents for viewing on mobile devices 
// and on the Web using 'pdftron.PDF.Flattener'.
//
// @note Both 'Optimizer' and 'Flattener' are separately licensable add-on options to the core PDFNet license.
//
// ----
//
// 'pdftron.PDF.Optimizer' can be used to optimize PDF documents by reducing the file size, removing 
// redundant information, and compressing data streams using the latest in image compression technology. 
//
// PDF Optimizer can compress and shrink PDF file size with the following operations:
// - Remove duplicated fonts, images, ICC profiles, and any other data stream. 
// - Optionally convert high-quality or print-ready PDF files to small, efficient and web-ready PDF. 
// - Optionally down-sample large images to a given resolution. 
// - Optionally compress or recompress PDF images using JBIG2 and JPEG2000 compression formats. 
// - Compress uncompressed streams and remove unused PDF objects.
// ----
//
// 'pdftron.PDF.Flattener' can be used to speed-up PDF rendering on mobile devices and on the Web by 
// simplifying page content (e.g. flattening complex graphics into images) while maintaining vector text 
// whenever possible.
//
// Flattener can also be used to simplify process of writing custom converters from PDF to other formats. 
// In this case, Flattener can be used as first step in the conversion pipeline to reduce any PDF to a 
// very simple representation (e.g. vector text on top of a background image). 
//---------------------------------------------------------------------------------------

func main(){
    // Relative path to the folder containing the test files.
    inputPath := "../../TestFiles/"
    outputPath := "../../TestFiles/Output/"
    inputFileName := "newsletter"
    
    // The first step in every application using PDFNet is to initialize the 
    // library and set the path to common PDF resources. The library is usually 
    // initialized only once, but calling Initialize() multiple times is also fine.
    PDFNetInitialize(PDFTronLicense.Key)
    
    //--------------------------------------------------------------------------------
    // Example 1) Simple optimization of a pdf with default settings.
    
    doc := NewPDFDoc(inputPath + inputFileName + ".pdf")
    doc.InitSecurityHandler()
    OptimizerOptimize(doc)
    
    doc.Save(outputPath + inputFileName + "_opt1.pdf", uint(SDFDocE_linearized))
    doc.Close()
    
    //--------------------------------------------------------------------------------
    // Example 2) Reduce image quality and use jpeg compression for
    // non monochrome images.    
    doc = NewPDFDoc(inputPath + inputFileName + ".pdf")
    doc.InitSecurityHandler()
    imageSettings := NewImageSettings()
    
    // low quality jpeg compression
    imageSettings.SetCompressionMode(ImageSettingsE_jpeg)
    imageSettings.SetQuality(1)
    
    // Set the output dpi to be standard screen resolution
    imageSettings.SetImageDPI(144,96)
    
    // this option will recompress images not compressed with
    // jpeg compression and use the result if the new image
    // is smaller.
    imageSettings.ForceRecompression(true)
    
    // this option is not commonly used since it can 
    // potentially lead to larger files.  It should be enabled
    // only if the output compression specified should be applied
    // to every image of a given type regardless of the output image size
    //imageSettings.ForceChanges(true)

    optSettings := NewOptimizerSettings()
    optSettings.SetColorImageSettings(imageSettings)
    optSettings.SetGrayscaleImageSettings(imageSettings)

    // use the same settings for both color and grayscale images
    OptimizerOptimize(doc, optSettings)
    
    doc.Save(outputPath + inputFileName + "_opt2.pdf", uint(SDFDocE_linearized))
    doc.Close()
    
    //--------------------------------------------------------------------------------
    // Example 3) Use monochrome image settings and default settings
    // for color and grayscale images. 
    
    doc = NewPDFDoc(inputPath + inputFileName + ".pdf")
    doc.InitSecurityHandler()

    monoImageSettings := NewMonoImageSettings()
    
    monoImageSettings.SetCompressionMode(MonoImageSettingsE_jbig2)
    monoImageSettings.ForceRecompression(true)

    optSettings = NewOptimizerSettings()
    optSettings.SetMonoImageSettings(monoImageSettings)
    
    OptimizerOptimize(doc, optSettings)
    doc.Save(outputPath + inputFileName + "_opt3.pdf", uint(SDFDocE_linearized))
    doc.Close()
	
    // ----------------------------------------------------------------------
    // Example 4) Use Flattener to simplify content in this document
    // using default settings
    
    doc = NewPDFDoc(inputPath + "TigerText.pdf")
    doc.InitSecurityHandler()
    
    fl := NewFlattener()
    // The following lines can increase the resolution of background
    // images.
    //fl.SetDPI(300)
    //fl.SetMaximumImagePixels(5000000)

    // This line can be used to output Flate compressed background
    // images rather than DCTDecode compressed images which is the default
    //fl.SetPreferJPG(false)

    // In order to adjust thresholds for when text is Flattened
    // the following function can be used.
    //fl.SetThreshold(FlattenerE_threshold_keep_most)

    // We use e_fast option here since it is usually preferable
    // to avoid Flattening simple pages in terms of size and 
    // rendering speed. If the desire is to simplify the 
    // document for processing such that it contains only text and
    // a background image e_simple should be used instead.
    fl.Process(doc, FlattenerE_fast)
    doc.Save(outputPath + "TigerText_flatten.pdf", uint(SDFDocE_linearized))
    doc.Close()

    // ----------------------------------------------------------------------
    // Example 5) Optimize a PDF for viewing using SaveViewerOptimized.
    
    doc = NewPDFDoc(inputPath + inputFileName + ".pdf")
    doc.InitSecurityHandler()
    
    opts := NewViewerOptimizedOptions()

    // set the maximum dimension (width or height) that thumbnails will have.
    opts.SetThumbnailSize(1500)

    // set thumbnail rendering threshold. A number from 0 (include all thumbnails) to 100 (include only the first thumbnail) 
    // representing the complexity at which SaveViewerOptimized would include the thumbnail. 
    // By default it only produces thumbnails on the first and complex pages. 
    // The following line will produce thumbnails on every page.
    // opts.SetThumbnailRenderingThreshold(0) 

    doc.SaveViewerOptimized(outputPath + inputFileName + "_SaveViewerOptimized.pdf", opts)
    doc.Close()
    PDFNetTerminate()
}
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code lineNumbers="true" %}

```cpp
//---------------------------------------------------------------------------------------
// Copyright (c) 2001-2024 by Apryse Software Inc. All Rights Reserved.
// Consult legal.txt regarding legal and license information.
//---------------------------------------------------------------------------------------

#include <PDF/PDFNet.h>
#include <PDF/Optimizer.h>
#include <iostream>
#include <PDF/Flattener.h>
#include "../../LicenseKey/CPP/LicenseKey.h"

using namespace std;
using namespace pdftron;
using namespace Common;
using namespace SDF;
using namespace PDF;

//---------------------------------------------------------------------------------------
// The following sample illustrates how to reduce PDF file size using 'pdftron.PDF.Optimizer'.
// The sample also shows how to simplify and optimize PDF documents for viewing on mobile devices 
// and on the Web using 'pdftron.PDF.Flattener'.
//
// @note Both 'Optimizer' and 'Flattener' are separately licensable add-on options to the core PDFNet license.
//
// ----
//
// 'pdftron.PDF.Optimizer' can be used to optimize PDF documents by reducing the file size, removing 
// redundant information, and compressing data streams using the latest in image compression technology. 
//
// PDF Optimizer can compress and shrink PDF file size with the following operations:
// - Remove duplicated fonts, images, ICC profiles, and any other data stream. 
// - Optionally convert high-quality or print-ready PDF files to small, efficient and web-ready PDF. 
// - Optionally down-sample large images to a given resolution. 
// - Optionally compress or recompress PDF images using JBIG2 and JPEG2000 compression formats. 
// - Compress uncompressed streams and remove unused PDF objects. 
//
// ----
//
// 'pdftron.PDF.Flattener' can be used to speed-up PDF rendering on mobile devices and on the Web by 
// simplifying page content (e.g. flattening complex graphics into images) while maintaining vector text 
// whenever possible.
//
// Flattener can also be used to simplify process of writing custom converters from PDF to other formats. 
// In this case, Flattener can be used as first step in the conversion pipeline to reduce any PDF to a 
// very simple representation (e.g. vector text on top of a background image).
//---------------------------------------------------------------------------------------

int main(int argc, char * argv[])
{
	int ret = 0;
	std::string input_path = "../../TestFiles/";
	std::string output_path = "../../TestFiles/Output/";
	std::string input_filename = "newsletter";	

	// The first step in every application using PDFNet is to initialize the 
	// library and set the path to common PDF resources. The library is usually 
	// initialized only once, but calling Initialize() multiple times is also fine.
	PDFNet::Initialize(LicenseKey);

	//--------------------------------------------------------------------------------
	// Example 1) Simple optimization of a pdf with default settings. 
	//
	try
	{
		pdftron::PDF::PDFDoc doc(input_path + input_filename + ".pdf");
		doc.InitSecurityHandler();

		Optimizer::Optimize(doc);

		doc.Save(output_path + input_filename + "_opt1.pdf", SDFDoc::e_linearized, NULL);
	}
	catch (Common::Exception& e)
	{
		std::cout << e << endl;
		ret = 1;		
	}
	catch (...)
	{
		cout << "Unknown Exception" << endl;
		ret = 1;
	}

	//--------------------------------------------------------------------------------
	// Example 2) Reduce image quality and use jpeg compression for
	// non monochrome images.
	try
	{
		PDFDoc doc(input_path + input_filename + ".pdf");
		doc.InitSecurityHandler();

		Optimizer::ImageSettings image_settings;

		// low quality jpeg compression
		image_settings.SetCompressionMode(Optimizer::ImageSettings::e_jpeg);
		image_settings.SetQuality(1);

		// Set the output dpi to be standard screen resolution
		image_settings.SetImageDPI(144,96);

		// this option will recompress images not compressed with
		// jpeg compression and use the result if the new image
		// is smaller.
		image_settings.ForceRecompression(true);

		// this option is not commonly used since it can 
		// potentially lead to larger files.  It should be enabled
		// only if the output compression specified should be applied
		// to every image of a given type regardless of the output image size
		//image_settings.ForceChanges(true);


		Optimizer::OptimizerSettings opt_settings;
		opt_settings.SetColorImageSettings(image_settings);
		opt_settings.SetGrayscaleImageSettings(image_settings);

		// use the same settings for both color and grayscale images
		Optimizer::Optimize(doc, opt_settings);

		doc.Save(output_path + input_filename + "_opt2.pdf", SDFDoc::e_linearized, NULL);
	}
	catch (Common::Exception& e)
	{
		std::cout << e << endl;
		ret = 1;		
	}
	catch (...)
	{
		cout << "Unknown Exception" << endl;
		ret = 1;
	}

	//--------------------------------------------------------------------------------
	// Example 3) Use monochrome image settings and default settings
	// for color and grayscale images. 
	try
	{
		PDFDoc doc(input_path + input_filename + ".pdf");
		doc.InitSecurityHandler();

		Optimizer::MonoImageSettings mono_image_settings;

		mono_image_settings.SetCompressionMode(Optimizer::MonoImageSettings::e_jbig2);
		mono_image_settings.ForceRecompression(true);

		Optimizer::OptimizerSettings opt_settings;
		opt_settings.SetMonoImageSettings(mono_image_settings);

		Optimizer::Optimize(doc, opt_settings);

		doc.Save(output_path + input_filename + "_opt3.pdf", SDFDoc::e_linearized, NULL);
	}
	catch (Common::Exception& e)
	{
		std::cout << e << endl;
		ret = 1;		
	}
	catch (...)
	{
		cout << "Unknown Exception" << endl;
		ret = 1;
	}

	// ----------------------------------------------------------------------
	// Example 4) Use Flattener to simplify content in this document
	// using default settings
	try
	{
		PDFDoc doc(input_path + "TigerText.pdf");
		doc.InitSecurityHandler();

		Flattener fl;

		// The following lines can increase the resolution of background
		// images.
		//fl.SetDPI(300);
		//fl.SetMaximumImagePixels(5000000);

		// This line can be used to output Flate compressed background
		// images rather than DCTDecode compressed images which is the default
		//fl.SetPreferJPG(false);

		// In order to adjust thresholds for when text is Flattened
		// the following function can be used.
		//fl.SetThreshold(Flattener::e_keep_most);

		// We use e_fast option here since it is usually preferable
		// to avoid Flattening simple pages in terms of size and 
		// rendering speed. If the desire is to simplify the 
		// document for processing such that it contains only text and
		// a background image e_simple should be used instead.
		fl.Process(doc,Flattener::e_fast);

		doc.Save(output_path + "TigerText_flatten.pdf", SDFDoc::e_linearized, NULL);

	}
	catch (Common::Exception& e)
	{
		std::cout << e << endl;
		ret = 1;		
	}
	catch (...)
	{
		cout << "Unknown Exception" << endl;
		ret = 1;
	}

	//--------------------------------------------------------------------------------
	// Example 5) Optimize a PDF for viewing using SaveViewerOptimized.
	try
	{
		PDFDoc doc(input_path + input_filename + ".pdf");
		doc.InitSecurityHandler();

		ViewerOptimizedOptions opts;

		// set the maximum dimension (width or height) that thumbnails will have.
		opts.SetThumbnailSize(1500);

		// set thumbnail rendering threshold. A number from 0 (include all thumbnails) to 100 (include only the first thumbnail) 
		// representing the complexity at which SaveViewerOptimized would include the thumbnail. 
		// By default it only produces thumbnails on the first and complex pages. 
		// The following line will produce thumbnails on every page.
		// opts.SetThumbnailRenderingThreshold(0); 
	
		doc.SaveViewerOptimized(output_path + input_filename + "_SaveViewerOptimized.pdf", opts);
	}
	catch (Common::Exception& e)
	{
		std::cout << e << endl;
		ret = 1;
	}
	catch (...)
	{
		cout << "Unknown Exception" << endl;
		ret = 1;
	}

	PDFNet::Terminate();
	return ret;
}
```

{% endcode %}
{% endtab %}

{% tab title="Java" %}
{% code lineNumbers="true" %}

```java
//---------------------------------------------------------------------------------------
// Copyright (c) 2001-2024 by Apryse Software Inc. All Rights Reserved.
// Consult legal.txt regarding legal and license information.
//---------------------------------------------------------------------------------------

import com.pdftron.pdf.*;
import com.pdftron.sdf.SDFDoc;

public class OptimizerTest {
    //---------------------------------------------------------------------------------------
    // The following sample illustrates how to reduce PDF file size using 'pdftron.PDF.Optimizer'.
    // The sample also shows how to simplify and optimize PDF documents for viewing on mobile devices
    // and on the Web using 'pdftron.PDF.Flattener'.
    //
    // @note Both 'Optimizer' and 'Flattener' are separately licensable add-on options to the core PDFNet license.
    //
    // ----
    //
    // 'pdftron.PDF.Optimizer' can be used to optimize PDF documents by reducing the file size, removing
    // redundant information, and compressing data streams using the latest in image compression technology.
    //
    // PDF Optimizer can compress and shrink PDF file size with the following operations:
    // - Remove duplicated fonts, images, ICC profiles, and any other data stream.
    // - Optionally convert high-quality or print-ready PDF files to small, efficient and web-ready PDF.
    // - Optionally down-sample large images to a given resolution.
    // - Optionally compress or recompress PDF images using JBIG2 and JPEG2000 compression formats.
    // - Compress uncompressed streams and remove unused PDF objects.
    //
    // 'pdftron.PDF.Flattener' can be used to speed-up PDF rendering on mobile devices and on the Web by
    // simplifying page content (e.g. flattening complex graphics into images) while maintaining vector text
    // whenever possible.
    //
    // Flattener can also be used to simplify process of writing custom converters from PDF to other formats.
    // In this case, Flattener can be used as first step in the conversion pipeline to reduce any PDF to a
    // very simple representation (e.g. vector text on top of a background image).
    //---------------------------------------------------------------------------------------
    public static void main(String[] args) {
        String input_path = "../../TestFiles/";
        String output_path = "../../TestFiles/Output/";
        String input_filename = "newsletter.pdf";
        String input_filename2 = "newsletter_opt1.pdf";
        String input_filename3 = "newsletter_opt2.pdf";
        String input_filename4 = "newsletter_opt3.pdf";
        String input_filename5 = "newsletter_SaveViewerOptimized.pdf";

        PDFNet.initialize(PDFTronLicense.Key());

        //--------------------------------------------------------------------------------
        // Example 1) Optimize a PDF.
        try (PDFDoc doc = new PDFDoc(input_path + input_filename)) {
            doc.initSecurityHandler();
            Optimizer.optimize(doc);
            doc.save(output_path + input_filename2, SDFDoc.SaveMode.LINEARIZED, null);
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }

        //--------------------------------------------------------------------------------
        // Example 2) Reduce image quality and use jpeg compression for
        // non monochrome images.
        try (PDFDoc doc = new PDFDoc(input_path + input_filename)) {
            doc.initSecurityHandler();

            Optimizer.ImageSettings image_settings = new Optimizer.ImageSettings();

            // low quality jpeg compression
            image_settings.setCompressionMode(Optimizer.ImageSettings.e_jpeg);
            image_settings.setQuality(1);

            // Set the output dpi to be standard screen resolution
            image_settings.setImageDPI(144, 96);

            // this option will recompress images not compressed with
            // jpeg compression and use the result if the new image
            // is smaller.
            image_settings.forceRecompression(true);


            // this option is not commonly used since it can
            // potentially lead to larger files.  It should be enabled
            // only if the output compression specified should be applied
            // to every image of a given type regardless of the output image size
            //image_settings.forceChanges(true);

            Optimizer.OptimizerSettings opt_settings = new Optimizer.OptimizerSettings();
            opt_settings.setColorImageSettings(image_settings);
            opt_settings.setGrayscaleImageSettings(image_settings);

            Optimizer.optimize(doc, opt_settings);

            doc.save(output_path + input_filename3, SDFDoc.SaveMode.LINEARIZED, null);
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }

        //--------------------------------------------------------------------------------
        // Example 3) Use monochrome image settings and default settings
        // for color and grayscale images.
        try (PDFDoc doc = new PDFDoc(input_path + input_filename)) {
            doc.initSecurityHandler();

            Optimizer.MonoImageSettings mono_image_settings = new Optimizer.MonoImageSettings();
            mono_image_settings.setCompressionMode(Optimizer.MonoImageSettings.e_jbig2);
            mono_image_settings.forceRecompression(true);
            Optimizer.OptimizerSettings opt_settings = new Optimizer.OptimizerSettings();
            opt_settings.setMonoImageSettings(mono_image_settings);

            Optimizer.optimize(doc, opt_settings);

            doc.save(output_path + input_filename4, SDFDoc.SaveMode.LINEARIZED, null);
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }

        // ----------------------------------------------------------------------
        // Example 4) Use Flattener to simplify content in this document
        // using default settings
        try (PDFDoc doc = new PDFDoc(input_path + "TigerText.pdf")) {
            doc.initSecurityHandler();

            Flattener fl = new Flattener();

            // The following lines can increase the resolution of background
            // images.
            //fl.setDPI(300);
            //fl.setMaximumImagePixels(5000000);

            // This line can be used to output Flate compressed background
            // images rather than DCTDecode compressed images which is the default
            //fl.setPreferJPG(false);

            // In order to adjust thresholds for when text is Flattened
            // the following function can be used.
            //fl.setThreshold(Flattener.e_keep_most);

            // We use e_fast option here since it is usually preferable
            // to avoid Flattening simple pages in terms of size and
            // rendering speed. If the desire is to simplify the
            // document for processing such that it contains only text and
            // a background image e_simple should be used instead.
            fl.Process(doc, Flattener.e_fast);

            doc.save(output_path + "TigerText_flatten.pdf", SDFDoc.SaveMode.LINEARIZED, null);
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }
        
        // ----------------------------------------------------------------------
        // Example 5) Optimize a PDF for viewing using SaveViewerOptimized.
        try (PDFDoc doc = new PDFDoc(input_path + input_filename)) {
            doc.initSecurityHandler();

            ViewerOptimizedOptions opts = new ViewerOptimizedOptions();

            // set the maximum dimension (width or height) that thumbnails will have.
            opts.setThumbnailSize(1500);

            // set thumbnail rendering threshold. A number from 0 (include all thumbnails) to 100 (include only the first thumbnail) 
            // representing the complexity at which SaveViewerOptimized would include the thumbnail. 
            // By default it only produces thumbnails on the first and complex pages. 
            // The following line will produce thumbnails on every page.
            // opts.setThumbnailRenderingThreshold(0); 

            doc.saveViewerOptimized(output_path + input_filename5 , opts);
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }
        PDFNet.terminate();
    }
}
```

{% endcode %}
{% endtab %}

{% tab title="JavaScript" %}
{% code lineNumbers="true" %}

```js
//---------------------------------------------------------------------------------------
// Copyright (c) 2001-2024 by Apryse Software Inc. All Rights Reserved.
// Consult legal.txt regarding legal and license information.
//---------------------------------------------------------------------------------------

//---------------------------------------------------------------------------------------
// The following sample illustrates how to reduce PDF file size using 'pdftron.PDF.Optimizer'.
// The sample also shows how to simplify and optimize PDF documents for viewing on mobile devices 
// and on the Web using 'pdftron.PDF.Flattener'.
//
// @note Both 'Optimizer' and 'Flattener' are separately licensable add-on options to the core PDFNet license.
//
// ----
//
// 'pdftron.PDF.Optimizer' can be used to optimize PDF documents by reducing the file size, removing 
// redundant information, and compressing data streams using the latest in image compression technology. 
//
// PDF Optimizer can compress and shrink PDF file size with the following operations:
// - Remove duplicated fonts, images, ICC profiles, and any other data stream. 
// - Optionally convert high-quality or print-ready PDF files to small, efficient and web-ready PDF. 
// - Optionally down-sample large images to a given resolution. 
// - Optionally compress or recompress PDF images using JBIG2 and JPEG2000 compression formats. 
// - Compress uncompressed streams and remove unused PDF objects. 
//
// ----
//
// 'pdftron.PDF.Flattener' can be used to speed-up PDF rendering on mobile devices and on the Web by 
// simplifying page content (e.g. flattening complex graphics into images) while maintaining vector text 
// whenever possible.
//
// Flattener can also be used to simplify process of writing custom converters from PDF to other formats. 
// In this case, Flattener can be used as first step in the conversion pipeline to reduce any PDF to a 
// very simple representation (e.g. vector text on top of a background image).
//---------------------------------------------------------------------------------------

const { PDFNet } = require('@pdftron/pdfnet-node');
const PDFTronLicense = require('../LicenseKey/LicenseKey');

((exports) => {
  'use strict';

  exports.runOptimizerTest = () => {
    const main = async () => {
      const inputPath = '../TestFiles/';
      const outputPath = inputPath + 'Output/';
      const inputFilename = 'newsletter';

      // The first step in every application using PDFNet is to initialize the 
      // library and set the path to common PDF resources. The library is usually 
      // initialized only once, but calling Initialize() multiple times is also fine.

      //--------------------------------------------------------------------------------
      // Example 1) Simple optimization of a pdf with default settings. 
      //
      try {
        const doc = await PDFNet.PDFDoc.createFromFilePath(inputPath + inputFilename + '.pdf');
        await doc.initSecurityHandler();
        await PDFNet.Optimizer.optimize(doc);
        doc.save(outputPath + inputFilename + '_opt1.pdf', PDFNet.SDFDoc.SaveOptions.e_linearized);
      }
      catch (err) {
        console.log(err);
      }

      //--------------------------------------------------------------------------------
      // Example 2) Reduce image quality and use jpeg compression for
      // non monochrome images.
      try {
        const doc = await PDFNet.PDFDoc.createFromFilePath(inputPath + inputFilename + '.pdf');
        await doc.initSecurityHandler();
        const image_settings = new PDFNet.Optimizer.ImageSettings();

        // low quality jpeg compression
        image_settings.setCompressionMode(PDFNet.Optimizer.ImageSettings.CompressionMode.e_jpeg);
        image_settings.setQuality(1);

        // Set the output dpi to be standard screen resolution
        image_settings.setImageDPI(144, 96);

        // this option will recompress images not compressed with
        // jpeg compression and use the result if the new image
        // is smaller.
        image_settings.forceRecompression(true);

        // this option is not commonly used since it can 
        // potentially lead to larger files.  It should be enabled
        // only if the output compression specified should be applied
        // to every image of a given type regardless of the output image size
        //image_settings.forceChanges(true);

        const opt_settings = new PDFNet.Optimizer.OptimizerSettings();
        opt_settings.setColorImageSettings(image_settings);
        opt_settings.setGrayscaleImageSettings(image_settings);

        // use the same settings for both color and grayscale images
        await PDFNet.Optimizer.optimize(doc, opt_settings);

        doc.save(outputPath + inputFilename + '_opt2.pdf', PDFNet.SDFDoc.SaveOptions.e_linearized);
      }
      catch (err) {
        console.log(err);
      }

      //--------------------------------------------------------------------------------
      // Example 3) Use monochrome image settings and default settings
      // for color and grayscale images. 
      try {
        const doc = await PDFNet.PDFDoc.createFromFilePath(inputPath + inputFilename + '.pdf');
        await doc.initSecurityHandler();

        const mono_image_settings = new PDFNet.Optimizer.MonoImageSettings();

        mono_image_settings.setCompressionMode(PDFNet.Optimizer.MonoImageSettings.CompressionMode.e_jbig2);
        mono_image_settings.forceRecompression(true);

        const opt_settings = new PDFNet.Optimizer.OptimizerSettings();

        opt_settings.setMonoImageSettings(mono_image_settings);

        await PDFNet.Optimizer.optimize(doc, opt_settings);
        doc.save(outputPath + inputFilename + '_opt3.pdf', PDFNet.SDFDoc.SaveOptions.e_linearized);
      }
      catch (err) {
        console.log(err);
      }

      // ----------------------------------------------------------------------
      // Example 4) Use Flattener to simplify content in this document
      // using default settings
      try {
        const doc = await PDFNet.PDFDoc.createFromFilePath(inputPath + 'TigerText.pdf');
        await doc.initSecurityHandler();

        const fl = await PDFNet.Flattener.create();

        // The following lines can increase the resolution of background
        // images.
        //fl.setDPI(300);
        //fl.setMaximumImagePixels(5000000);

        // This line can be used to output Flate compressed background
        // images rather than DCTDecode compressed images which is the default
        //fl.setPreferJPG(false);

        // In order to adjust thresholds for when text is Flattened
        // the following function can be used.
        //fl.setThreshold(PDFNet.Flattener.Threshold.e_keep_most);

        // We use e_fast option here since it is usually preferable
        // to avoid Flattening simple pages in terms of size and 
        // rendering speed. If the desire is to simplify the 
        // document for processing such that it contains only text and
        // a background image e_simple should be used instead.
        await fl.process(doc, PDFNet.Flattener.Mode.e_fast);

        doc.save(outputPath + 'TigerText_flatten.pdf', PDFNet.SDFDoc.SaveOptions.e_linearized);
      }
      catch (err) {
        console.log(err);
      }

      //--------------------------------------------------------------------------------
      // Example 5) Optimize a PDF for viewing using SaveViewerOptimized.
      try {
        const doc = await PDFNet.PDFDoc.createFromFilePath(inputPath + inputFilename + '.pdf');
        doc.initSecurityHandler();

        const opts = new PDFNet.PDFDoc.ViewerOptimizedOptions();

        // set the maximum dimension (width or height) that thumbnails will have.
        opts.setThumbnailSize(1500);

        // set thumbnail rendering threshold. A number from 0 (include all thumbnails) to 100 (include only the first thumbnail) 
        // representing the complexity at which SaveViewerOptimized would include the thumbnail. 
        // By default it only produces thumbnails on the first and complex pages. 
        // The following line will produce thumbnails on every page.
        // opts.setThumbnailRenderingThreshold(0); 

        await doc.saveViewerOptimized(outputPath + inputFilename + '_SaveViewerOptimized.pdf', opts);
      }
      catch (err) {
        console.log(err);
      }
    };
    PDFNet.runWithCleanup(main, PDFTronLicense.Key).catch(function (error) {
      console.log('Error: ' + JSON.stringify(error));
    }).then(function () { return PDFNet.shutdown(); });
  };
  exports.runOptimizerTest();
})(exports);
// eslint-disable-next-line spaced-comment
//# sourceURL=OptimizerTest.js
```

{% endcode %}
{% endtab %}

{% tab title="PHP" %}
{% code lineNumbers="true" %}

```php
<?php
//---------------------------------------------------------------------------------------
// Copyright (c) 2001-2023 by Apryse Software Inc. All Rights Reserved.
// Consult LICENSE.txt regarding license information.
//---------------------------------------------------------------------------------------
if(file_exists("../../../PDFNetC/Lib/PDFNetPHP.php"))
include("../../../PDFNetC/Lib/PDFNetPHP.php");
include("../../LicenseKey/PHP/LicenseKey.php");

// Relative path to the folder containing the test files.
$input_path = getcwd()."/../../TestFiles/";
$output_path = $input_path."Output/";
$input_filename = "newsletter";

//---------------------------------------------------------------------------------------
// The following sample illustrates how to reduce PDF file size using 'pdftron.PDF.Optimizer'.
// The sample also shows how to simplify and optimize PDF documents for viewing on mobile devices 
// and on the Web using 'pdftron.PDF.Flattener'.
//
// @note Both 'Optimizer' and 'Flattener' are separately licensable add-on options to the core PDFNet license.
//
// ----
//
// 'pdftron.PDF.Optimizer' can be used to optimize PDF documents by reducing the file size, removing 
// redundant information, and compressing data streams using the latest in image compression technology. 
//
// PDF Optimizer can compress and shrink PDF file size with the following operations:
// - Remove duplicated fonts, images, ICC profiles, and any other data stream. 
// - Optionally convert high-quality or print-ready PDF files to small, efficient and web-ready PDF. 
// - Optionally down-sample large images to a given resolution. 
// - Optionally compress or recompress PDF images using JBIG2 and JPEG2000 compression formats. 
// - Compress uncompressed streams and remove unused PDF objects.
// ----
//
// 'pdftron.PDF.Flattener' can be used to speed-up PDF rendering on mobile devices and on the Web by 
// simplifying page content (e.g. flattening complex graphics into images) while maintaining vector text 
// whenever possible.
//
// Flattener can also be used to simplify process of writing custom converters from PDF to other formats. 
// In this case, Flattener can be used as first step in the conversion pipeline to reduce any PDF to a 
// very simple representation (e.g. vector text on top of a background image). 
//---------------------------------------------------------------------------------------

	// The first step in every application using PDFNet is to initialize the 
	// library and set the path to common PDF resources. The library is usually 
	// initialized only once, but calling Initialize() multiple times is also fine.
	PDFNet::Initialize($LicenseKey);
	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.

	//--------------------------------------------------------------------------------
	// Example 1) Simple optimization of a pdf with default settings. 
	//

	$doc = new PDFDoc($input_path.$input_filename.".pdf");
	$doc->InitSecurityHandler();

	Optimizer::Optimize($doc);

	$doc->Save($output_path.$input_filename."_opt1.pdf", SDFDoc::e_linearized);
	$doc->Close();

	//--------------------------------------------------------------------------------
	// Example 2) Reduce image quality and use jpeg compression for
	// non monochrome images.
	
	$doc = new PDFDoc($input_path.$input_filename.".pdf");
	$doc->InitSecurityHandler();

	$image_settings = new ImageSettings();

	// low quality jpeg compression
	$image_settings->SetCompressionMode(ImageSettings::e_jpeg);
	$image_settings->SetQuality(1);

	// Set the output dpi to be standard screen resolution
	$image_settings->SetImageDPI(144,96);

	// this option will recompress images not compressed with
	// jpeg compression and use the result if the new image
	// is smaller.
	$image_settings->ForceRecompression(true);

	// this option is not commonly used since it can 
	// potentially lead to larger files.  It should be enabled
	// only if the output compression specified should be applied
	// to every image of a given type regardless of the output image size
	//$image_settings->ForceChanges(true);

	$opt_settings = new OptimizerSettings();
	$opt_settings->SetColorImageSettings($image_settings);
	$opt_settings->SetGrayScaleImageSettings($image_settings);

	// use the same settings for both color and grayscale images
	Optimizer::Optimize($doc, $opt_settings);

	$doc->Save($output_path.$input_filename."_opt2.pdf", SDFDoc::e_linearized);
	$doc->Close();

	//--------------------------------------------------------------------------------
	// Example 3) Use monochrome image settings and default settings
	// for color and grayscale images. 
	
	$doc = new PDFDoc($input_path.$input_filename.".pdf");
	$doc->InitSecurityHandler();

	$mono_image_settings = new MonoImageSettings();

	$mono_image_settings->SetCompressionMode(MonoImageSettings::e_jbig2);
	$mono_image_settings->ForceRecompression(true);

	$opt_settings = new OptimizerSettings();
	$opt_settings->SetMonoImageSettings($mono_image_settings);

	Optimizer::Optimize($doc, $opt_settings);

	$doc->Save($output_path.$input_filename."_opt3.pdf", SDFDoc::e_linearized);
	$doc->Close();
	
	// ----------------------------------------------------------------------
	// Example 4) Use Flattener to simplify content in this document
	// using default settings
	
	$doc = new PDFDoc($input_path."TigerText.pdf");
	$doc->InitSecurityHandler();
	
	$fl = new Flattener();
	// The following lines can increase the resolution of background
	// images.
	//$fl->SetDPI(300);
	//$fl->SetMaximumImagePixels(5000000);

	// This line can be used to output Flate compressed background
	// images rather than DCTDecode compressed images which is the default
	//$fl->SetPreferJPG(false);

	// In order to adjust thresholds for when text is Flattened
	// the following function can be used.
	//$fl->SetThreshold(Flattener::e_threshold_keep_most);

	// We use e_fast option here since it is usually preferable
	// to avoid Flattening simple pages in terms of size and 
	// rendering speed. If the desire is to simplify the 
	// document for processing such that it contains only text and
	// a background image e_simple should be used instead.
	$fl->Process($doc, Flattener::e_fast);
	$doc->Save($output_path."TigerText_flatten.pdf", SDFDoc::e_linearized);
	$doc->Close();

	// ----------------------------------------------------------------------
	// Example 5) Optimize a PDF for viewing using SaveViewerOptimized.
	
	$doc = new PDFDoc($input_path.$input_filename.".pdf");
	$doc->InitSecurityHandler();
	
	$opts = new ViewerOptimizedOptions();

	// set the maximum dimension (width or height) that thumbnails will have.
        $opts->SetThumbnailSize(1500);

	// set thumbnail rendering threshold. A number from 0 (include all thumbnails) to 100 (include only the first thumbnail) 
        // representing the complexity at which SaveViewerOptimized would include the thumbnail. 
        // By default it only produces thumbnails on the first and complex pages. 
        // The following line will produce thumbnails on every page.
        // opts->SetThumbnailRenderingThreshold(0); 

        $doc->SaveViewerOptimized($output_path.$input_filename."_SaveViewerOptimized.pdf", $opts);
	$doc->Close();
	PDFNet::Terminate();
?>
```

{% endcode %}
{% endtab %}

{% tab title="Ruby" %}
{% code lineNumbers="true" %}

```ruby
#---------------------------------------------------------------------------------------
# Copyright (c) 2001-2023 by Apryse Software Inc. All Rights Reserved.
# Consult LICENSE.txt regarding license information.
#---------------------------------------------------------------------------------------

require '../../../PDFNetC/Lib/PDFNetRuby'
include PDFNetRuby
require '../../LicenseKey/RUBY/LicenseKey'

$stdout.sync = true

#---------------------------------------------------------------------------------------
# The following sample illustrates how to reduce PDF file size using 'pdftron.PDF.Optimizer'.
# The sample also shows how to simplify and optimize PDF documents for viewing on mobile devices 
# and on the Web using 'pdftron.PDF.Flattener'.
#
# @note Both 'Optimizer' and 'Flattener' are separately licensable add-on options to the core PDFNet license.
#
# ----
#
# 'pdftron.PDF.Optimizer' can be used to optimize PDF documents by reducing the file size, removing 
# redundant information, and compressing data streams using the latest in image compression technology. 
#
# PDF Optimizer can compress and shrink PDF file size with the following operations:
# - Remove duplicated fonts, images, ICC profiles, and any other data stream. 
# - Optionally convert high-quality or print-ready PDF files to small, efficient and web-ready PDF. 
# - Optionally down-sample large images to a given resolution. 
# - Optionally compress or recompress PDF images using JBIG2 and JPEG2000 compression formats. 
# - Compress uncompressed streams and remove unused PDF objects. 
#
# 'pdftron.PDF.Flattener' can be used to speed-up PDF rendering on mobile devices and on the Web by 
# simplifying page content (e.g. flattening complex graphics into images) while maintaining vector text 
# whenever possible.
#
# Flattener can also be used to simplify process of writing custom converters from PDF to other formats. 
# In this case, Flattener can be used as first step in the conversion pipeline to reduce any PDF to a 
# very simple representation (e.g. vector text on top of a background image).
#---------------------------------------------------------------------------------------

	# Relative path to the folder containing the test files.
	input_path = "../../TestFiles/"
	output_path = "../../TestFiles/Output/"
	input_filename = "newsletter"
	
	# The first step in every application using PDFNet is to initialize the 
	# library and set the path to common PDF resources. The library is usually 
	# initialized only once, but calling Initialize multiple times is also fine.
	PDFNet.Initialize(PDFTronLicense.Key)
	
	#--------------------------------------------------------------------------------
	# Example 1) Simple optimization of a pdf with default settings.
	
	doc = PDFDoc.new(input_path + input_filename + ".pdf")
	doc.InitSecurityHandler
	Optimizer.Optimize(doc)
	
	doc.Save(output_path + input_filename + "_opt1.pdf", SDFDoc::E_linearized)
	doc.Close
	
	#--------------------------------------------------------------------------------
	# Example 2) Reduce image quality and use jpeg compression for
	# non monochrome images.	
	doc = PDFDoc.new(input_path + input_filename + ".pdf")
	doc.InitSecurityHandler
	image_settings = ImageSettings.new
	
	# low quality jpeg compression
	image_settings.SetCompressionMode(ImageSettings::E_jpeg)
	image_settings.SetQuality(1)
	
	# Set the output dpi to be standard screen resolution
	image_settings.SetImageDPI(144,96)
	
	# this option will recompress images not compressed with
	# jpeg compression and use the result if the new image
	# is smaller.
	image_settings.ForceRecompression(true)
	
	# this option is not commonly used since it can 
	# potentially lead to larger files.  It should be enabled
	# only if the output compression specified should be applied
	# to every image of a given type regardless of the output image size
	#image_settings.ForceChanges(True)

	opt_settings = OptimizerSettings.new
	opt_settings.SetColorImageSettings(image_settings)
	opt_settings.SetGrayscaleImageSettings(image_settings)
	
	# use the same settings for both color and grayscale images
	Optimizer.Optimize(doc, opt_settings)
	
	doc.Save(output_path + input_filename + "_opt2.pdf", SDFDoc::E_linearized)
	doc.Close
	
	#--------------------------------------------------------------------------------
	# Example 3) Use monochrome image settings and default settings
	# for color and grayscale images. 
	
	doc = PDFDoc.new(input_path + input_filename + ".pdf")
	doc.InitSecurityHandler

	mono_image_settings = MonoImageSettings.new
	
	mono_image_settings.SetCompressionMode(MonoImageSettings::E_jbig2)
	mono_image_settings.ForceRecompression(true)

	opt_settings = OptimizerSettings.new
	opt_settings.SetMonoImageSettings(mono_image_settings)
	
	Optimizer.Optimize(doc, opt_settings)
	doc.Save(output_path + input_filename + "_opt3.pdf", SDFDoc::E_linearized)
	doc.Close
	
	#----------------------------------------------------------------------
	# Example 4) Use Flattener to simplify content in this document
	# using default settings
	
	doc = PDFDoc.new(input_path + "TigerText.pdf")
	doc.InitSecurityHandler
	
	fl = Flattener.new
	
	# The following lines can increase the resolution of background
	# images.
	#fl.SetDPI(300)
	#fl.SetMaximumImagePixels(5000000)

	# This line can be used to output Flate compressed background
	# images rather than DCTDecode compressed images which is the default
	#fl.SetPreferJPG(false)

	# In order to adjust thresholds for when text is Flattened
	# the following function can be used.
	#fl.SetThreshold(Flattener::E_threshold_keep_most)

	# We use e_fast option here since it is usually preferable
	# to avoid Flattening simple pages in terms of size and 
	# rendering speed. If the desire is to simplify the 
	# document for processing such that it contains only text and
	# a background image e_simple should be used instead.
	fl.Process(doc, Flattener::E_fast)
	doc.Save(output_path + "TigerText_flatten.pdf", SDFDoc::E_linearized)
	doc.Close


	# ----------------------------------------------------------------------
	# Example 5) Optimize a PDF for viewing using SaveViewerOptimized.

	doc = PDFDoc.new(input_path + input_filename + ".pdf")
	doc.InitSecurityHandler

	opts = ViewerOptimizedOptions.new

	# set the maximum dimension (width or height) that thumbnails will have.
	opts.SetThumbnailSize(1500)

	# set thumbnail rendering threshold. A number from 0 (include all thumbnails) to 100 (include only the first thumbnail) 
	# representing the complexity at which SaveViewerOptimized would include the thumbnail. 
	# By default it only produces thumbnails on the first and complex pages. 
	# The following line will produce thumbnails on every page.
	# opts.SetThumbnailRenderingThreshold(0) 

	doc.SaveViewerOptimized(output_path + input_filename + "_SaveViewerOptimized.pdf", opts)
	doc.Close
	PDFNet.Terminate
```

{% endcode %}
{% endtab %}

{% tab title="Python" %}
{% code lineNumbers="true" %}

```python
#---------------------------------------------------------------------------------------
# Copyright (c) 2001-2023 by Apryse Software Inc. All Rights Reserved.
# Consult LICENSE.txt regarding license information.
#---------------------------------------------------------------------------------------

import site
site.addsitedir("../../../PDFNetC/Lib")
import sys
from PDFNetPython import *

sys.path.append("../../LicenseKey/PYTHON")
from LicenseKey import *

#---------------------------------------------------------------------------------------
# The following sample illustrates how to reduce PDF file size using 'pdftron.PDF.Optimizer'.
# The sample also shows how to simplify and optimize PDF documents for viewing on mobile devices 
# and on the Web using 'pdftron.PDF.Flattener'.
#
# @note Both 'Optimizer' and 'Flattener' are separately licensable add-on options to the core PDFNet license.
#
# ----
#
# 'pdftron.PDF.Optimizer' can be used to optimize PDF documents by reducing the file size, removing 
# redundant information, and compressing data streams using the latest in image compression technology. 
#
# PDF Optimizer can compress and shrink PDF file size with the following operations:
# - Remove duplicated fonts, images, ICC profiles, and any other data stream. 
# - Optionally convert high-quality or print-ready PDF files to small, efficient and web-ready PDF. 
# - Optionally down-sample large images to a given resolution. 
# - Optionally compress or recompress PDF images using JBIG2 and JPEG2000 compression formats. 
# - Compress uncompressed streams and remove unused PDF objects.
# ----
#
# 'pdftron.PDF.Flattener' can be used to speed-up PDF rendering on mobile devices and on the Web by 
# simplifying page content (e.g. flattening complex graphics into images) while maintaining vector text 
# whenever possible.
#
# Flattener can also be used to simplify process of writing custom converters from PDF to other formats. 
# In this case, Flattener can be used as first step in the conversion pipeline to reduce any PDF to a 
# very simple representation (e.g. vector text on top of a background image). 
#---------------------------------------------------------------------------------------

def main():
    
    # Relative path to the folder containing the test files.
    input_path = "../../TestFiles/"
    output_path = "../../TestFiles/Output/"
    input_filename = "newsletter"
    
    # The first step in every application using PDFNet is to initialize the 
    # library and set the path to common PDF resources. The library is usually 
    # initialized only once, but calling Initialize() multiple times is also fine.
    PDFNet.Initialize(LicenseKey)
    
    #--------------------------------------------------------------------------------
    # Example 1) Simple optimization of a pdf with default settings.
    
    doc = PDFDoc(input_path + input_filename + ".pdf")
    doc.InitSecurityHandler()
    Optimizer.Optimize(doc)
    
    doc.Save(output_path + input_filename + "_opt1.pdf", SDFDoc.e_linearized)
    doc.Close()
    
    #--------------------------------------------------------------------------------
    # Example 2) Reduce image quality and use jpeg compression for
    # non monochrome images.    
    doc = PDFDoc(input_path + input_filename + ".pdf")
    doc.InitSecurityHandler()
    image_settings = ImageSettings()
    
    # low quality jpeg compression
    image_settings.SetCompressionMode(ImageSettings.e_jpeg)
    image_settings.SetQuality(1)
    
    # Set the output dpi to be standard screen resolution
    image_settings.SetImageDPI(144,96)
    
    # this option will recompress images not compressed with
    # jpeg compression and use the result if the new image
    # is smaller.
    image_settings.ForceRecompression(True)
    
    # this option is not commonly used since it can 
    # potentially lead to larger files.  It should be enabled
    # only if the output compression specified should be applied
    # to every image of a given type regardless of the output image size
    #image_settings.ForceChanges(True)

    opt_settings = OptimizerSettings()
    opt_settings.SetColorImageSettings(image_settings)
    opt_settings.SetGrayscaleImageSettings(image_settings)

    # use the same settings for both color and grayscale images
    Optimizer.Optimize(doc, opt_settings)
    
    doc.Save(output_path + input_filename + "_opt2.pdf", SDFDoc.e_linearized)
    doc.Close()
    
    #--------------------------------------------------------------------------------
    # Example 3) Use monochrome image settings and default settings
    # for color and grayscale images. 
    
    doc = PDFDoc(input_path + input_filename + ".pdf")
    doc.InitSecurityHandler()

    mono_image_settings = MonoImageSettings()
    
    mono_image_settings.SetCompressionMode(MonoImageSettings.e_jbig2)
    mono_image_settings.ForceRecompression(True)

    opt_settings = OptimizerSettings()
    opt_settings.SetMonoImageSettings(mono_image_settings)
    
    Optimizer.Optimize(doc, opt_settings)
    doc.Save(output_path + input_filename + "_opt3.pdf", SDFDoc.e_linearized)
    doc.Close()
	
    # ----------------------------------------------------------------------
    # Example 4) Use Flattener to simplify content in this document
    # using default settings
    
    doc = PDFDoc(input_path + "TigerText.pdf")
    doc.InitSecurityHandler()
    
    fl = Flattener()
    # The following lines can increase the resolution of background
    # images.
    #fl.SetDPI(300)
    #fl.SetMaximumImagePixels(5000000)

    # This line can be used to output Flate compressed background
    # images rather than DCTDecode compressed images which is the default
    #fl.SetPreferJPG(false)

    # In order to adjust thresholds for when text is Flattened
    # the following function can be used.
    #fl.SetThreshold(Flattener.e_threshold_keep_most)

    # We use e_fast option here since it is usually preferable
    # to avoid Flattening simple pages in terms of size and 
    # rendering speed. If the desire is to simplify the 
    # document for processing such that it contains only text and
    # a background image e_simple should be used instead.
    fl.Process(doc, Flattener.e_fast)
    doc.Save(output_path + "TigerText_flatten.pdf", SDFDoc.e_linearized)
    doc.Close()

    # ----------------------------------------------------------------------
    # Example 5) Optimize a PDF for viewing using SaveViewerOptimized.
    
    doc = PDFDoc(input_path + input_filename + ".pdf")
    doc.InitSecurityHandler()
    
    opts = ViewerOptimizedOptions()

    # set the maximum dimension (width or height) that thumbnails will have.
    opts.SetThumbnailSize(1500)

    # set thumbnail rendering threshold. A number from 0 (include all thumbnails) to 100 (include only the first thumbnail) 
    # representing the complexity at which SaveViewerOptimized would include the thumbnail. 
    # By default it only produces thumbnails on the first and complex pages. 
    # The following line will produce thumbnails on every page.
    # opts.SetThumbnailRenderingThreshold(0) 

    doc.SaveViewerOptimized(output_path + input_filename + "_SaveViewerOptimized.pdf", opts)
    doc.Close()
    PDFNet.Terminate()
    
if __name__ == '__main__':
    main()
```

{% endcode %}
{% endtab %}

{% tab title="VB" %}
{% code lineNumbers="true" %}

```vb
'
' Copyright (c) 2001-2024 by Apryse Software Inc. All Rights Reserved.
'

Imports System

Imports pdftron
Imports pdftron.Common
Imports pdftron.Filters
Imports pdftron.SDF
Imports pdftron.PDF

Module OptimizerTestVB
    Dim pdfNetLoader As PDFNetLoader
    Sub New()
        pdfNetLoader = pdftron.PDFNetLoader.Instance()
    End Sub


    '---------------------------------------------------------------------------------------
    ' The following sample illustrates how to reduce PDF file size using 'pdftron.PDF.Optimizer'.
    ' The sample also shows how to simplify and optimize PDF documents for viewing on mobile devices 
    ' and on the Web using 'pdftron.PDF.Flattener'.
    '
    ' @note Both 'Optimizer' and 'Flattener' are separately licensable add-on options to the core PDFNet license.
    '
    ' ----
    '
    ' 'pdftron.PDF.Optimizer' can be used to optimize PDF documents by reducing the file size, removing 
    ' redundant information, and compressing data streams using the latest in image compression technology. 
    '
    ' PDF Optimizer can compress and shrink PDF file size with the following operations:
    ' - Remove duplicated fonts, images, ICC profiles, and any other data stream. 
    ' - Optionally convert high-quality or print-ready PDF files to small, efficient and web-ready PDF. 
    ' - Optionally down-sample large images to a given resolution. 
    ' - Optionally compress or recompress PDF images using JBIG2 and JPEG2000 compression formats. 
    ' - Compress uncompressed streams and remove unused PDF objects.
    ' ----
    '
    ' 'pdftron.PDF.Flattener' can be used to speed-up PDF rendering on mobile devices and on the Web by 
    ' simplifying page content (e.g. flattening complex graphics into images) while maintaining vector text 
    ' whenever possible.
    '
    ' Flattener can also be used to simplify process of writing custom converters from PDF to other formats. 
    ' In this case, Flattener can be used as first step in the conversion pipeline to reduce any PDF to a 
    ' very simple representation (e.g. vector text on top of a background image).
    '---------------------------------------------------------------------------------------
    Sub Main()
        PDFNet.Initialize(PDFTronLicense.Key)

        Dim input_path As String = "../../../../TestFiles/"
        Dim output_path As String = "../../../../TestFiles/Output/"
        Dim input_filename As String = "newsletter"

        '--------------------------------------------------------------------------------
        ' Example 1) Simple optimization of a pdf with default settings. 
        '
        Try
            Using doc As PDFDoc = New PDFDoc(input_path & input_filename & ".pdf")
                doc.InitSecurityHandler()
                Optimizer.Optimize(doc)
                doc.Save(output_path & input_filename & "_opt1.pdf", SDFDoc.SaveOptions.e_linearized)
            End Using
        Catch e As PDFNetException
            Console.WriteLine(e.Message)
        End Try

        '--------------------------------------------------------------------------------
        ' Example 2) Reduce image quality and use jpeg compression for
        ' non monochrome images.
        Try
            Using doc As PDFDoc = New PDFDoc(input_path & input_filename & ".pdf")
                doc.InitSecurityHandler()

                Dim image_settings As New Optimizer.ImageSettings

                ' low quality jpeg compression
                image_settings.SetCompressionMode(Optimizer.ImageSettings.CompressionMode.e_jpeg)
                image_settings.SetQuality(1)

                ' Set the output dpi to be standard screen resolution
                image_settings.SetImageDPI(144, 96)

                ' this option will recompress images not compressed with
                ' jpeg compression and use the result if the new image
                ' is smaller.
                image_settings.ForceRecompression(True)

                ' this option is not commonly used since it can 
                ' potentially lead to larger files.  It should be enabled
                ' only if the output compression specified should be applied
                ' to every image of a given type regardless of the output image size
                'image_settings.ForceChanges(true);

                ' use the same settings for both color and grayscale images
                Dim opt_settings As New Optimizer.OptimizerSettings
                opt_settings.SetColorImageSettings(image_settings)
                opt_settings.SetGrayscaleImageSettings(image_settings)

                Optimizer.Optimize(doc, opt_settings)

                doc.Save(output_path & input_filename & "_opt2.pdf", SDFDoc.SaveOptions.e_linearized)
            End Using
        Catch e As PDFNetException
            Console.WriteLine(e.Message)
        End Try

        '--------------------------------------------------------------------------------
        ' Example 3) Use monochrome image settings and default settings
        ' for color and grayscale images. 
        Try
            Using doc As PDFDoc = New PDFDoc(input_path & input_filename & ".pdf")
                doc.InitSecurityHandler()

                Dim mono_image_settings As New Optimizer.MonoImageSettings

                mono_image_settings.SetCompressionMode(Optimizer.MonoImageSettings.CompressionMode.e_jbig2)
                mono_image_settings.ForceRecompression(True)

                Dim opt_settings As New Optimizer.OptimizerSettings
                opt_settings.SetMonoImageSettings(mono_image_settings)

                Optimizer.Optimize(doc, opt_settings)

                doc.Save(output_path & input_filename & "_opt3.pdf", SDFDoc.SaveOptions.e_linearized)
            End Using
        Catch e As PDFNetException
            Console.WriteLine(e.Message)
        End Try

        '-------------------------------------------------------------------------------
        ' Example 4) Use Flattener to simplify content in this document
        ' using default settings
        Try
            Using doc As PDFDoc = New PDFDoc(input_path & "TigerText.pdf")
                doc.InitSecurityHandler()

                Dim fl As New Flattener

                ' The following lines can increase the resolution of background
                ' images.
                'fl.SetDPI(300)
                'fl.SetMaximumImagePixels(5000000)

                ' This line can be used to output Flate compressed background
                ' images rather than DCTDecode compressed images which is the default
                'fl.SetPreferJPG(false)

                ' In order to adjust thresholds for when text is Flattened
                ' the following function can be used.
                'fl.SetThreshold(Flattener.Threshold.e_keep_most)

                ' We use e_fast option here since it is usually preferable
                ' to avoid Flattening simple pages in terms of size and 
                ' rendering speed. If the desire is to simplify the 
                ' document for processing such that it contains only text and
                ' a background image e_simple should be used instead.
                fl.Process(doc, Flattener.FlattenMode.e_fast)

                doc.Save(output_path & "TigerText_flatten.pdf", SDFDoc.SaveOptions.e_linearized)
            End Using
        Catch e As PDFNetException
            Console.WriteLine(e.Message)
        End Try

        '-------------------------------------------------------------------------------
        ' Example 5)  Example 5) Optimize a PDF for viewing using SaveViewerOptimized.

        Try
            Using doc As PDFDoc = New PDFDoc(input_path & input_filename & ".pdf")
                doc.InitSecurityHandler()

                Dim opts As New ViewerOptimizedOptions

                ' set the maximum dimension (width or height) that thumbnails will have.
                opts.SetThumbnailSize(1500)

                ' set thumbnail rendering threshold. A number from 0 (include all thumbnails) to 100 (include only the first thumbnail) 
                ' representing the complexity at which SaveViewerOptimized would include the thumbnail. 
                ' By default it only produces thumbnails on the first and complex pages. 
                ' The following line will produce thumbnails on every page.
                ' opts.SetThumbnailRenderingThreshold(0); 
                doc.SaveViewerOptimized(output_path & input_filename & "_SaveViewerOptimized.pdf", opts)
            End Using
        Catch e As PDFNetException
            Console.WriteLine(e.Message)
        End Try
        PDFNet.Terminate()

    End Sub
End Module
```

{% endcode %}
{% endtab %}
{% endtabs %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.apryse.com/core/get-started/samples/optimizertest.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
