Compress PDFs - Optimizer - PHP Sample Code

Sample code for using Apryse SDK to reduce PDF file size by removing redundant information and compressing data streams using the latest in image compression technology. Samples provided in Python, C++, C#, Java, Node.js (JavaScript), PHP, Ruby and VB. Learn more about our Server SDK.

1<?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?>

Did you find this helpful?

Trial setup questions?

Ask experts on Discord

Need other help?

Contact Support

Pricing or product questions?

Contact Sales