Compress PDFs - Optimizer - Go Sample Code

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

1//---------------------------------------------------------------------------------------
2// Copyright (c) 2001-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}

Did you find this helpful?

Trial setup questions?

Ask experts on Discord

Need other help?

Contact Support

Pricing or product questions?

Contact Sales