Convert to PDF to PNG, JPG, BMP or TIFF - Go Sample Code

Sample code to use Apryse SDK's built-in rasterizer to render PDF images on the fly and save the resulting images in various raster image formats (such as PNG, JPEG, BMP, TIFF). Samples provided in Python, C++, C#, Java, Node.js (JavaScript), PHP, Ruby, Go and VB. Learn more about our Server SDK and PDF Conversion Library.

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 "fmt"
9 "strconv"
10 "os"
11 . "pdftron"
12)
13
14import "pdftron/Samples/LicenseKey/GO"
15
16// Relative path to the folder containing test files.
17var inputPath = "../../TestFiles/"
18var outputPath = "../../TestFiles/Output/"
19
20func main(){
21 // The first step in every application using PDFNet is to initialize the
22 // library and set the path to common PDF resources. The library is usually
23 // initialized only once, but calling Initialize() multiple times is also fine.
24 PDFNetInitialize(PDFTronLicense.Key)
25
26 // Optional: Set ICC color profiles to fine tune color conversion
27 // for PDF 'device' color spaces...
28
29 // PDFNetSetResourcesPath("../../../resources")
30 // PDFNetSetColorManagement()
31 // PDFNetSetDefaultDeviceCMYKProfile("D:/Misc/ICC/USWebCoatedSWOP.icc")
32 // PDFNetSetDefaultDeviceRGBProfile("AdobeRGB1998.icc") // will search in PDFNet resource folder.
33
34 // ----------------------------------------------------
35 // Optional: Set predefined font mappings to override default font
36 // substitution for documents with missing fonts...
37
38 // PDFNetAddFontSubst("StoneSans-Semibold", "C:/WINDOWS/Fonts/comic.ttf")
39 // PDFNetAddFontSubst("StoneSans", "comic.ttf") // search for 'comic.ttf' in PDFNet resource folder.
40 // PDFNetAddFontSubst(PDFNetE_Identity, "C:/WINDOWS/Fonts/arialuni.ttf")
41 // PDFNetAddFontSubst(PDFNetE_Japan1, "C:/Program Files/Adobe/Acrobat 7.0/Resource/CIDFont/KozMinProVI-Regular.otf")
42 // PDFNetAddFontSubst(PDFNetE_Japan2, "c:/myfonts/KozMinProVI-Regular.otf")
43 // PDFNetAddFontSubst(PDFNetE_Korea1, "AdobeMyungjoStd-Medium.otf")
44 // PDFNetAddFontSubst(PDFNetE_CNS1, "AdobeSongStd-Light.otf")
45 // PDFNetAddFontSubst(PDFNetE_GB1, "AdobeMingStd-Light.otf")
46
47 //Example 1) Convert the first page to PNG and TIFF at 92 DPI.
48
49 // PDFDraw class is used to rasterize PDF pages.
50 draw := NewPDFDraw()
51
52 //--------------------------------------------------------------------------------
53 // Example 1) Convert the first page to PNG and TIFF at 92 DPI.
54 // A three step tutorial to convert PDF page to an image.
55
56 // A) Open the PDF document.
57 doc := NewPDFDoc(inputPath + "tiger.pdf")
58
59 // Initialize the security handler, in case the PDF is encrypted.
60 doc.InitSecurityHandler()
61
62 // B) The output resolution is set to 92 DPI.
63 draw.SetDPI(92)
64
65 // C) Rasterize the first page in the document and save the result as PNG.
66 itr := doc.GetPageIterator()
67 draw.Export(itr.Current(), outputPath + "tiger_92dpi.png")
68
69 fmt.Println("Example 1: tiger_92dpi.png")
70
71 // Export the same page as TIFF
72 itr = doc.GetPageIterator()
73 draw.Export(itr.Current(), (outputPath + "tiger_92dpi.tif"), "TIFF")
74
75 //--------------------------------------------------------------------------------
76 // Example 2) Convert the all pages in a given document to JPEG at 72 DPI.
77
78 fmt.Println("Example 2:")
79
80 hintSet := NewObjSet() // A collection of rendering 'hits'.
81
82 doc = NewPDFDoc(inputPath + "newsletter.pdf")
83 // Initialize the security handler, in case the PDF is encrypted.
84 doc.InitSecurityHandler()
85
86 // Set the output resolution is to 72 DPI.
87 draw.SetDPI(72)
88
89 // Use optional encoder parameter to specify JPEG quality.
90 encoderParam := hintSet.CreateDict()
91 encoderParam.PutNumber("Quality", 80)
92
93 // Traverse all pages in the document.
94 itr = doc.GetPageIterator()
95 for itr.HasNext(){
96 filename := "newsletter" + strconv.Itoa(itr.Current().GetIndex()) + ".jpg"
97 fmt.Println(filename)
98 draw.Export(itr.Current(), outputPath + filename, "JPEG", encoderParam)
99 itr.Next()
100 }
101 fmt.Println("Done.")
102
103 // Examples 3-5
104 // Common code for remaining samples.
105 tigerDoc := NewPDFDoc(inputPath + "tiger.pdf")
106 // Initialize the security handler, in case the PDF is encrypted.
107 tigerDoc.InitSecurityHandler()
108 page := tigerDoc.GetPage(1)
109
110 //--------------------------------------------------------------------------------
111 // Example 3) Convert the first page to raw bitmap. Also, rotate the
112 // page 90 degrees and save the result as RAW.
113 draw.SetDPI(100) // Set the output resolution is to 100 DPI.
114 draw.SetRotate(PageE_90) // Rotate all pages 90 degrees clockwise.
115 bmp := draw.GetBitmap(page, PDFDrawE_rgb)
116 bmpBytes := make([]byte, int(bmp.GetBuffer().Size()))
117 buffVUC := bmp.GetBuffer()
118 for i := 0; i < int(buffVUC.Size()); i++{
119 bmpBytes[i] = buffVUC.Get(i)
120 }
121 // Save the raw RGB data to disk.
122 f, err := os.Create(outputPath + "tiger_100dpi_rot90.raw")
123
124 if err != nil {
125 fmt.Println(err)
126 }
127 defer f.Close()
128 _, err2 := f.Write(bmpBytes)
129 if err2 != nil {
130 fmt.Println(err2)
131 }
132
133 fmt.Println("Example 3: tiger_100dpi_rot90.raw")
134
135 draw.SetRotate(PageE_0) // Disable image rotation for remaining samples.
136
137 //--------------------------------------------------------------------------------
138 // Example 4) Convert PDF page to a fixed image size. Also illustrates some
139 // other features in PDFDraw class such as rotation, image stretching, exporting
140 // to grayscale, or monochrome.
141
142 // Initialize render 'grayHint' parameter, that is used to control the
143 // rendering process. In this case we tell the rasterizer to export the image as
144 // 1 Bit Per Component (BPC) image.
145 monoHint := hintSet.CreateDict()
146 monoHint.PutNumber("BPC", 1)
147
148 // SetImageSize can be used instead of SetDPI() to adjust page scaling
149 // dynamically so that given image fits into a buffer of given dimensions.
150 draw.SetImageSize(1000, 1000) // Set the output image to be 1000 wide and 1000 pixels tall
151 draw.Export(page, outputPath + "tiger_1000x1000.png", "PNG", monoHint)
152 fmt.Println("Example 4: tiger_1000x1000.png")
153
154 draw.SetImageSize(200, 400) // Set the output image to be 200 wide and 400 pixels tall
155 draw.SetRotate(PageE_180) // Rotate all pages 90 degrees clockwise
156
157 // 'grayHint' tells the rasterizer to export the image as grayscale.
158 grayHint := hintSet.CreateDict()
159 grayHint.PutName("ColorSpace", "Gray")
160
161 draw.Export(page, (outputPath + "tiger_200x400_rot180.png"), "PNG", grayHint)
162 fmt.Println("Example 4: tiger_200x400_rot180.png")
163
164 draw.SetImageSize(400, 200, false) // The third parameter sets 'preserve-aspect-ratio' to false
165 draw.SetRotate(PageE_0) // Disable image rotation
166 draw.Export(page, outputPath + "tiger_400x200_stretch.jpg", "JPEG")
167 fmt.Println("Example 4: tiger_400x200_stretch.jpg")
168
169 //--------------------------------------------------------------------------------
170 // Example 5) Zoom into a specific region of the page and rasterize the
171 // area at 200 DPI and as a thumbnail (i.e. a 50x50 pixel image).
172 zoomRect := NewRect(216.0, 522.0, 330.0, 600.0)
173 page.SetCropBox(zoomRect) // Set the page crop box.
174
175 // Select the crop region to be used for drawing.
176 draw.SetPageBox(PageE_crop)
177 draw.SetDPI(900) // Set the output image resolution to 900 DPI.
178 draw.Export(page, outputPath + "tiger_zoom_900dpi.png", "PNG")
179 fmt.Println("Example 5: tiger_zoom_900dpi.png")
180
181 // -------------------------------------------------------------------------------
182 // Example 6)
183 draw.SetImageSize(50, 50) // Set the thumbnail to be 50x50 pixel image.
184 draw.Export(page, outputPath + "tiger_zoom_50x50.png", "PNG")
185 fmt.Println("Example 6: tiger_zoom_50x50.png")
186
187 cmykHint := hintSet.CreateDict()
188 cmykHint.PutName("ColorSpace", "CMYK")
189
190 //--------------------------------------------------------------------------------
191 // Example 7) Convert the first PDF page to CMYK TIFF at 92 DPI.
192 // A three step tutorial to convert PDF page to an image
193 // A) Open the PDF document
194 doc = NewPDFDoc(inputPath + "tiger.pdf")
195 // Initialize the security handler, in case the PDF is encrypted.
196 doc.InitSecurityHandler()
197
198 // The output resolution is set to 92 DPI.
199 draw.SetDPI(92)
200
201 // C) Rasterize the first page in the document and save the result as TIFF.
202 pg := doc.GetPage(1)
203 draw.Export(pg, outputPath + "out1.tif", "TIFF", cmykHint)
204 fmt.Println("Example 7: out1.tif")
205
206 doc.Close()
207
208 // A) Open the PDF document.
209 doc = NewPDFDoc(inputPath + "tiger.pdf");
210 // Initialize the security handler, in case the PDF is encrypted.
211 doc.InitSecurityHandler();
212
213 // B) Get the page matrix
214 pg = doc.GetPage(1);
215 box := PageE_crop;
216 mtx := pg.GetDefaultMatrix(true, box);
217 // We want to render a quadrant, so use half of width and height
218 pgW := pg.GetPageWidth(box) / 2;
219 pgH := pg.GetPageHeight(box) / 2;
220
221 // C) Scale matrix from PDF space to buffer space
222 dpi := 96.0;
223 scale := dpi / 72.0; // PDF space is 72 dpi
224 bufW := int(scale * pgW);
225 bufH := int(scale * pgH);
226 bytesPerPixel := 4; // BGRA buffer
227 bufSize := bufW * bufH * bytesPerPixel;
228 mtx.Translate(0, -pgH); // translate by '-pgH' since we want south-west quadrant
229 mtx = NewMatrix2D(scale, 0.0, 00.0, scale, 00.0, 00.0).Multiply(mtx);
230
231 // D) Rasterize page into memory buffer, according to our parameters
232 rast := NewPDFRasterizer();
233 buf := rast.Rasterize(pg, bufW, bufH, bufW * bytesPerPixel, bytesPerPixel, true, mtx);
234 if(bufSize != 0 && buf.Size() != 0){
235 // buf now contains raw BGRA bitmap.
236 fmt.Println("Example 8: Successfully rasterized into memory buffer.");
237 }else{
238 fmt.Println("Example 8: Failed to rasterize into memory buffer.");
239 }
240
241 //--------------------------------------------------------------------------------
242 // Example 9) Export raster content to PNG using different image smoothing settings.
243 textDoc := NewPDFDoc(inputPath + "lorem_ipsum.pdf");
244 textDoc.InitSecurityHandler();
245
246 draw.SetImageSmoothing(false, false);
247 filename := "raster_text_no_smoothing.png";
248 draw.Export(textDoc.GetPageIterator().Current(), outputPath + filename);
249 fmt.Println("Example 9 a): " + filename + ". Done.");
250
251 filename = "raster_text_smoothed.png";
252 draw.SetImageSmoothing(true, false); // second argument = default quality bilinear resampling
253 draw.Export(textDoc.GetPageIterator().Current(), outputPath + filename);
254 fmt.Println("Example 9 b): " + filename + ". Done.");
255
256 filename = "raster_text_high_quality.png";
257 draw.SetImageSmoothing(true, true); // second argument = default quality bilinear resampling
258 draw.Export(textDoc.GetPageIterator().Current(), outputPath + filename);
259 fmt.Println("Example 9 c): " + filename + ". Done.");
260
261 //--------------------------------------------------------------------------------
262 // Example 10) Export separations directly, without conversion to an output colorspace
263
264 separationDoc := NewPDFDoc(inputPath + "op_blend_test.pdf");
265 separationDoc.InitSecurityHandler();
266 separationHint := hintSet.CreateDict();
267 separationHint.PutName("ColorSpace", "Separation");
268 draw.SetDPI(96);
269 draw.SetImageSmoothing(true, true);
270 draw.SetOverprint(PDFRasterizerE_op_on);
271
272 filename = "merged_separations.png";
273 draw.Export(separationDoc.GetPageIterator().Current(), outputPath + filename, "PNG");
274 fmt.Println("Example 10 a): " + filename + ". Done.");
275
276 filename = "separation";
277 draw.Export(separationDoc.GetPageIterator().Current(), outputPath + filename, "PNG", separationHint);
278 fmt.Println("Example 10 b): " + filename + "_[ink].png. Done.");
279
280 filename = "separation_NChannel.tif";
281 draw.Export(separationDoc.GetPageIterator().Current(), outputPath + filename, "TIFF", separationHint);
282 fmt.Println("Example 10 c): " + filename + ". Done.");
283 PDFNetTerminate()
284}

Did you find this helpful?

Trial setup questions?

Ask experts on Discord

Need other help?

Contact Support

Pricing or product questions?

Contact Sales