Sample C# 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). Learn more about our Server SDK and PDF Conversion Library.
1//---------------------------------------------------------------------------------------
2// Copyright (c) 2001-2024 by Apryse Software Inc. All Rights Reserved.
3// Consult legal.txt regarding legal and license information.
4//---------------------------------------------------------------------------------------
5
6using System;
7using System.Drawing;
8using System.Drawing.Imaging;
9using System.Runtime.InteropServices;
10
11using pdftron;
12using pdftron.Common;
13using pdftron.PDF;
14using pdftron.SDF;
15
16namespace PDFDrawTestCS
17{
18 /// <summary>
19 //---------------------------------------------------------------------------------------
20 // The following sample illustrates how to convert PDF documents to various raster image
21 // formats (such as PNG, JPEG, BMP, TIFF), as well as how to convert a PDF page to GDI+ Bitmap
22 // for further manipulation and/or display in WinForms applications.
23 //---------------------------------------------------------------------------------------
24 /// </summary>
25 class Class1
26 {
27 private static pdftron.PDFNetLoader pdfNetLoader = pdftron.PDFNetLoader.Instance();
28 static Class1() {}
29
30 /// <summary>
31 /// The main entry point for the application.
32 /// </summary>
33 static void Main(string[] args)
34 {
35 // The first step in every application using PDFNet is to initialize the
36 // library and set the path to common PDF resources. The library is usually
37 // initialized only once, but calling Initialize() multiple times is also fine.
38 PDFNet.Initialize(PDFTronLicense.Key);
39
40 try
41 {
42 // Optional: Set ICC color profiles to fine tune color conversion
43 // for PDF 'device' color spaces. You can use your own ICC profiles.
44 // Standard Adobe color profiles can be download from Adobes site:
45 // http://www.adobe.com/support/downloads/iccprofiles/iccprofiles_win.html
46 //
47 // Simply drop all *.icc files in PDFNet resource folder or you specify
48 // the full pathname.
49 //---
50 // PDFNet.SetResourcesPath("../../../../../resources");
51 // PDFNet.SetColorManagement();
52 // PDFNet.SetDefaultDeviceCMYKProfile("USWebCoatedSWOP.icc"); // will search in PDFNet resource folder.
53 // PDFNet.SetDefaultDeviceRGBProfile("AdobeRGB1998.icc");
54
55 // Optional: Set predefined font mappings to override default font
56 // substitution for documents with missing fonts. For example:
57 //---
58 // PDFNet.AddFontSubst("StoneSans-Semibold", "C:/WINDOWS/Fonts/comic.ttf");
59 // PDFNet.AddFontSubst("StoneSans", "comic.ttf"); // search for 'comic.ttf' in PDFNet resource folder.
60 // PDFNet.AddFontSubst(PDFNet.CharacterOrdering.e_Identity, "C:/WINDOWS/Fonts/arialuni.ttf");
61 // PDFNet.AddFontSubst(PDFNet.CharacterOrdering.e_Japan1, "C:/Program Files/Adobe/Acrobat 7.0/Resource/CIDFont/KozMinProVI-Regular.otf");
62 // PDFNet.AddFontSubst(PDFNet.CharacterOrdering.e_Japan2, "c:/myfonts/KozMinProVI-Regular.otf");
63 //
64 // If fonts are in PDFNet resource folder, it is not necessary to specify
65 // the full path name. For example,
66 //---
67 // PDFNet.AddFontSubst(PDFNet.CharacterOrdering.e_Korea1, "AdobeMyungjoStd-Medium.otf");
68 // PDFNet.AddFontSubst(PDFNet.CharacterOrdering.e_CNS1, "AdobeSongStd-Light.otf");
69 // PDFNet.AddFontSubst(PDFNet.CharacterOrdering.e_GB1, "AdobeMingStd-Light.otf");
70 }
71 catch (Exception)
72 {
73 Console.WriteLine("The specified color profile was not found.");
74 }
75
76 // Relative path to the folder containing test files.
77 string input_path = "../../../../TestFiles/";
78 string output_path = "../../../../TestFiles/Output/";
79
80
81 using (PDFDraw draw = new PDFDraw())
82 {
83 //--------------------------------------------------------------------------------
84 // Example 1) Convert the first PDF page to PNG at 92 DPI.
85 // A three step tutorial to convert PDF page to an image.
86 try
87 {
88 // A) Open the PDF document.
89 using (PDFDoc doc = new PDFDoc(input_path + "tiger.pdf"))
90 {
91 // Initialize the security handler, in case the PDF is encrypted.
92 doc.InitSecurityHandler();
93
94 // B) The output resolution is set to 92 DPI.
95 draw.SetDPI(92);
96
97 // C) Rasterize the first page in the document and save the result as PNG.
98 Page pg = doc.GetPage(1);
99 draw.Export(pg, output_path + "tiger_92dpi.png");
100
101 Console.WriteLine("Example 1: tiger_92dpi.png");
102
103 // Export the same page as TIFF
104 draw.Export(pg, output_path + "tiger_92dpi.tif", "TIFF");
105 }
106 }
107 catch (PDFNetException e) {
108 Console.WriteLine(e.Message);
109 }
110
111 //--------------------------------------------------------------------------------
112 // Example 2) Convert the all pages in a given document to JPEG at 72 DPI.
113 ObjSet hint_set=new ObjSet(); // A collection of rendering 'hits'.
114 Console.WriteLine("Example 2:");
115 try
116 {
117 using (PDFDoc doc = new PDFDoc(input_path + "newsletter.pdf"))
118 {
119 // Initialize the security handler, in case the PDF is encrypted.
120 doc.InitSecurityHandler();
121
122 draw.SetDPI(72); // Set the output resolution is to 72 DPI.
123
124 // Use optional encoder parameter to specify JPEG quality.
125 Obj encoder_param = hint_set.CreateDict();
126 encoder_param.PutNumber("Quality", 80);
127
128 // Traverse all pages in the document.
129 for (PageIterator itr=doc.GetPageIterator(); itr.HasNext(); itr.Next())
130 {
131 string output_filename = string.Format("newsletter{0:d}.jpg", itr.GetPageNumber());
132 Console.WriteLine("newsletter{0:d}.jpg", itr.GetPageNumber());
133 draw.Export(itr.Current(), output_path + output_filename, "JPEG", encoder_param);
134 }
135 }
136
137 Console.WriteLine("Done.");
138 }
139 catch (PDFNetException e)
140 {
141 Console.WriteLine(e.Message);
142 }
143
144 try // Examples 3-6
145 {
146 // Common code for remaining samples.
147 using (PDFDoc tiger_doc = new PDFDoc(input_path + "tiger.pdf"))
148 {
149 // Initialize the security handler, in case the PDF is encrypted.
150 tiger_doc.InitSecurityHandler();
151 Page page = tiger_doc.GetPage(1);
152
153 //--------------------------------------------------------------------------------
154 // Example 3) Convert the first page to GDI+ Bitmap. Also, rotate the
155 // page 90 degrees and save the result as RAW.
156 draw.SetDPI(100); // Set the output resolution is to 100 DPI.
157 draw.SetRotate(Page.Rotate.e_90); // Rotate all pages 90 degrees clockwise.
158
159 Bitmap bmp = draw.GetBitmap(page);
160
161 // Save the raw RGB data to disk.
162 string filename = "tiger_100dpi_rot90.raw";
163
164 System.IO.File.WriteAllBytes(output_path + filename, BitmapToByteArray(bmp));
165
166 Console.WriteLine("Example 3: tiger_100dpi_rot90.raw");
167 draw.SetRotate(Page.Rotate.e_0); // Disable image rotation for remaining samples.
168
169 //--------------------------------------------------------------------------------
170 // Example 4) Convert PDF page to a fixed image size. Also illustrates some
171 // other features in PDFDraw class such as rotation, image stretching, exporting
172 // to grayscale, or monochrome.
173
174 // Initialize render 'gray_hint' parameter, that is used to control the
175 // rendering process. In this case we tell the rasterizer to export the image as
176 // 1 Bit Per Component (BPC) image.
177 Obj mono_hint=hint_set.CreateDict();
178 mono_hint.PutNumber("BPC", 1);
179
180 // SetImageSize can be used instead of SetDPI() to adjust page scaling
181 // dynamically so that given image fits into a buffer of given dimensions.
182 draw.SetImageSize(1000, 1000); // Set the output image to be 1000 wide and 1000 pixels tall
183 draw.Export(page, output_path + "tiger_1000x1000.png", "PNG", mono_hint);
184 Console.WriteLine("Example 4: tiger_1000x1000.png");
185
186 draw.SetImageSize(200, 400); // Set the output image to be 200 wide and 300 pixels tall
187 draw.SetRotate(Page.Rotate.e_180); // Rotate all pages 90 degrees clockwise.
188
189 // 'gray_hint' tells the rasterizer to export the image as grayscale.
190 Obj gray_hint=hint_set.CreateDict();
191 gray_hint.PutName("ColorSpace", "Gray");
192
193 draw.Export(page, output_path + "tiger_200x400_rot180.png", "PNG", gray_hint);
194 Console.WriteLine("Example 4: tiger_200x400_rot180.png");
195
196 draw.SetImageSize(400, 200, false); // The third parameter sets 'preserve-aspect-ratio' to false.
197 draw.SetRotate(Page.Rotate.e_0); // Disable image rotation.
198 draw.Export(page, output_path + "tiger_400x200_stretch.jpg", "JPEG");
199 Console.WriteLine("Example 4: tiger_400x200_stretch.jpg");
200
201 //--------------------------------------------------------------------------------
202 // Example 5) Zoom into a specific region of the page and rasterize the
203 // area at 200 DPI and as a thumbnail (i.e. a 50x50 pixel image).
204 page.SetCropBox(new Rect(216, 522, 330, 600)); // Set the page crop box.
205
206 // Select the crop region to be used for drawing.
207 draw.SetPageBox(Page.Box.e_crop);
208 draw.SetDPI(900); // Set the output image resolution to 900 DPI.
209 draw.Export(page, output_path + "tiger_zoom_900dpi.png", "PNG");
210 Console.WriteLine("Example 5: tiger_zoom_900dpi.png");
211
212 // -------------------------------------------------------------------------------
213 // Example 6)
214 draw.SetImageSize(50, 50); // Set the thumbnail to be 50x50 pixel image.
215 draw.Export(page, output_path + "tiger_zoom_50x50.png", "PNG");
216 Console.WriteLine("Example 6: tiger_zoom_50x50.png");
217 }
218 }
219 catch (PDFNetException e)
220 {
221 Console.WriteLine(e.Message);
222 }
223
224 Obj cmyk_hint = hint_set.CreateDict();
225 cmyk_hint.PutName("ColorSpace", "CMYK");
226
227 //--------------------------------------------------------------------------------
228 // Example 7) Convert the first PDF page to CMYK TIFF at 92 DPI.
229 // A three step tutorial to convert PDF page to an image.
230 try
231 {
232 // A) Open the PDF document.
233 using (PDFDoc doc = new PDFDoc(input_path + "tiger.pdf"))
234 {
235 // Initialize the security handler, in case the PDF is encrypted.
236 doc.InitSecurityHandler();
237
238 // B) The output resolution is set to 92 DPI.
239 draw.SetDPI(92);
240
241 // C) Rasterize the first page in the document and save the result as TIFF.
242 Page pg = doc.GetPage(1);
243 draw.Export(pg, output_path + "out1.tif", "TIFF", cmyk_hint);
244 Console.WriteLine("Example 7: out1.tif");
245 }
246 }
247 catch (PDFNetException e)
248 {
249 Console.WriteLine(e.Message);
250 }
251
252 //--------------------------------------------------------------------------------
253 // Example 8) Export raster content to PNG using different image smoothing settings.
254 try
255 {
256 // A) Open the PDF document.
257 using (PDFDoc doc = new PDFDoc(input_path + "tiger.pdf"))
258 {
259 // Initialize the security handler, in case the PDF is encrypted.
260 doc.InitSecurityHandler();
261
262 // B) Get the page matrix
263 Page pg = doc.GetPage(1);
264 Page.Box box = Page.Box.e_crop;
265 Matrix2D mtx = pg.GetDefaultMatrix(true, box);
266 // We want to render a quadrant, so use half of width and height
267 double pg_w = pg.GetPageWidth(box) / 2;
268 double pg_h = pg.GetPageHeight(box) / 2;
269
270 // C) Scale matrix from PDF space to buffer space
271 double dpi = 96.0;
272 double scale = dpi / 72.0; // PDF space is 72 dpi
273 int buf_w = (int) (Math.Floor(scale * pg_w));
274 int buf_h = (int) (Math.Floor(scale * pg_h));
275 int bytes_per_pixel = 4; // BGRA buffer
276 int buf_size = buf_w * buf_h * bytes_per_pixel;
277 mtx.Translate(0, -pg_h); // translate by '-pg_h' since we want south-west quadrant
278 mtx = new Matrix2D(scale, 0, 0, scale, 0, 0) * mtx;
279
280 // D) Rasterize page into memory buffer, according to our parameters
281 byte[] buf;
282 PDFRasterizer rast = new PDFRasterizer();
283 buf = rast.Rasterize(pg, buf_w, buf_h, buf_w * bytes_per_pixel, bytes_per_pixel, true, mtx);
284
285 // buf now contains raw BGRA bitmap.
286 Console.WriteLine("Example 8: Successfully rasterized into memory buffer.");
287 }
288 }
289 catch (PDFNetException e)
290 {
291 Console.WriteLine(e.Message);
292 }
293 //--------------------------------------------------------------------------------
294 // Example 9) Export raster content to PNG using different image smoothing settings.
295 try
296 {
297 using (PDFDoc text_doc = new PDFDoc(input_path + "lorem_ipsum.pdf"))
298 {
299 text_doc.InitSecurityHandler();
300
301 draw.SetImageSmoothing(false, false);
302 string filename = "raster_text_no_smoothing.png";
303 draw.Export(text_doc.GetPageIterator().Current(), output_path + filename);
304 Console.WriteLine("Example 9 a): " + filename + ". Done.");
305
306 filename = "raster_text_smoothed.png";
307 draw.SetImageSmoothing(true, false /*default quality bilinear resampling*/);
308 draw.Export(text_doc.GetPageIterator().Current(), output_path + filename);
309 Console.WriteLine("Example 9 b): " + filename + ". Done.");
310
311 filename = "raster_text_high_quality.png";
312 draw.SetImageSmoothing(true, true /*high quality area resampling*/);
313 draw.Export(text_doc.GetPageIterator().Current(), output_path + filename);
314 Console.WriteLine("Example 9 c): " + filename + ". Done.");
315 }
316 }
317 catch (Exception e)
318 {
319 Console.WriteLine(e.Message);
320 }
321
322 //--------------------------------------------------------------------------------
323 // Example 10) Export separations directly, without conversion to an output colorspace
324 try
325 {
326 using (PDFDoc separation_doc = new PDFDoc(input_path + "op_blend_test.pdf"))
327 {
328 separation_doc.InitSecurityHandler();
329 Obj separation_hint = hint_set.CreateDict();
330 separation_hint.PutName("ColorSpace", "Separation");
331 draw.SetDPI(96);
332 draw.SetImageSmoothing(true, true);
333 draw.SetOverprint(PDFRasterizer.OverprintPreviewMode.e_op_on);
334
335 string filename = "merged_separations.png";
336 draw.Export(separation_doc.GetPageIterator().Current(), output_path + filename, "PNG");
337 Console.WriteLine("Example 10 a): " + filename + ". Done.");
338
339 filename = "separation";
340 draw.Export(separation_doc.GetPageIterator().Current(), output_path + filename, "PNG", separation_hint);
341 Console.WriteLine("Example 10 b): " + filename + "_[ink].png. Done.");
342
343 filename = "separation_NChannel.tif";
344 draw.Export(separation_doc.GetPageIterator().Current(), output_path + filename, "TIFF", separation_hint);
345 Console.WriteLine("Example 10 c): " + filename + ". Done.");
346 }
347 }
348 catch (PDFNetException e)
349 {
350 Console.WriteLine(e.Message);
351 }
352
353 } // using PDFDraw
354 PDFNet.Terminate();
355 }
356
357 public static byte[] BitmapToByteArray(Bitmap bitmap)
358 {
359
360 BitmapData bmpdata = null;
361
362 try
363 {
364 bmpdata = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, bitmap.PixelFormat);
365 int numbytes = bmpdata.Stride * bitmap.Height;
366 byte[] bytedata = new byte[numbytes];
367 IntPtr ptr = bmpdata.Scan0;
368
369 Marshal.Copy(ptr, bytedata, 0, numbytes);
370
371 return bytedata;
372 }
373 finally
374 {
375 if (bmpdata != null)
376 bitmap.UnlockBits(bmpdata);
377 }
378 } // end
379 }
380}
1//---------------------------------------------------------------------------------------
2// Copyright (c) 2001-2024 by Apryse Software Inc. All Rights Reserved.
3// Consult legal.txt regarding legal and license information.
4//---------------------------------------------------------------------------------------
5
6#include <PDF/PDFNet.h>
7#include <PDF/PDFDoc.h>
8#include <PDF/PDFDraw.h>
9#include <Filters/MappedFile.h>
10#include <Filters/FilterWriter.h>
11#include <cmath>
12#include <string>
13#include <iostream>
14#include <fstream>
15#include <sstream>
16#include <SDF/ObjSet.h>
17#include "../../LicenseKey/CPP/LicenseKey.h"
18
19using namespace std;
20using namespace pdftron;
21using namespace PDF;
22using namespace Filters;
23
24//---------------------------------------------------------------------------------------
25// The following sample illustrates how to convert PDF documents to various raster image
26// formats (such as PNG, JPEG, BMP, TIFF, etc), as well as how to convert a PDF page to
27// GDI+ Bitmap for further manipulation and/or display in WinForms applications.
28//---------------------------------------------------------------------------------------
29int main(int argc, char *argv[])
30{
31 try
32 {
33 // The first step in every application using PDFNet is to initialize the
34 // library and set the path to common PDF resources. The library is usually
35 // initialized only once, but calling Initialize() multiple times is also fine.
36 PDFNet::Initialize(LicenseKey);
37
38 // Optional: Set ICC color profiles to fine tune color conversion
39 // for PDF 'device' color spaces...
40
41 // PDFNet::SetResourcesPath("../../../resources");
42 // PDFNet::SetColorManagement(PDFNet::e_lcms);
43 // PDFNet::SetDefaultDeviceCMYKProfile("D:/Misc/ICC/USWebCoatedSWOP.icc");
44 // PDFNet::SetDefaultDeviceRGBProfile("AdobeRGB1998.icc"); // will search in PDFNet resource folder.
45
46 // ----------------------------------------------------
47 // Optional: Set predefined font mappings to override default font
48 // substitution for documents with missing fonts...
49
50 // PDFNet::AddFontSubst("StoneSans-Semibold", "C:/WINDOWS/Fonts/comic.ttf");
51 // PDFNet::AddFontSubst("StoneSans", "comic.ttf"); // search for 'comic.ttf' in PDFNet resource folder.
52 // PDFNet::AddFontSubst(PDFNet::e_Identity, "C:/WINDOWS/Fonts/arialuni.ttf");
53 // PDFNet::AddFontSubst(PDFNet::e_Japan1, "C:/Program Files/Adobe/Acrobat 7.0/Resource/CIDFont/KozMinProVI-Regular.otf");
54 // PDFNet::AddFontSubst(PDFNet::e_Japan2, "c:/myfonts/KozMinProVI-Regular.otf");
55 // PDFNet::AddFontSubst(PDFNet::e_Korea1, "AdobeMyungjoStd-Medium.otf");
56 // PDFNet::AddFontSubst(PDFNet::e_CNS1, "AdobeSongStd-Light.otf");
57 // PDFNet::AddFontSubst(PDFNet::e_GB1, "AdobeMingStd-Light.otf");
58
59 // Relative path to the folder containing test files.
60 string input_path = "../../TestFiles/";
61 string output_path = "../../TestFiles/Output/";
62
63 PDFDraw draw; // PDFDraw class is used to rasterize PDF pages.
64
65 //--------------------------------------------------------------------------------
66 // Example 1) Convert the first page to PNG and TIFF at 92 DPI.
67 // A three step tutorial to convert PDF page to an image.
68 try
69 {
70 // A) Open the PDF document.
71 PDFDoc doc((input_path + "tiger.pdf").c_str());
72
73 // Initialize the security handler, in case the PDF is encrypted.
74 doc.InitSecurityHandler();
75
76 // B) The output resolution is set to 92 DPI.
77 draw.SetDPI(92);
78
79 // C) Rasterize the first page in the document and save the result as PNG.
80 draw.Export(doc.GetPageIterator().Current(), (output_path + "tiger_92dpi.png").c_str());
81
82 cout << "Example 1: tiger_92dpi.png" << endl;
83
84 // Export the same page as TIFF
85 draw.Export(doc.GetPageIterator().Current(), (output_path + "tiger_92dpi.tif").c_str(), "TIFF");
86 }
87 catch(Common::Exception& e)
88 {
89 cout << e << endl;
90 }
91 catch(...)
92 {
93 cout << "Unknown Exception" << endl;
94 }
95
96 //--------------------------------------------------------------------------------
97 // Example 2) Convert the all pages in a given document to JPEG at 72 DPI.
98 cout << "Example 2:" << endl;
99 SDF::ObjSet hint_set; // A collection of rendering 'hits'.
100 try
101 {
102 PDFDoc doc((input_path + "newsletter.pdf").c_str());
103 // Initialize the security handler, in case the PDF is encrypted.
104 doc.InitSecurityHandler();
105
106 draw.SetDPI(72); // Set the output resolution is to 72 DPI.
107
108 // Use optional encoder parameter to specify JPEG quality.
109 SDF::Obj encoder_param=hint_set.CreateDict();
110 encoder_param.PutNumber("Quality", 80);
111
112 // Traverse all pages in the document.
113 for (PageIterator itr=doc.GetPageIterator(); itr.HasNext(); itr.Next()) {
114 ostringstream sstm;
115 sstm << output_path << "newsletter" << itr.Current().GetIndex() << ".jpg";
116 string path = sstm.str();
117 cout << "newsletter" << itr.Current().GetIndex() << ".jpg" << endl;
118
119 draw.Export(itr.Current(), path.c_str(), "JPEG", encoder_param);
120 }
121
122 cout << "Done." << endl;
123 }
124 catch(Common::Exception& e)
125 {
126 cout << e << endl;
127 }
128 catch(...)
129 {
130 cout << "Unknown Exception" << endl;
131 }
132
133
134 // Examples 3-6
135 try
136 {
137 // Common code for remaining samples.
138 PDFDoc tiger_doc((input_path + "tiger.pdf").c_str());
139 // Initialize the security handler, in case the PDF is encrypted.
140 tiger_doc.InitSecurityHandler();
141 Page page = tiger_doc.GetPage(1);
142
143 //--------------------------------------------------------------------------------
144 // Example 3) Convert the first page to raw bitmap. Also, rotate the
145 // page 90 degrees and save the result as RAW.
146 draw.SetDPI(100); // Set the output resolution is to 100 DPI.
147 draw.SetRotate(Page::e_90); // Rotate all pages 90 degrees clockwise.
148
149 int width = 0, height = 0, stride = 0;
150 double dpi = 0.0;
151 const UChar* buf = draw.GetBitmap(page, width, height, stride, dpi, PDFDraw::e_rgb);
152
153
154 // Save the raw RGB data to disk.
155 ofstream outfile((output_path + "tiger_100dpi_rot90.raw").c_str(), ofstream::binary);
156 outfile.write((char*)buf, height * stride);
157 outfile.close();
158
159
160 cout << "Example 3: tiger_100dpi_rot90.raw" << endl;
161 draw.SetRotate(Page::e_0); // Disable image rotation for remaining samples.
162
163 //--------------------------------------------------------------------------------
164 // Example 4) Convert PDF page to a fixed image size. Also illustrates some
165 // other features in PDFDraw class such as rotation, image stretching, exporting
166 // to grayscale, or monochrome.
167
168 // Initialize render 'gray_hint' parameter, that is used to control the
169 // rendering process. In this case we tell the rasterizer to export the image as
170 // 1 Bit Per Component (BPC) image.
171 SDF::Obj mono_hint=hint_set.CreateDict();
172 mono_hint.PutNumber("BPC", 1);
173
174 // SetImageSize can be used instead of SetDPI() to adjust page scaling
175 // dynamically so that given image fits into a buffer of given dimensions.
176 draw.SetImageSize(1000, 1000); // Set the output image to be 1000 wide and 1000 pixels tall
177 draw.Export(page, (output_path + "tiger_1000x1000.png").c_str(), "PNG", mono_hint);
178 cout << "Example 4: tiger_1000x1000.png" << endl;
179
180 draw.SetImageSize(200, 400); // Set the output image to be 200 wide and 300 pixels tall
181 draw.SetRotate(Page::e_180); // Rotate all pages 90 degrees clockwise.
182
183 // 'gray_hint' tells the rasterizer to export the image as grayscale.
184 SDF::Obj gray_hint=hint_set.CreateDict();
185 gray_hint.PutName("ColorSpace", "Gray");
186
187 draw.Export(page, (output_path + "tiger_200x400_rot180.png").c_str(), "PNG", gray_hint);
188 cout << "Example 4: tiger_200x400_rot180.png" << endl;
189
190 draw.SetImageSize(400, 200, false); // The third parameter sets 'preserve-aspect-ratio' to false.
191 draw.SetRotate(Page::e_0); // Disable image rotation.
192 draw.Export(page, (output_path + "tiger_400x200_stretch.jpg").c_str(), "JPEG");
193 cout << "Example 4: tiger_400x200_stretch.jpg" << endl;
194
195 //--------------------------------------------------------------------------------
196 // Example 5) Zoom into a specific region of the page and rasterize the
197 // area at 200 DPI and as a thumbnail (i.e. a 50x50 pixel image).
198 Rect zoom_rect(216, 522, 330, 600);
199 page.SetCropBox(zoom_rect); // Set the page crop box.
200
201 // Select the crop region to be used for drawing.
202 draw.SetPageBox(Page::e_crop);
203 draw.SetDPI(900); // Set the output image resolution to 900 DPI.
204 draw.Export(page, (output_path + "tiger_zoom_900dpi.png").c_str(), "PNG");
205 cout << "Example 5: tiger_zoom_900dpi.png" << endl;
206
207 // -------------------------------------------------------------------------------
208 // Example 6)
209 draw.SetImageSize(50, 50); // Set the thumbnail to be 50x50 pixel image.
210 draw.Export(page, (output_path + "tiger_zoom_50x50.png").c_str(), "PNG");
211 cout << "Example 6: tiger_zoom_50x50.png" << endl;
212 }
213 catch(Common::Exception& e)
214 {
215 cout << e << endl;
216 }
217 catch(...)
218 {
219 cout << "Unknown Exception" << endl;
220 }
221
222
223
224 //--------------------------------------------------------------------------------
225 // Example 7) Convert the first PDF page to CMYK TIFF at 92 DPI.
226 // A three step tutorial to convert PDF page to an image
227 try
228 {
229 pdftron::SDF::Obj cmyk_hint = hint_set.CreateDict();
230 cmyk_hint.PutName("ColorSpace", "CMYK");
231 // A) Open the PDF document.
232 PDFDoc doc((input_path + "tiger.pdf").c_str());
233 // Initialize the security handler, in case the PDF is encrypted.
234 doc.InitSecurityHandler();
235
236 // B) The output resolution is set to 92 DPI.
237 draw.SetDPI(92);
238
239 // C) Rasterize the first page in the document and save the result as TIFF.
240 Page pg = doc.GetPage(1);
241 draw.Export(pg, output_path + "out1.tif", "TIFF", cmyk_hint);
242 cout << "Example 7: out1.tif" << endl;
243 }
244 catch(Common::Exception& e)
245 {
246 cout << e << endl;
247 }
248 catch(...)
249 {
250 cout << "Unknown Exception" << endl;
251 }
252
253 //--------------------------------------------------------------------------------
254 // Example 8) PDFRasterizer can be used for more complex rendering tasks, such as
255 // strip by strip or tiled document rendering. In particular, it is useful for
256 // cases where you cannot simply modify the page crop box (interactive viewing,
257 // parallel rendering). This example shows how you can rasterize the south-west
258 // quadrant of a page.
259 try
260 {
261 // A) Open the PDF document.
262 PDFDoc doc((input_path + "tiger.pdf").c_str());
263 // Initialize the security handler, in case the PDF is encrypted.
264 doc.InitSecurityHandler();
265
266 // B) Get the page matrix
267 Page pg = doc.GetPage(1);
268 Page::Box box = Page::e_crop;
269 Common::Matrix2D mtx = pg.GetDefaultMatrix(true, box);
270 // We want to render a quadrant, so use half of width and height
271 const double pg_w = pg.GetPageWidth(box) / 2;
272 const double pg_h = pg.GetPageHeight(box) / 2;
273
274 // C) Scale matrix from PDF space to buffer space
275 const double dpi = 96.0;
276 const double scale = dpi / 72.0; // PDF space is 72 dpi
277 const int buf_w = static_cast<int>(floor(scale * pg_w));
278 const int buf_h = static_cast<int>(floor(scale * pg_h));
279 const int bytes_per_pixel = 4; // BGRA buffer
280 const int buf_size = buf_w * buf_h * bytes_per_pixel;
281 mtx.Translate(0, -pg_h); // translate by '-pg_h' since we want south-west quadrant
282 mtx = Common::Matrix2D(scale, 0, 0, scale, 0, 0) * mtx;
283
284 // D) Rasterize page into memory buffer, according to our parameters
285 std::vector<unsigned char> buf;
286 PDFRasterizer rast;
287 buf = rast.Rasterize(pg, buf_w, buf_h, buf_w * bytes_per_pixel, bytes_per_pixel, true, mtx);
288
289 // buf now contains raw BGRA bitmap.
290 cout << "Example 8: Successfully rasterized into memory buffer." << endl;
291 }
292 catch(Common::Exception& e)
293 {
294 cout << e << endl;
295 }
296 catch (...) {
297 cout << "Unknown Exception" << endl;
298 }
299 //--------------------------------------------------------------------------------
300 // Example 9) Export raster content to PNG using different image smoothing settings.
301 try
302 {
303 PDFDoc text_doc((input_path + "lorem_ipsum.pdf").c_str());
304 text_doc.InitSecurityHandler();
305
306 draw.SetImageSmoothing(false, false);
307 string filename = "raster_text_no_smoothing.png";
308 draw.Export(text_doc.GetPageIterator().Current(), (output_path + filename).c_str());
309 cout << "Example 9 a): " << filename << ". Done." << endl;
310
311 filename = "raster_text_smoothed.png";
312 draw.SetImageSmoothing(true, false /*default quality bilinear resampling*/);
313 draw.Export(text_doc.GetPageIterator().Current(), (output_path + filename).c_str());
314 cout << "Example 9 b): " << filename << ". Done." << endl;
315
316 filename = "raster_text_high_quality.png";
317 draw.SetImageSmoothing(true, true /*high quality area resampling*/);
318 draw.Export(text_doc.GetPageIterator().Current(), (output_path + filename).c_str());
319 cout << "Example 9 c): " << filename << ". Done." << endl;
320 }
321 catch(Common::Exception& e)
322 {
323 cout << e << endl;
324 }
325 catch (...) {
326 cout << "Unknown Exception" << endl;
327 }
328 //--------------------------------------------------------------------------------
329 // Example 10) Export separations directly, without conversion to an output colorspace
330 try
331 {
332 PDFDoc separation_doc((input_path + "op_blend_test.pdf").c_str());
333 separation_doc.InitSecurityHandler();
334 pdftron::SDF::Obj separation_hint = hint_set.CreateDict();
335 separation_hint.PutName("ColorSpace", "Separation");
336 draw.SetDPI(96);
337 draw.SetImageSmoothing(true, true);
338 draw.SetOverprint(PDFRasterizer::e_op_on);
339
340 string filename = "merged_separations.png";
341 draw.Export(separation_doc.GetPageIterator().Current(), (output_path + filename).c_str(), "PNG");
342 cout << "Example 10 a): " << filename <<". Done." << endl;
343
344 filename = "separation";
345 draw.Export(separation_doc.GetPageIterator().Current(), (output_path + filename).c_str(), "PNG", separation_hint);
346 cout << "Example 10 b): " << filename <<"_[ink].png. Done." << endl;
347
348 filename = "separation_NChannel.tif";
349 draw.Export(separation_doc.GetPageIterator().Current(), (output_path + filename).c_str(), "TIFF", separation_hint);
350 cout << "Example 10 c): " << filename << ". Done." << endl;
351 }
352 catch(Common::Exception& e)
353 {
354 cout << e << endl;
355 }
356 catch (...) {
357 cout << "Unknown Exception" << endl;
358 }
359 PDFNet::Terminate();
360 }
361 catch(Common::Exception& e)
362 {
363 cout << e << endl;
364 }
365 catch (...) {
366 cout << "Unknown Exception" << endl;
367 }
368
369 return 0;
370}
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}
1//---------------------------------------------------------------------------------------
2// Copyright (c) 2001-2024 by Apryse Software Inc. All Rights Reserved.
3// Consult legal.txt regarding legal and license information.
4//---------------------------------------------------------------------------------------
5
6import java.awt.image.PixelGrabber;
7
8//import com.pdftron.filters.FilterWriter;
9//import com.pdftron.filters.MappedFile;
10import com.pdftron.pdf.*;
11import com.pdftron.sdf.Obj;
12import com.pdftron.sdf.ObjSet;
13import com.pdftron.common.Matrix2D;
14import com.pdftron.common.PDFNetException;
15
16import java.io.FileOutputStream;
17import java.io.File;
18import java.nio.ByteBuffer;
19import java.nio.IntBuffer;
20
21//---------------------------------------------------------------------------------------
22// The following sample illustrates how to convert PDF documents to various raster image
23// formats (such as PNG, JPEG, BMP, TIFF, etc), as well as how to convert a PDF page to
24// GDI+ Bitmap for further manipulation and/or display in WinForms applications.
25//---------------------------------------------------------------------------------------
26public class PDFDrawTest {
27 public static void main(String[] args) {
28 try {
29 // The first step in every application using PDFNet is to initialize the
30 // library and set the path to common PDF resources. The library is usually
31 // initialized only once, but calling Initialize() multiple times is also fine.
32 PDFNet.initialize(PDFTronLicense.Key());
33
34 // Optional: Set ICC color profiles to fine tune color conversion
35 // for PDF 'device' color spaces...
36
37 //PDFNet.setResourcesPath("../../../resources");
38 //PDFNet.setColorManagement();
39 //PDFNet.setDefaultDeviceCMYKProfile("D:/Misc/ICC/USWebCoatedSWOP.icc");
40 //PDFNet.setDefaultDeviceRGBProfile("AdobeRGB1998.icc"); // will search in PDFNet resource folder.
41
42 // ----------------------------------------------------
43 // Optional: Set predefined font mappings to override default font
44 // substitution for documents with missing fonts...
45
46 // PDFNet.addFontSubst("StoneSans-Semibold", "C:/WINDOWS/Fonts/comic.ttf");
47 // PDFNet.addFontSubst("StoneSans", "comic.ttf"); // search for 'comic.ttf' in PDFNet resource folder.
48 // PDFNet.addFontSubst(PDFNet.e_Identity, "C:/WINDOWS/Fonts/arialuni.ttf");
49 // PDFNet.addFontSubst(PDFNet.e_Japan1, "C:/Program Files/Adobe/Acrobat 7.0/Resource/CIDFont/KozMinProVI-Regular.otf");
50 // PDFNet.addFontSubst(PDFNet.e_Japan2, "c:/myfonts/KozMinProVI-Regular.otf");
51 // PDFNet.addFontSubst(PDFNet.e_Korea1, "AdobeMyungjoStd-Medium.otf");
52 // PDFNet.addFontSubst(PDFNet.e_CNS1, "AdobeSongStd-Light.otf");
53 // PDFNet.addFontSubst(PDFNet.e_GB1, "AdobeMingStd-Light.otf");
54
55 // Relative path to the folder containing test files.
56 String input_path = "../../TestFiles/";
57 String output_path = "../../TestFiles/Output/";
58
59 PDFDraw draw = new PDFDraw(); // PDFDraw class is used to rasterize PDF pages.
60 ObjSet hint_set = new ObjSet();
61
62 //--------------------------------------------------------------------------------
63 // Example 1) Convert the first page to PNG and TIFF at 92 DPI.
64 // A three step tutorial to convert PDF page to an image.
65 try (PDFDoc doc = new PDFDoc((input_path + "tiger.pdf"))) {
66 // A) Open the PDF document.
67
68 // Initialize the security handler, in case the PDF is encrypted.
69 doc.initSecurityHandler();
70
71 // B) The output resolution is set to 92 DPI.
72 draw.setDPI(92);
73
74 // C) Rasterize the first page in the document and save the result as PNG.
75 Page pg = doc.getPage(1);
76 draw.export(pg, (output_path + "tiger_92dpi.png"));
77 // output "tiger_92dpi.png"
78
79 System.out.println("Example 1: tiger_92dpi.png");
80
81 // Export the same page as TIFF
82 draw.export(pg, (output_path + "tiger_92dpi.tif"), "TIFF");
83 // output "tiger_92dpi.tif"
84 } catch (Exception e) {
85 e.printStackTrace();
86 }
87
88 //--------------------------------------------------------------------------------
89 // Example 2) Convert the all pages in a given document to JPEG at 72 DPI.
90 System.out.println("Example 2:");
91 try (PDFDoc doc = new PDFDoc((input_path + "newsletter.pdf"))) {
92 // Initialize the security handler, in case the PDF is encrypted.
93 doc.initSecurityHandler();
94
95 draw.setDPI(72); // Set the output resolution is to 72 DPI.
96
97 // Use optional encoder parameter to specify JPEG quality.
98 Obj encoder_param = hint_set.createDict();
99 encoder_param.putNumber("Quality", 80);
100
101 // Traverse all pages in the document.
102 for (PageIterator itr = doc.getPageIterator(); itr.hasNext(); ) {
103 Page current = itr.next();
104 String filename = "newsletter" + current.getIndex() + ".jpg";
105 System.out.println(filename);
106 draw.export(current, output_path + filename, "JPEG", encoder_param);
107 }
108
109 System.out.println("Done.");
110 } catch (Exception e) {
111 e.printStackTrace();
112 }
113
114 FileOutputStream fos = null;
115 // Examples 3-5
116 try (PDFDoc tiger_doc = new PDFDoc((input_path + "tiger.pdf"))) {
117 // Common code for remaining samples.
118 // Initialize the security handler, in case the PDF is encrypted.
119 tiger_doc.initSecurityHandler();
120 Page page = tiger_doc.getPageIterator().next();
121
122 //--------------------------------------------------------------------------------
123 // Example 3) Convert the first page to raw bitmap. Also, rotate the
124 // page 90 degrees and save the result as RAW.
125 draw.setDPI(100); // Set the output resolution is to 100 DPI.
126 draw.setRotate(Page.e_90); // Rotate all pages 90 degrees clockwise.
127
128 // create a Java image
129 java.awt.Image image = draw.getBitmap(page);
130
131 //
132 int width = image.getWidth(null), height = image.getHeight(null);
133 int[] arr = new int[width * height];
134 PixelGrabber pg = new PixelGrabber(image, 0, 0, width, height, arr, 0, width);
135 pg.grabPixels();
136
137 // convert to byte array
138 ByteBuffer byteBuffer = ByteBuffer.allocate(arr.length * 4);
139 IntBuffer intBuffer = byteBuffer.asIntBuffer();
140 intBuffer.put(arr);
141 byte[] rawByteArray = byteBuffer.array();
142 // finally write the file
143 fos = new FileOutputStream(output_path + "tiger_100dpi_rot90.raw");
144 fos.write(rawByteArray);
145 System.out.println("Example 3: tiger_100dpi_rot90.raw");
146
147 draw.setRotate(Page.e_0); // Disable image rotation for remaining samples.
148
149 //--------------------------------------------------------------------------------
150 // Example 4) Convert PDF page to a fixed image size. Also illustrates some
151 // other features in PDFDraw class such as rotation, image stretching, exporting
152 // to grayscale, or monochrome.
153
154 // Initialize render 'gray_hint' parameter, that is used to control the
155 // rendering process. In this case we tell the rasterizer to export the image as
156 // 1 Bit Per Component (BPC) image.
157 Obj mono_hint = hint_set.createDict();
158 mono_hint.putNumber("BPC", 1);
159
160 // SetImageSize can be used instead of SetDPI() to adjust page scaling
161 // dynamically so that given image fits into a buffer of given dimensions.
162 draw.setImageSize(1000, 1000); // Set the output image to be 1000 wide and 1000 pixels tall
163
164 draw.export(page, (output_path + "tiger_1000x1000.png"), "PNG", mono_hint);
165 System.out.println("Example 4: tiger_1000x1000.png");
166
167 draw.setImageSize(200, 400); // Set the output image to be 200 wide and 300 pixels tall
168 draw.setRotate(Page.e_180); // Rotate all pages 90 degrees clockwise.
169
170 // 'gray_hint' tells the rasterizer to export the image as grayscale.
171 Obj gray_hint = hint_set.createDict();
172 gray_hint.putName("ColorSpace", "Gray");
173
174 draw.export(page, (output_path + "tiger_200x400_rot180.png"), "PNG", gray_hint);
175 System.out.println("Example 4: tiger_200x400_rot180.png");
176
177 draw.setImageSize(400, 200, false); // The third parameter sets 'preserve-aspect-ratio' to false.
178 draw.setRotate(Page.e_0); // Disable image rotation.
179 draw.export(page, (output_path + "tiger_400x200_stretch.jpg"), "JPEG");
180 // output "tiger_400x200_stretch.jpg"
181 System.out.println("Example 4: tiger_400x200_stretch.jpg");
182
183 //--------------------------------------------------------------------------------
184 // Example 5) Zoom into a specific region of the page and rasterize the
185 // area at 200 DPI and as a thumbnail (i.e. a 50x50 pixel image).
186 Rect zoom_rect = new Rect(216, 522, 330, 600);
187 page.setCropBox(zoom_rect); // Set the page crop box.
188
189 // Select the crop region to be used for drawing.
190 draw.setPageBox(Page.e_crop);
191 draw.setDPI(900); // Set the output image resolution to 900 DPI.
192 draw.export(page, (output_path + "tiger_zoom_900dpi.png"), "PNG");
193 // output "tiger_zoom_900dpi.png"
194 System.out.println("Example 5: tiger_zoom_900dpi.png");
195
196 // -------------------------------------------------------------------------------
197 // Example 6)
198 draw.setImageSize(50, 50); // Set the thumbnail to be 50x50 pixel image.
199 draw.export(page, (output_path + "tiger_zoom_50x50.png"), "PNG");
200 // output "tiger_zoom_50x50.png"
201 System.out.println("Example 6: tiger_zoom_50x50.png");
202 } catch (Exception e) {
203 e.printStackTrace();
204 } finally {
205 if (fos != null) {
206 try {
207 fos.close();
208 } catch (Exception ignored) {
209 }
210 }
211 }
212
213 Obj cmyk_hint = hint_set.createDict();
214 cmyk_hint.putName("ColorSpace", "CMYK");
215
216 //--------------------------------------------------------------------------------
217 // Example 7) Convert the first PDF page to CMYK TIFF at 92 DPI.
218 // A three step tutorial to convert PDF page to an image
219 try (PDFDoc doc = new PDFDoc(input_path + "tiger.pdf")) {
220 // A) Open the PDF document.
221
222 // Initialize the security handler, in case the PDF is encrypted.
223 doc.initSecurityHandler();
224
225 // B) The output resolution is set to 92 DPI.
226 draw.setDPI(92);
227
228 // C) Rasterize the first page in the document and save the result as TIFF.
229 Page pg = doc.getPage(1);
230 draw.export(pg, output_path + "out1.tif", "TIFF", cmyk_hint);
231 // output "out1.tif"
232 System.out.println("Example 7: out1.tif");
233 } catch (Exception e) {
234 e.printStackTrace();
235 }
236
237 //--------------------------------------------------------------------------------
238 // Example 8) PDFRasterizer can be used for more complex rendering tasks, such as
239 // strip by strip or tiled document rendering. In particular, it is useful for
240 // cases where you cannot simply modify the page crop box (interactive viewing,
241 // parallel rendering). This example shows how you can rasterize the south-west
242 // quadrant of a page.
243 try (PDFDoc doc = new PDFDoc(input_path + "tiger.pdf")) {
244 // A) Open the PDF document.
245 // Initialize the security handler, in case the PDF is encrypted.
246 doc.initSecurityHandler();
247
248 // B) Get the page matrix
249 Page pg = doc.getPage(1);
250 int box = Page.e_crop;
251 Matrix2D mtx = pg.getDefaultMatrix(true, box, 0);
252 // We want to render a quadrant, so use half of width and height
253 double pg_w = pg.getPageWidth(box) / 2;
254 double pg_h = pg.getPageHeight(box) / 2;
255
256 // C) Scale matrix from PDF space to buffer space
257 double dpi = 96.0;
258 double scale = dpi / 72.0; // PDF space is 72 dpi
259 double buf_w = Math.floor(scale * pg_w);
260 double buf_h = Math.floor(scale * pg_h);
261 int bytes_per_pixel = 4; // BGRA buffer
262 mtx.translate(0, -pg_h); // translate by '-pg_h' since we want south-west quadrant
263 mtx = (new Matrix2D(scale, 0, 0, scale, 0, 0)).multiply(mtx);
264
265 // D) Rasterize page into memory buffer, according to our parameters
266 PDFRasterizer rast = new PDFRasterizer();
267 byte[] buf = rast.rasterize(pg, (int) buf_w, (int) buf_h, (int) buf_w * bytes_per_pixel, bytes_per_pixel, true, mtx, null);
268
269 System.out.println("Example 8: Successfully rasterized into memory buffer.");
270 } catch (Exception e) {
271 e.printStackTrace();
272 }
273
274 //--------------------------------------------------------------------------------
275 // Example 9) Export raster content to PNG using different image smoothing settings.
276 try (PDFDoc text_doc = new PDFDoc(input_path + "lorem_ipsum.pdf")) {
277 text_doc.initSecurityHandler();
278
279 draw.setImageSmoothing(false, false);
280 String filename = "raster_text_no_smoothing.png";
281 draw.export(text_doc.getPageIterator().next(), output_path + filename);
282 System.out.println("Example 9 a): " + filename + ". Done.");
283
284 filename = "raster_text_smoothed.png";
285 draw.setImageSmoothing(true, false /*default quality bilinear resampling*/);
286 draw.export(text_doc.getPageIterator().next(), output_path + filename);
287 System.out.println("Example 9 b): " + filename + ". Done.");
288
289 filename = "raster_text_high_quality.png";
290 draw.setImageSmoothing(true, true /*high quality area resampling*/);
291 draw.export(text_doc.getPageIterator().next(), output_path + filename);
292 System.out.println("Example 9 c): " + filename + ". Done.");
293 } catch (Exception e) {
294 e.printStackTrace();
295 }
296
297
298 //--------------------------------------------------------------------------------
299 // Example 10) Export separations directly, without conversion to an output colorspace
300 try (PDFDoc separation_doc = new PDFDoc(input_path + "op_blend_test.pdf")) {
301 separation_doc.initSecurityHandler();
302
303 Obj separation_hint = hint_set.createDict();
304 separation_hint.putName("ColorSpace", "Separation");
305 draw.setDPI(96);
306 draw.setImageSmoothing(true, true);
307 // set overprint preview to always on
308 draw.setOverprint(1);
309
310 String filename = new String("merged_separations.png");
311 draw.export(separation_doc.getPage(1), output_path + filename, "PNG");
312 System.out.println("Example 10 a): " + filename + ". Done.");
313
314 filename = new String("separation");
315 draw.export(separation_doc.getPage(1), output_path + filename, "PNG", separation_hint);
316 System.out.println("Example 10 b): " + filename + "_[ink].png. Done.");
317
318 filename = new String("separation_NChannel.tif");
319 draw.export(separation_doc.getPage(1), output_path + filename, "TIFF", separation_hint);
320 System.out.println("Example 10 c): " + filename + ". Done.");
321 } catch (Exception e) {
322 e.printStackTrace();
323 }
324
325 // Calling Terminate when PDFNet is no longer in use is a good practice, but
326 // is not required.
327 PDFNet.terminate();
328 } catch (Exception e) {
329 e.printStackTrace();
330 }
331 }
332}
1//---------------------------------------------------------------------------------------
2// Copyright (c) 2001-2024 by Apryse Software Inc. All Rights Reserved.
3// Consult legal.txt regarding legal and license information.
4//---------------------------------------------------------------------------------------
5
6//---------------------------------------------------------------------------------------
7// The following sample illustrates how to convert PDF documents to various raster image
8// formats (such as PNG, JPEG, BMP, TIFF, etc), as well as how to convert a PDF page to
9// GDI+ Bitmap for further manipulation and/or display in WinForms applications.
10//---------------------------------------------------------------------------------------
11
12const fs = require('fs');
13const { PDFNet } = require('@pdftron/pdfnet-node');
14const PDFTronLicense = require('../LicenseKey/LicenseKey');
15
16((exports) => {
17
18 exports.runPDFDrawTest = () => {
19
20 const main = async () => {
21 // Relative path to the folder containing test files.
22 const inputPath = '../TestFiles/';
23 const outputPath = inputPath + 'Output/';
24
25 try {
26
27 // Optional: Set ICC color profiles to fine tune color conversion
28 // for PDF 'device' color spaces...
29
30 // PDFNet.setResourcesPath('../resources');
31 // PDFNet.setColorManagement(PDFNet.CMSType.e_lcms);
32 // PDFNet.setDefaultDeviceCMYKProfile('D:/Misc/ICC/USWebCoatedSWOP.icc');
33 // PDFNet.setDefaultDeviceRGBProfile('AdobeRGB1998.icc'); // will search in PDFNet resource folder.
34
35 // ----------------------------------------------------
36 // Optional: Set predefined font mappings to override default font
37 // substitution for documents with missing fonts...
38
39 // PDFNet.addFontSubst('StoneSans-Semibold', 'C:/WINDOWS/Fonts/comic.ttf');
40 // PDFNet.addFontSubst('StoneSans', 'comic.ttf'); // search for 'comic.ttf' in PDFNet resource folder.
41 // PDFNet.addFontSubst(PDFNet.CharacterOrdering.e_Identity, 'C:/WINDOWS/Fonts/arialuni.ttf');
42 // PDFNet.addFontSubst(PDFNet.CharacterOrdering.e_Japan1, 'C:/Program Files/Adobe/Acrobat 7.0/Resource/CIDFont/KozMinProVI-Regular.otf');
43 // PDFNet.addFontSubst(PDFNet.CharacterOrdering.e_Japan2, 'c:/myfonts/KozMinProVI-Regular.otf');
44 // PDFNet.addFontSubst(PDFNet.CharacterOrdering.e_Korea1, 'AdobeMyungjoStd-Medium.otf');
45 // PDFNet.addFontSubst(PDFNet.CharacterOrdering.e_CNS1, 'AdobeSongStd-Light.otf');
46 // PDFNet.addFontSubst(PDFNet.CharacterOrdering.e_GB1, 'AdobeMingStd-Light.otf');
47
48 const draw = await PDFNet.PDFDraw.create(); // PDFDraw class is used to rasterize PDF pages.
49
50 //--------------------------------------------------------------------------------
51 // Example 1) Convert the first page to PNG and TIFF at 92 DPI.
52 // A three step tutorial to convert PDF page to an image.
53 try {
54 // A) Open the PDF document.
55 const doc = await PDFNet.PDFDoc.createFromFilePath(inputPath + 'tiger.pdf');
56
57 // Initialize the security handler, in case the PDF is encrypted.
58 doc.initSecurityHandler();
59
60 // B) The output resolution is set to 92 DPI.
61 draw.setDPI(92);
62
63 const firstPage = await (await doc.getPageIterator()).current();
64 // C) Rasterize the first page in the document and save the result as PNG.
65 await draw.export(firstPage, outputPath + 'tiger_92dpi.png');
66
67 console.log('Example 1: tiger_92dpi.png');
68
69 // Export the same page as TIFF
70 await draw.export(firstPage, outputPath + 'tiger_92dpi.tif', 'TIFF');
71 } catch (err) {
72 console.log(err);
73 }
74
75 //--------------------------------------------------------------------------------
76 // Example 2) Convert the all pages in a given document to JPEG at 72 DPI.
77 console.log('Example 2:');
78 const hint_set = await PDFNet.ObjSet.create(); // A collection of rendering 'hits'.
79 try {
80 const doc = await PDFNet.PDFDoc.createFromFilePath(inputPath + 'newsletter.pdf');
81 // Initialize the security handler, in case the PDF is encrypted.
82 doc.initSecurityHandler();
83
84 draw.setDPI(72); // Set the output resolution is to 72 DPI.
85
86 // Use optional encoder parameter to specify JPEG quality.
87 const encoderParam = await hint_set.createDict();
88 await encoderParam.putNumber('Quality', 80);
89
90 // Traverse all pages in the document.
91 for (const itr = await doc.getPageIterator(); await itr.hasNext(); await itr.next()) {
92 const currPage = await itr.current();
93 const currPageIdx = await currPage.getIndex();
94 const path = outputPath + 'newsletter' + currPageIdx + '.jpg';
95 console.log('newsletter' + currPageIdx + '.jpg');
96
97 await draw.export(currPage, path, 'JPEG', encoderParam);
98 }
99 console.log('Done.');
100 } catch (err) {
101 console.log(err);
102 }
103
104 // Examples 3-6
105 try {
106 // Common code for remaining samples.
107 const tiger_doc = await PDFNet.PDFDoc.createFromFilePath(inputPath + 'tiger.pdf');
108 // Initialize the security handler, in case the PDF is encrypted.
109 tiger_doc.initSecurityHandler();
110 const page = await tiger_doc.getPage(1);
111
112 //--------------------------------------------------------------------------------
113 // Example 3) Convert the first page to raw bitmap. Also, rotate the
114 // page 90 degrees and save the result as RAW.
115 draw.setDPI(100); // Set the output resolution is to 100 DPI.
116 draw.setRotate(PDFNet.Page.Rotate.e_90); // Rotate all pages 90 degrees clockwise.
117
118 const bitmapInfo = await draw.getBitmap(page, PDFNet.PDFDraw.PixelFormat.e_rgb, false);
119 const buf = Buffer.from(bitmapInfo.buf, 0, bitmapInfo.height * bitmapInfo.stride)
120
121 // Save the raw RGB data to disk.
122 fs.appendFileSync(outputPath + 'tiger_100dpi_rot90.raw', buf, 'binary');
123
124 console.log('Example 3: tiger_100dpi_rot90.raw');
125 draw.setRotate(PDFNet.Page.Rotate.e_0); // Disable image rotation for remaining samples.
126
127 //--------------------------------------------------------------------------------
128 // Example 4) Convert PDF page to a fixed image size. Also illustrates some
129 // other features in PDFDraw class such as rotation, image stretching, exporting
130 // to grayscale, or monochrome.
131
132 // Initialize render 'gray_hint' parameter, that is used to control the
133 // rendering process. In this case we tell the rasterizer to export the image as
134 // 1 Bit Per Component (BPC) image.
135 const mono_hint = await hint_set.createDict();
136 await mono_hint.putNumber('BPC', 1);
137
138 // SetImageSize can be used instead of SetDPI() to adjust page scaling
139 // dynamically so that given image fits into a buffer of given dimensions.
140 draw.setImageSize(1000, 1000); // Set the output image to be 1000 wide and 1000 pixels tall
141 draw.export(page, outputPath + 'tiger_1000x1000.png', 'PNG', mono_hint);
142 console.log('Example 4: tiger_1000x1000.png');
143
144 draw.setImageSize(200, 400); // Set the output image to be 200 wide and 300 pixels tall
145 draw.setRotate(PDFNet.Page.Rotate.e_180); // Rotate all pages 90 degrees clockwise.
146
147 // 'gray_hint' tells the rasterizer to export the image as grayscale.
148 const gray_hint = await hint_set.createDict();
149 await gray_hint.putName('ColorSpace', 'Gray');
150
151 await draw.export(page, outputPath + 'tiger_200x400_rot180.png', 'PNG', gray_hint);
152 console.log('Example 4: tiger_200x400_rot180.png');
153
154 draw.setImageSize(400, 200, false); // The third parameter sets 'preserve-aspect-ratio' to false.
155 draw.setRotate(PDFNet.Page.Rotate.e_0); // Disable image rotation.
156 await draw.export(page, outputPath + 'tiger_400x200_stretch.jpg', 'JPEG');
157 console.log('Example 4: tiger_400x200_stretch.jpg');
158
159 //--------------------------------------------------------------------------------
160 // Example 5) Zoom into a specific region of the page and rasterize the
161 // area at 200 DPI and as a thumbnail (i.e. a 50x50 pixel image).
162 const zoom_rect = await PDFNet.Rect.init(216, 522, 330, 600);
163 await page.setCropBox(zoom_rect); // Set the page crop box.
164
165 // Select the crop region to be used for drawing.
166 draw.setPageBox(PDFNet.Page.Box.e_crop);
167 draw.setDPI(900); // Set the output image resolution to 900 DPI.
168 await draw.export(page, outputPath + 'tiger_zoom_900dpi.png', 'PNG');
169 console.log('Example 5: tiger_zoom_900dpi.png');
170
171 // -------------------------------------------------------------------------------
172 // Example 6)
173 draw.setImageSize(50, 50); // Set the thumbnail to be 50x50 pixel image.
174 await draw.export(page, outputPath + 'tiger_zoom_50x50.png', 'PNG');
175 console.log('Example 6: tiger_zoom_50x50.png');
176 } catch (err) {
177 console.log(err);
178 }
179
180 //--------------------------------------------------------------------------------
181 // Example 7) Convert the first PDF page to CMYK TIFF at 92 DPI.
182 // A three step tutorial to convert PDF page to an image
183 try {
184 const cmyk_hint = await hint_set.createDict();
185 await cmyk_hint.putName('ColorSpace', 'CMYK');
186 // A) Open the PDF document.
187 const doc = await PDFNet.PDFDoc.createFromFilePath(inputPath + 'tiger.pdf');
188 // Initialize the security handler, in case the PDF is encrypted.
189 doc.initSecurityHandler();
190
191 // B) The output resolution is set to 92 DPI.
192 draw.setDPI(92);
193
194 // C) Rasterize the first page in the document and save the result as TIFF.
195 const pg = await doc.getPage(1);
196 await draw.export(pg, outputPath + 'out1.tif', 'TIFF', cmyk_hint);
197 console.log('Example 7: out1.tif');
198 } catch (err) {
199 console.log(err);
200 }
201
202 //--------------------------------------------------------------------------------
203 // Example 8) PDFRasterizer can be used for more complex rendering tasks, such as
204 // strip by strip or tiled document rendering. In particular, it is useful for
205 // cases where you cannot simply modify the page crop box (interactive viewing,
206 // parallel rendering). This example shows how you can rasterize the south-west
207 // quadrant of a page.
208 try {
209 // A) Open the PDF document.
210 const doc = await PDFNet.PDFDoc.createFromFilePath(inputPath + 'tiger.pdf');
211 // Initialize the security handler, in case the PDF is encrypted.
212 doc.initSecurityHandler();
213
214 // B) Get the page matrix
215 const pg = await doc.getPage(1);
216 const box = PDFNet.Page.Rotate.e_crop;
217 let mtx = await pg.getDefaultMatrix(true, box);
218 // We want to render a quadrant, so use half of width and height
219 const pg_w = await pg.getPageWidth(box) / 2;
220 const pg_h = await pg.getPageHeight(box) / 2;
221
222 // C) Scale matrix from PDF space to buffer space
223 const dpi = 96.0;
224 const scale = dpi / 72.0; // PDF space is 72 dpi
225 const buf_w = Math.floor(scale * pg_w);
226 const buf_h = Math.floor(scale * pg_h);
227 const bytes_per_pixel = 4; // BGRA buffer
228 await mtx.translate(0, -pg_h); // translate by '-pg_h' since we want south-west quadrant
229 const scale_mtx = await PDFNet.Matrix2D.create(scale, 0, 0, scale, 0, 0);
230 await scale_mtx.multiply(mtx);
231 mtx = scale_mtx;
232
233 // D) Rasterize page into memory buffer, according to our parameters
234 const rast = await PDFNet.PDFRasterizer.create();
235 const buf = await rast.rasterize(pg, buf_w, buf_h, buf_w * bytes_per_pixel, bytes_per_pixel, true, mtx);
236
237 // buf now contains raw BGRA bitmap.
238 console.log('Example 8: Successfully rasterized into memory buffer.');
239 } catch (err) {
240 console.log(err);
241 }
242
243 //--------------------------------------------------------------------------------
244 // Example 9) Export raster content to PNG using different image smoothing settings.
245 try {
246 const text_doc = await PDFNet.PDFDoc.createFromFilePath(inputPath + 'lorem_ipsum.pdf');
247 text_doc.initSecurityHandler();
248 const itr = await text_doc.getPageIterator();
249 const page = await itr.current();
250
251 draw.setImageSmoothing(false, false);
252 let filename = 'raster_text_no_smoothing.png';
253 await draw.export(page, outputPath + filename);
254 console.log('Example 9 a): ' + filename + '. Done.');
255
256 filename = 'raster_text_smoothed.png';
257 draw.setImageSmoothing(true, false /*default quality bilinear resampling*/);
258 await draw.export(page, outputPath + filename);
259 console.log('Example 9 b): ' + filename + '. Done.');
260
261 filename = 'raster_text_high_quality.png';
262 draw.setImageSmoothing(true, true /*high quality area resampling*/);
263 await draw.export(page, outputPath + filename);
264 console.log('Example 9 c): ' + filename + '. Done.');
265 } catch (err) {
266 console.log(err);
267 }
268
269 //--------------------------------------------------------------------------------
270 // Example 10) Export separations directly, without conversion to an output colorspace
271 try {
272 const separation_doc = await PDFNet.PDFDoc.createFromFilePath(inputPath + 'op_blend_test.pdf');
273 separation_doc.initSecurityHandler();
274 const separation_hint = await hint_set.createDict();
275 await separation_hint.putName('ColorSpace', 'Separation');
276 draw.setDPI(96);
277 draw.setImageSmoothing(true, true);
278 draw.setOverprint(PDFNet.PDFRasterizer.OverprintPreviewMode.e_op_on);
279
280 const itr = await separation_doc.getPageIterator();
281 const page = await itr.current();
282 let filename = 'merged_separations.png';
283 await draw.export(page, outputPath + filename, 'PNG');
284 console.log('Example 10 a): ' + filename + '. Done.');
285
286 filename = 'separation';
287 await draw.export(page, outputPath + filename, 'PNG', separation_hint);
288 console.log('Example 10 b): ' + filename + '_[ink].png. Done.');
289
290 filename = 'separation_NChannel.tif';
291 await draw.export(page, outputPath + filename, 'TIFF', separation_hint);
292 console.log('Example 10 c): ' + filename + '. Done.');
293 } catch (err) {
294 console.log(err);
295 }
296 } catch (err) {
297 console.log(err);
298 }
299 };
300
301 PDFNet.runWithCleanup(main, PDFTronLicense.Key).catch(function (error) { console.log('Error: ' + JSON.stringify(error)); }).then(function () { return PDFNet.shutdown(); });
302 };
303 exports.runPDFDrawTest();
304})(exports);
305// eslint-disable-next-line spaced-comment
306//# sourceURL=PDFDrawTest.js
1#---------------------------------------------------------------------------------------
2# Copyright (c) 2001-2023 by Apryse Software Inc. All Rights Reserved.
3# Consult LICENSE.txt regarding license information.
4#---------------------------------------------------------------------------------------
5
6import site
7site.addsitedir("../../../PDFNetC/Lib")
8import sys
9from PDFNetPython import *
10
11sys.path.append("../../LicenseKey/PYTHON")
12from LicenseKey import *
13
14# Relative path to the folder containing test files.
15input_path = "../../TestFiles/"
16output_path = "../../TestFiles/Output/"
17
18#---------------------------------------------------------------------------------------
19# The following sample illustrates how to convert PDF documents to various raster image
20# formats (such as PNG, JPEG, BMP, TIFF, etc), as well as how to convert a PDF page to
21# GDI+ Bitmap for further manipulation and/or display in WinForms applications.
22#---------------------------------------------------------------------------------------
23
24def main():
25
26 # The first step in every application using PDFNet is to initialize the
27 # library and set the path to common PDF resources. The library is usually
28 # initialized only once, but calling Initialize() multiple times is also fine.
29 PDFNet.Initialize(LicenseKey)
30
31 # Optional: Set ICC color profiles to fine tune color conversion
32 # for PDF 'device' color spaces...
33
34 # PDFNet.SetResourcesPath("../../../resources")
35 # PDFNet.SetColorManagement()
36 # PDFNet.SetDefaultDeviceCMYKProfile("D:/Misc/ICC/USWebCoatedSWOP.icc")
37 # PDFNet.SetDefaultDeviceRGBProfile("AdobeRGB1998.icc") # will search in PDFNet resource folder.
38
39 # ----------------------------------------------------
40 # Optional: Set predefined font mappings to override default font
41 # substitution for documents with missing fonts...
42
43 # PDFNet.AddFontSubst("StoneSans-Semibold", "C:/WINDOWS/Fonts/comic.ttf")
44 # PDFNet.AddFontSubst("StoneSans", "comic.ttf") # search for 'comic.ttf' in PDFNet resource folder.
45 # PDFNet.AddFontSubst(PDFNet.e_Identity, "C:/WINDOWS/Fonts/arialuni.ttf")
46 # PDFNet.AddFontSubst(PDFNet.e_Japan1, "C:/Program Files/Adobe/Acrobat 7.0/Resource/CIDFont/KozMinProVI-Regular.otf")
47 # PDFNet.AddFontSubst(PDFNet.e_Japan2, "c:/myfonts/KozMinProVI-Regular.otf")
48 # PDFNet.AddFontSubst(PDFNet.e_Korea1, "AdobeMyungjoStd-Medium.otf")
49 # PDFNet.AddFontSubst(PDFNet.e_CNS1, "AdobeSongStd-Light.otf")
50 # PDFNet.AddFontSubst(PDFNet.e_GB1, "AdobeMingStd-Light.otf")
51
52 #Example 1) Convert the first page to PNG and TIFF at 92 DPI.
53
54 # PDFDraw class is used to rasterize PDF pages.
55 draw = PDFDraw()
56
57 #--------------------------------------------------------------------------------
58 # Example 1) Convert the first page to PNG and TIFF at 92 DPI.
59 # A three step tutorial to convert PDF page to an image.
60
61 # A) Open the PDF document.
62 doc = PDFDoc(input_path + "tiger.pdf")
63
64 # Initialize the security handler, in case the PDF is encrypted.
65 doc.InitSecurityHandler()
66
67 # B) The output resolution is set to 92 DPI.
68 draw.SetDPI(92)
69
70 # C) Rasterize the first page in the document and save the result as PNG.
71 itr = doc.GetPageIterator()
72 draw.Export(itr.Current(), output_path + "tiger_92dpi.png")
73
74 print("Example 1: tiger_92dpi.png")
75
76 # Export the same page as TIFF
77 itr = doc.GetPageIterator()
78 draw.Export(itr.Current(), (output_path + "tiger_92dpi.tif"), "TIFF")
79
80 #--------------------------------------------------------------------------------
81 # Example 2) Convert the all pages in a given document to JPEG at 72 DPI.
82
83 print("Example 2:")
84
85 hint_set = ObjSet() # A collection of rendering 'hits'.
86
87 doc = PDFDoc(input_path + "newsletter.pdf")
88 # Initialize the security handler, in case the PDF is encrypted.
89 doc.InitSecurityHandler()
90
91 # Set the output resolution is to 72 DPI.
92 draw.SetDPI(72)
93
94 # Use optional encoder parameter to specify JPEG quality.
95 encoder_param = hint_set.CreateDict()
96 encoder_param.PutNumber("Quality", 80)
97
98 # Traverse all pages in the document.
99 itr = doc.GetPageIterator()
100 while itr.HasNext():
101 filename = "newsletter" + str(itr.Current().GetIndex()) + ".jpg"
102 print(filename)
103 draw.Export(itr.Current(), output_path + filename, "JPEG", encoder_param)
104 itr.Next()
105 print("Done.")
106
107 # Examples 3-5
108 # Common code for remaining samples.
109 tiger_doc = PDFDoc(input_path + "tiger.pdf")
110 # Initialize the security handler, in case the PDF is encrypted.
111 tiger_doc.InitSecurityHandler()
112 page = tiger_doc.GetPage(1)
113
114 #--------------------------------------------------------------------------------
115 # Example 3) Convert the first page to raw bitmap. Also, rotate the
116 # page 90 degrees and save the result as RAW.
117 draw.SetDPI(100) # Set the output resolution is to 100 DPI.
118 draw.SetRotate(Page.e_90) # Rotate all pages 90 degrees clockwise.
119 bmp = draw.GetBitmap(page, PDFDraw.e_rgb)
120
121 # Save the raw RGB data to disk.
122 if sys.version_info.major >= 3:
123 f = open(output_path + "tiger_100dpi_rot90.raw", "w")
124 else:
125 f = open(output_path + "tiger_100dpi_rot90.raw", "wb")
126 try:
127 f.write(str(bmp.GetBuffer()))
128 finally:
129 f.close()
130
131 print("Example 3: tiger_100dpi_rot90.raw")
132
133 draw.SetRotate(Page.e_0) # Disable image rotation for remaining samples.
134
135 #--------------------------------------------------------------------------------
136 # Example 4) Convert PDF page to a fixed image size. Also illustrates some
137 # other features in PDFDraw class such as rotation, image stretching, exporting
138 # to grayscale, or monochrome.
139
140 # Initialize render 'gray_hint' parameter, that is used to control the
141 # rendering process. In this case we tell the rasterizer to export the image as
142 # 1 Bit Per Component (BPC) image.
143 mono_hint = hint_set.CreateDict()
144 mono_hint.PutNumber("BPC", 1)
145
146 # SetImageSize can be used instead of SetDPI() to adjust page scaling
147 # dynamically so that given image fits into a buffer of given dimensions.
148 draw.SetImageSize(1000, 1000) # Set the output image to be 1000 wide and 1000 pixels tall
149 draw.Export(page, output_path + "tiger_1000x1000.png", "PNG", mono_hint)
150 print("Example 4: tiger_1000x1000.png")
151
152 draw.SetImageSize(200, 400) # Set the output image to be 200 wide and 400 pixels tall
153 draw.SetRotate(Page.e_180) # Rotate all pages 90 degrees clockwise
154
155 # 'gray_hint' tells the rasterizer to export the image as grayscale.
156 gray_hint = hint_set.CreateDict()
157 gray_hint.PutName("ColorSpace", "Gray")
158
159 draw.Export(page, (output_path + "tiger_200x400_rot180.png"), "PNG", gray_hint)
160 print("Example 4: tiger_200x400_rot180.png")
161
162 draw.SetImageSize(400, 200, False) # The third parameter sets 'preserve-aspect-ratio' to False
163 draw.SetRotate(Page.e_0) # Disable image rotation
164 draw.Export(page, output_path + "tiger_400x200_stretch.jpg", "JPEG")
165 print("Example 4: tiger_400x200_stretch.jpg")
166
167 #--------------------------------------------------------------------------------
168 # Example 5) Zoom into a specific region of the page and rasterize the
169 # area at 200 DPI and as a thumbnail (i.e. a 50x50 pixel image).
170 zoom_rect = Rect(216, 522, 330, 600)
171 page.SetCropBox(zoom_rect) # Set the page crop box.
172
173 # Select the crop region to be used for drawing.
174 draw.SetPageBox(Page.e_crop)
175 draw.SetDPI(900) # Set the output image resolution to 900 DPI.
176 draw.Export(page, output_path + "tiger_zoom_900dpi.png", "PNG")
177 print("Example 5: tiger_zoom_900dpi.png")
178
179 # -------------------------------------------------------------------------------
180 # Example 6)
181 draw.SetImageSize(50, 50) # Set the thumbnail to be 50x50 pixel image.
182 draw.Export(page, output_path + "tiger_zoom_50x50.png", "PNG")
183 print("Example 6: tiger_zoom_50x50.png")
184
185 cmyk_hint = hint_set.CreateDict()
186 cmyk_hint.PutName("ColorSpace", "CMYK")
187
188 #--------------------------------------------------------------------------------
189 # Example 7) Convert the first PDF page to CMYK TIFF at 92 DPI.
190 # A three step tutorial to convert PDF page to an image
191 # A) Open the PDF document
192 doc = PDFDoc(input_path + "tiger.pdf")
193 # Initialize the security handler, in case the PDF is encrypted.
194 doc.InitSecurityHandler()
195
196 # The output resolution is set to 92 DPI.
197 draw.SetDPI(92)
198
199 # C) Rasterize the first page in the document and save the result as TIFF.
200 pg = doc.GetPage(1)
201 draw.Export(pg, output_path + "out1.tif", "TIFF", cmyk_hint)
202 print("Example 7: out1.tif")
203
204 doc.Close()
205
206 # A) Open the PDF document.
207 doc = PDFDoc(input_path + "tiger.pdf");
208 # Initialize the security handler, in case the PDF is encrypted.
209 doc.InitSecurityHandler();
210
211 # B) Get the page matrix
212 pg = doc.GetPage(1);
213 box = Page.e_crop;
214 mtx = pg.GetDefaultMatrix(True, box);
215 # We want to render a quadrant, so use half of width and height
216 pg_w = pg.GetPageWidth(box) / 2;
217 pg_h = pg.GetPageHeight(box) / 2;
218
219 # C) Scale matrix from PDF space to buffer space
220 dpi = 96.0;
221 scale = dpi / 72.0; # PDF space is 72 dpi
222 buf_w = int(scale * pg_w);
223 buf_h = int(scale * pg_h);
224 bytes_per_pixel = 4; # BGRA buffer
225 buf_size = buf_w * buf_h * bytes_per_pixel;
226 mtx.Translate(0, -pg_h); # translate by '-pg_h' since we want south-west quadrant
227 mtx = Matrix2D(scale, 0, 0, scale, 0, 0).Multiply(mtx);
228
229 # D) Rasterize page into memory buffer, according to our parameters
230 rast = PDFRasterizer();
231 buf = rast.Rasterize(pg, buf_w, buf_h, buf_w * bytes_per_pixel, bytes_per_pixel, True, mtx);
232
233 # buf now contains raw BGRA bitmap.
234 print("Example 8: Successfully rasterized into memory buffer.");
235
236 #--------------------------------------------------------------------------------
237 # Example 9) Export raster content to PNG using different image smoothing settings.
238 text_doc = PDFDoc(input_path + "lorem_ipsum.pdf");
239 text_doc.InitSecurityHandler();
240
241 draw.SetImageSmoothing(False, False);
242 filename = "raster_text_no_smoothing.png";
243 draw.Export(text_doc.GetPageIterator().Current(), output_path + filename);
244 print("Example 9 a): " + filename + ". Done.");
245
246 filename = "raster_text_smoothed.png";
247 draw.SetImageSmoothing(True, False); # second argument = default quality bilinear resampling
248 draw.Export(text_doc.GetPageIterator().Current(), output_path + filename);
249 print("Example 9 b): " + filename + ". Done.");
250
251 filename = "raster_text_high_quality.png";
252 draw.SetImageSmoothing(True, True); # second argument = default quality bilinear resampling
253 draw.Export(text_doc.GetPageIterator().Current(), output_path + filename);
254 print("Example 9 c): " + filename + ". Done.");
255
256 #--------------------------------------------------------------------------------
257 # Example 10) Export separations directly, without conversion to an output colorspace
258
259 separation_doc = PDFDoc(input_path + "op_blend_test.pdf");
260 separation_doc.InitSecurityHandler();
261 separation_hint = hint_set.CreateDict();
262 separation_hint.PutName("ColorSpace", "Separation");
263 draw.SetDPI(96);
264 draw.SetImageSmoothing(True, True);
265 draw.SetOverprint(PDFRasterizer.e_op_on);
266
267 filename = "merged_separations.png";
268 draw.Export(separation_doc.GetPageIterator().Current(), output_path + filename, "PNG");
269 print("Example 10 a): " + filename + ". Done.");
270
271 filename = "separation";
272 draw.Export(separation_doc.GetPageIterator().Current(), output_path + filename, "PNG", separation_hint);
273 print("Example 10 b): " + filename + "_[ink].png. Done.");
274
275 filename = "separation_NChannel.tif";
276 draw.Export(separation_doc.GetPageIterator().Current(), output_path + filename, "TIFF", separation_hint);
277 print("Example 10 c): " + filename + ". Done.");
278
279 PDFNet.Terminate()
280
281if __name__ == '__main__':
282 main()
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
14//---------------------------------------------------------------------------------------
15// The following sample illustrates how to convert PDF documents to various raster image
16// formats (such as PNG, JPEG, BMP, TIFF, etc), as well as how to convert a PDF page to
17// GDI+ Bitmap for further manipulation and/or display in WinForms applications.
18//---------------------------------------------------------------------------------------
19
20 // The first step in every application using PDFNet is to initialize the
21 // library and set the path to common PDF resources. The library is usually
22 // initialized only once, but calling Initialize() multiple times is also fine.
23 PDFNet::Initialize($LicenseKey);
24 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.
25
26 // Optional: Set ICC color profiles to fine tune color conversion
27 // for PDF 'device' color spaces...
28
29 // PDFNet::SetResourcesPath("../../../resources");
30 // PDFNet::SetColorManagement();
31 // PDFNet::SetDefaultDeviceCMYKProfile("D:/Misc/ICC/USWebCoatedSWOP.icc");
32 // PDFNet::SetDefaultDeviceRGBProfile("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 // PDFNet::AddFontSubst("StoneSans-Semibold", "C:/WINDOWS/Fonts/comic.ttf");
39 // PDFNet::AddFontSubst("StoneSans", "comic.ttf"); // search for 'comic.ttf' in PDFNet resource folder.
40 // PDFNet::AddFontSubst(PDFNet::e_Identity, "C:/WINDOWS/Fonts/arialuni.ttf");
41 // PDFNet::AddFontSubst(PDFNet::e_Japan1, "C:/Program Files/Adobe/Acrobat 7.0/Resource/CIDFont/KozMinProVI-Regular.otf");
42 // PDFNet::AddFontSubst(PDFNet::e_Japan2, "c:/myfonts/KozMinProVI-Regular.otf");
43 // PDFNet::AddFontSubst(PDFNet::e_Korea1, "AdobeMyungjoStd-Medium.otf");
44 // PDFNet::AddFontSubst(PDFNet::e_CNS1, "AdobeSongStd-Light.otf");
45 // PDFNet::AddFontSubst(PDFNet::e_GB1, "AdobeMingStd-Light.otf");
46 $draw = new PDFDraw();
47
48 //--------------------------------------------------------------------------------
49 // Example 1) Convert the first page to PNG and TIFF at 92 DPI.
50 // A three step tutorial to convert PDF page to an image.
51
52 // A) Open the PDF document.
53 $doc = new PDFDoc($input_path."tiger.pdf");
54
55 // Initialize the security handler, in case the PDF is encrypted.
56 $doc->InitSecurityHandler();
57
58 // B) The output resolution is set to 92 DPI.
59 $draw->SetDPI(92);
60
61 // C) Rasterize the first page in the document and save the result as PNG.
62 $ir = $doc->GetPageIterator();
63 $draw->Export($ir->Current(), $output_path."tiger_92dpi.png");
64
65 echo nl2br("Example 1: tiger_92dpi.png\n");
66
67 // Export the same page as TIFF
68 $draw->Export($ir->Current(), $output_path."tiger_92dpi.tif", "TIFF");
69
70 //--------------------------------------------------------------------------------
71 // Example 2) Convert the all pages in a given document to JPEG at 72 DPI.
72 echo nl2br("Example 2:\n");
73 $hint_set = new ObjSet(); // A collection of rendering 'hits'.
74
75 $doc = new PDFDoc($input_path."newsletter.pdf");
76 // Initialize the security handler, in case the PDF is encrypted.
77 $doc->InitSecurityHandler();
78
79 $draw->SetDPI(72); // Set the output resolution is to 72 DPI.
80
81 // Use optional encoder parameter to specify JPEG quality.
82 $encoder_param=$hint_set->CreateDict();
83 $encoder_param->PutNumber("Quality", 80);
84
85 // Traverse all pages in the document.
86 for ($itr=$doc->GetPageIterator(); $itr->HasNext(); $itr->Next()) {
87 $filename = "newsletter".$itr->Current()->GetIndex().".jpg";
88 echo nl2br($filename."\n");
89 $draw->Export($itr->Current(), $output_path.$filename, "JPEG", $encoder_param);
90 }
91
92 echo nl2br("Done.\n");
93
94 // Examples 3-5
95
96 // Common code for remaining samples.
97 $tiger_doc = new PDFDoc($input_path."tiger.pdf");
98 // Initialize the security handler, in case the PDF is encrypted.
99 $tiger_doc->InitSecurityHandler();
100 $page = $tiger_doc->GetPage(1);
101
102 //--------------------------------------------------------------------------------
103 // Example 3) Convert the first page to raw bitmap. Also, rotate the
104 // page 90 degrees and save the result as RAW.
105 $draw->SetDPI(100); // Set the output resolution is to 100 DPI.
106 $draw->SetRotate(Page::e_90); // Rotate all pages 90 degrees clockwise.
107
108 $bmp = $draw->GetBitmap($page, PDFDraw::e_rgb);
109
110 // Save the raw RGB data to disk.
111 file_put_contents($output_path."tiger_100dpi_rot90.raw", $bmp->GetBuffer());
112
113 echo nl2br("Example 3: tiger_100dpi_rot90.raw\n");
114 $draw->SetRotate(Page::e_0); // Disable image rotation for remaining samples.
115
116 //--------------------------------------------------------------------------------
117 // Example 4) Convert PDF page to a fixed image size. Also illustrates some
118 // other features in PDFDraw class such as rotation, image stretching, exporting
119 // to grayscale, or monochrome.
120
121 // Initialize render 'gray_hint' parameter, that is used to control the
122 // rendering process. In this case we tell the rasterizer to export the image as
123 // 1 Bit Per Component (BPC) image.
124 $mono_hint=$hint_set->CreateDict();
125 $mono_hint->PutNumber("BPC", 1);
126
127 // SetImageSize can be used instead of SetDPI() to adjust page scaling
128 // dynamically so that given image fits into a buffer of given dimensions.
129 $draw->SetImageSize(1000, 1000); // Set the output image to be 1000 wide and 1000 pixels tall
130 $draw->Export($page, $output_path."tiger_1000x1000.png", "PNG", $mono_hint);
131 echo nl2br("Example 4: tiger_1000x1000.png\n");
132
133 $draw->SetImageSize(200, 400); // Set the output image to be 200 wide and 300 pixels tall
134 $draw->SetRotate(Page::e_180); // Rotate all pages 90 degrees clockwise.
135
136 // 'gray_hint' tells the rasterizer to export the image as grayscale.
137 $gray_hint=$hint_set->CreateDict();
138 $gray_hint->PutName("ColorSpace", "Gray");
139
140 $draw->Export($page, $output_path."tiger_200x400_rot180.png", "PNG", $gray_hint);
141 echo nl2br("Example 4: tiger_200x400_rot180.png\n");
142
143 $draw->SetImageSize(400, 200, false); // The third parameter sets 'preserve-aspect-ratio' to false.
144 $draw->SetRotate(Page::e_0); // Disable image rotation.
145 $draw->Export($page, $output_path."tiger_400x200_stretch.jpg", "JPEG");
146 echo nl2br("Example 4: tiger_400x200_stretch.jpg\n");
147
148 //--------------------------------------------------------------------------------
149 // Example 5) Zoom into a specific region of the page and rasterize the
150 // area at 200 DPI and as a thumbnail (i.e. a 50x50 pixel image).
151 $zoom_rect = new Rect(216.0, 522.0, 330.0, 600.0);
152 $page->SetCropBox($zoom_rect); // Set the page crop box.
153
154 // Select the crop region to be used for drawing.
155 $draw->SetPageBox(Page::e_crop);
156 $draw->SetDPI(900); // Set the output image resolution to 900 DPI.
157 $draw->Export($page, $output_path."tiger_zoom_900dpi.png", "PNG");
158 echo nl2br("Example 5: tiger_zoom_900dpi.png\n");
159
160
161 // -------------------------------------------------------------------------------
162 // Example 6)
163 $draw->SetImageSize(50, 50); // Set the thumbnail to be 50x50 pixel image.
164 $draw->Export($page, $output_path."tiger_zoom_50x50.png", "PNG");
165 echo nl2br("Example 6: tiger_zoom_50x50.png\n");
166
167 $cmyk_hint = $hint_set->CreateDict();
168 $cmyk_hint->PutName("ColorSpace", "CMYK");
169
170 //--------------------------------------------------------------------------------
171 // Example 7) Convert the first PDF page to CMYK TIFF at 92 DPI.
172 // A three step tutorial to convert PDF page to an image
173 // A) Open the PDF document.
174 $doc = new PDFDoc($input_path."tiger.pdf");
175 // Initialize the security handler, in case the PDF is encrypted.
176 $doc->InitSecurityHandler();
177
178 // B) The output resolution is set to 92 DPI.
179 $draw->SetDPI(92);
180
181 // C) Rasterize the first page in the document and save the result as TIFF.
182 $pg = $doc->GetPage(1);
183 $draw->Export($pg, $output_path."out1.tif", "TIFF", $cmyk_hint);
184 echo nl2br("Example 7: out1.tif\n");
185
186 $doc->Close();
187
188 //--------------------------------------------------------------------------------
189 // Example 8) PDFRasterizer can be used for more complex rendering tasks, such as
190 // strip by strip or tiled document rendering. In particular, it is useful for
191 // cases where you cannot simply modify the page crop box (interactive viewing,
192 // parallel rendering). This example shows how you can rasterize the south-west
193 // quadrant of a page.
194 // A) Open the PDF document.
195 $doc = new PDFDoc($input_path."tiger.pdf");
196 // Initialize the security handler, in case the PDF is encrypted.
197 $doc->InitSecurityHandler();
198
199 // B) Get the page matrix
200 $pg = $doc->GetPage(1);
201 $box = Page::e_crop;
202 $mtx = $pg->GetDefaultMatrix(true, $box);
203 // We want to render a quadrant, so use half of width and height
204 $pg_w = $pg->GetPageWidth($box) / 2;
205 $pg_h = $pg->GetPageHeight($box) / 2;
206
207 // C) Scale matrix from PDF space to buffer space
208 $dpi = 96.0;
209 $scale = $dpi / 72.0; // PDF space is 72 dpi
210 $buf_w = (int)($scale * $pg_w);
211 $buf_h = (int)($scale * $pg_h);
212 $bytes_per_pixel = 4; // BGRA buffer
213 $buf_size = $buf_w * $buf_h * $bytes_per_pixel;
214 $mtx->Translate(0, -$pg_h); // translate by '-pg_h' since we want south-west quadrant
215 $mtx = new Matrix2D($scale, 0.0, 0.0, $scale, 0.0, 0.0);
216 $mtx->Multiply($mtx);
217
218 // D) Rasterize page into memory buffer, according to our parameters
219 $rast = new PDFRasterizer();
220 $buf = $rast->Rasterize($pg, $buf_w, $buf_h, $buf_w * $bytes_per_pixel, $bytes_per_pixel, true, $mtx);
221
222 // buf now contains raw BGRA bitmap.
223 echo nl2br("Example 8: Successfully rasterized into memory buffer.\n");
224
225 //--------------------------------------------------------------------------------
226 // Example 9) Export raster content to PNG using different image smoothing settings.
227 $text_doc = new PDFDoc($input_path."lorem_ipsum.pdf");
228 $text_doc->InitSecurityHandler();
229
230 $draw->SetImageSmoothing(false, false);
231 $filename = "raster_text_no_smoothing.png";
232 $ir = $text_doc->GetPageIterator();
233 $draw->Export($ir->Current(), $output_path.$filename);
234 echo nl2br("Example 9 a): ".$filename.". Done.\n");
235
236 $filename = "raster_text_smoothed.png";
237 $draw->SetImageSmoothing(true, false /*default quality bilinear resampling*/);
238 $draw->Export($ir->Current(), $output_path.$filename);
239 echo nl2br("Example 9 b): ".$filename.". Done.\n");
240
241 $filename = "raster_text_high_quality.png";
242 $draw->SetImageSmoothing(true, true /*high quality area resampling*/);
243 $draw->Export($ir->Current(), $output_path.$filename);
244 echo nl2br("Example 9 c): ".$filename.". Done.\n");
245
246 //--------------------------------------------------------------------------------
247 // Example 10) Export separations directly, without conversion to an output colorspace
248 $separation_doc = new PDFDoc($input_path."op_blend_test.pdf");
249 $separation_doc->InitSecurityHandler();
250 $separation_hint = $hint_set->CreateDict();
251 $separation_hint->PutName("ColorSpace", "Separation");
252 $draw->SetDPI(96);
253 $draw->SetImageSmoothing(true, true);
254 $draw->SetOverprint(PDFRasterizer::e_op_on);
255
256 $filename = "merged_separations.png";
257 $ir = $separation_doc->GetPageIterator();
258 $draw->Export($ir->Current(), $output_path.$filename, "PNG");
259 echo nl2br("Example 10 a): ".$filename.". Done.\n");
260
261 $filename = "separation";
262 $draw->Export($ir->Current(), $output_path.$filename, "PNG", $separation_hint);
263 echo nl2br("Example 10 b): ".$filename."_[ink].png. Done.\n");
264
265 $filename = "separation_NChannel.tif";
266 $draw->Export($ir->Current(), $output_path.$filename, "TIFF", $separation_hint);
267 echo nl2br("Example 10 c): ".$filename.". Done.\n");
268 PDFNet::Terminate();
269?>
1#---------------------------------------------------------------------------------------
2# Copyright (c) 2001-2023 by Apryse Software Inc. All Rights Reserved.
3# Consult LICENSE.txt regarding license information.
4#---------------------------------------------------------------------------------------
5
6require '../../../PDFNetC/Lib/PDFNetRuby'
7include PDFNetRuby
8require '../../LicenseKey/RUBY/LicenseKey'
9
10$stdout.sync = true
11
12# Relative path to the folder containing test files.
13input_path = "../../TestFiles/"
14output_path = "../../TestFiles/Output/"
15
16#---------------------------------------------------------------------------------------
17# The following sample illustrates how to convert PDF documents to various raster image
18# formats (such as PNG, JPEG, BMP, TIFF, etc), as well as how to convert a PDF page to
19# GDI+ Bitmap for further manipulation and/or display in WinForms applications.
20#---------------------------------------------------------------------------------------
21
22 # The first step in every application using PDFNet is to initialize the
23 # library and set the path to common PDF resources. The library is usually
24 # initialized only once, but calling Initialize multiple times is also fine.
25 PDFNet.Initialize(PDFTronLicense.Key)
26
27 # Optional: Set ICC color profiles to fine tune color conversion
28 # for PDF 'device' color spaces...
29
30 # PDFNet.SetResourcesPath("../../../resources")
31 # PDFNet.SetColorManagement
32 # PDFNet.SetDefaultDeviceCMYKProfile("D:/Misc/ICC/USWebCoatedSWOP.icc")
33 # PDFNet.SetDefaultDeviceRGBProfile("AdobeRGB1998.icc") # will search in PDFNet resource folder.
34
35 # ----------------------------------------------------
36 # Optional: Set predefined font mappings to override default font
37 # substitution for documents with missing fonts...
38
39 # PDFNet.AddFontSubst("StoneSans-Semibold", "C:/WINDOWS/Fonts/comic.ttf")
40 # PDFNet.AddFontSubst("StoneSans", "comic.ttf") # search for 'comic.ttf' in PDFNet resource folder.
41 # PDFNet.AddFontSubst(PDFNet.E_Identity, "C:/WINDOWS/Fonts/arialuni.ttf")
42 # PDFNet.AddFontSubst(PDFNet.E_Japan1, "C:/Program Files/Adobe/Acrobat 7.0/Resource/CIDFont/KozMinProVI-Regular.otf")
43 # PDFNet.AddFontSubst(PDFNet.E_Japan2, "c:/myfonts/KozMinProVI-Regular.otf")
44 # PDFNet.AddFontSubst(PDFNet.E_Korea1, "AdobeMyungjoStd-Medium.otf")
45 # PDFNet.AddFontSubst(PDFNet.E_CNS1, "AdobeSongStd-Light.otf")
46 # PDFNet.AddFontSubst(PDFNet.E_GB1, "AdobeMingStd-Light.otf")
47
48 #Example 1) Convert the first page to PNG and TIFF at 92 DPI.
49
50 # PDFDraw class is used to rasterize PDF pages.
51 draw = PDFDraw.new
52
53 #--------------------------------------------------------------------------------
54 # Example 1) Convert the first page to PNG and TIFF at 92 DPI.
55 # A three step tutorial to convert PDF page to an image.
56
57 # A) Open the PDF document.
58 doc = PDFDoc.new(input_path + "tiger.pdf")
59
60 # Initialize the security handler, in case the PDF is encrypted.
61 doc.InitSecurityHandler
62
63 # B) The output resolution is set to 92 DPI.
64 draw.SetDPI(92)
65
66 # C) Rasterize the first page in the document and save the result as PNG.
67 itr = doc.GetPageIterator
68 draw.Export(itr.Current, output_path + "tiger_92dpi.png")
69
70 puts "Example 1: tiger_92dpi.png"
71
72 # Export the same page as TIFF
73 itr = doc.GetPageIterator
74 draw.Export(itr.Current, (output_path + "tiger_92dpi.tif"), "TIFF")
75
76 #--------------------------------------------------------------------------------
77 # Example 2) Convert the all pages in a given document to JPEG at 72 DPI.
78
79 puts "Example 2:"
80
81 hint_set = ObjSet.new # A collection of rendering 'hits'.
82
83 doc = PDFDoc.new(input_path + "newsletter.pdf")
84 # Initialize the security handler, in case the PDF is encrypted.
85 doc.InitSecurityHandler
86
87 # Set the output resolution is to 72 DPI.
88 draw.SetDPI(72)
89
90 # Use optional encoder parameter to specify JPEG quality.
91 encoder_param = hint_set.CreateDict
92 encoder_param.PutNumber("Quality", 80)
93
94 # Traverse all pages in the document.
95 itr = doc.GetPageIterator
96 while itr.HasNext do
97 filename = "newsletter" + itr.Current.GetIndex.to_s + ".jpg"
98 puts filename
99 draw.Export(itr.Current, output_path + filename, "JPEG", encoder_param)
100 itr.Next
101 end
102 puts "Done."
103
104 # Examples 3-5
105 # Common code for remaining samples.
106 tiger_doc = PDFDoc.new(input_path + "tiger.pdf")
107 # Initialize the security handler, in case the PDF is encrypted.
108 tiger_doc.InitSecurityHandler
109 page = tiger_doc.GetPage(1)
110
111 #--------------------------------------------------------------------------------
112 # Example 3) Convert the first page to raw bitmap. Also, rotate the
113 # page 90 degrees and save the result as RAW.
114 draw.SetDPI(100) # Set the output resolution is to 100 DPI.
115 draw.SetRotate(Page::E_90) # Rotate all pages 90 degrees clockwise.
116 bmp = draw.GetBitmap(page, PDFDraw::E_rgb)
117
118 # Save the raw RGB data to disk.
119 File.open(output_path + "tiger_100dpi_rot90.raw", 'w') { |file| file.write(bmp.GetBuffer) }
120
121 puts "Example 3: tiger_100dpi_rot90.raw"
122
123 draw.SetRotate(Page::E_0) # Disable image rotation for remaining samples.
124
125 #--------------------------------------------------------------------------------
126 # Example 4) Convert PDF page to a fixed image size. Also illustrates some
127 # other features in PDFDraw class such as rotation, image stretching, exporting
128 # to grayscale, or monochrome.
129
130 # Initialize render 'gray_hint' parameter, that is used to control the
131 # rendering process. In this case we tell the rasterizer to export the image as
132 # 1 Bit Per Component (BPC) image.
133 mono_hint = hint_set.CreateDict
134 mono_hint.PutNumber("BPC", 1)
135
136 # SetImageSize can be used instead of SetDPI to adjust page scaling
137 # dynamically so that given image fits into a buffer of given dimensions.
138 draw.SetImageSize(1000, 1000) # Set the output image to be 1000 wide and 1000 pixels tall
139 draw.Export(page, output_path + "tiger_1000x1000.png", "PNG", mono_hint)
140 puts "Example 4: tiger_1000x1000.png"
141
142 draw.SetImageSize(200, 400) # Set the output image to be 200 wide and 400 pixels tall
143 draw.SetRotate(Page::E_180) # Rotate all pages 90 degrees clockwise
144
145 # 'gray_hint' tells the rasterizer to export the image as grayscale.
146 gray_hint = hint_set.CreateDict
147 gray_hint.PutName("ColorSpace", "Gray")
148
149 draw.Export(page, (output_path + "tiger_200x400_rot180.png"), "PNG", gray_hint)
150 puts "Example 4: tiger_200x400_rot180.png"
151
152 draw.SetImageSize(400, 200, false) # The third parameter sets 'preserve-aspect-ratio' to false
153 draw.SetRotate(Page::E_0) # Disable image rotation
154 draw.Export(page, output_path + "tiger_400x200_stretch.jpg", "JPEG")
155 puts "Example 4: tiger_400x200_stretch.jpg"
156
157 #--------------------------------------------------------------------------------
158 # Example 5) Zoom into a specific region of the page and rasterize the
159 # area at 200 DPI and as a thumbnail (i.e. a 50x50 pixel image).
160 zoom_rect = Rect.new(216, 522, 330, 600)
161 page.SetCropBox(zoom_rect) # Set the page crop box.
162
163 # Select the crop region to be used for drawing.
164 draw.SetPageBox(Page::E_crop)
165 draw.SetDPI(900) # Set the output image resolution to 900 DPI.
166 draw.Export(page, output_path + "tiger_zoom_900dpi.png", "PNG")
167 puts "Example 5: tiger_zoom_900dpi.png"
168
169 # -------------------------------------------------------------------------------
170 # Example 6)
171 draw.SetImageSize(50, 50) # Set the thumbnail to be 50x50 pixel image.
172 draw.Export(page, output_path + "tiger_zoom_50x50.png", "PNG")
173 puts "Example 6: tiger_zoom_50x50.png"
174
175 cmyk_hint = hint_set.CreateDict
176 cmyk_hint.PutName("ColorSpace", "CMYK")
177
178 #--------------------------------------------------------------------------------
179 # Example 6) Convert the first PDF page to CMYK TIFF at 92 DPI.
180 # A three step tutorial to convert PDF page to an image
181 # A) Open the PDF document
182 doc = PDFDoc.new(input_path + "tiger.pdf")
183 # Initialize the security handler, in case the PDF is encrypted.
184 doc.InitSecurityHandler
185
186 # The output resolution is set to 92 DPI.
187 draw.SetDPI(92)
188
189 # C) Rasterize the first page in the document and save the result as TIFF.
190 pg = doc.GetPage(1)
191 draw.Export(pg, output_path + "out1.tif", "TIFF", cmyk_hint)
192 puts "Example 7: out1.tif"
193
194 doc.Close
195
196 # A) Open the PDF document.
197 doc = PDFDoc.new(input_path + "tiger.pdf")
198 # Initialize the security handler, in case the PDF is encrypted.
199 doc.InitSecurityHandler
200
201 # B) Get the page matrix
202 pg = doc.GetPage(1)
203 box = Page::E_crop
204 mtx = pg.GetDefaultMatrix(true, box)
205 # We want to render a quadrant, so use half of width and height
206 pg_w = pg.GetPageWidth(box) / 2
207 pg_h = pg.GetPageHeight(box) / 2
208
209 # C) Scale matrix from PDF space to buffer space
210 dpi = 96.0
211 scale = dpi / 72.0 # PDF space is 72 dpi
212 buf_w = ((scale * pg_w).floor).to_i
213 buf_h = ((scale * pg_h).floor).to_i
214 bytes_per_pixel = 4 # BGRA buffer
215 buf_size = buf_w * buf_h * bytes_per_pixel
216 mtx.Translate(0, -pg_h) # translate by '-pg_h' since we want south-west quadrant
217 mtx = Matrix2D.new(scale, 0, 0, scale, 0, 0).Multiply(mtx)
218
219 # D) Rasterize page into memory buffer, according to our parameters
220 rast = PDFRasterizer.new
221 buf = rast.Rasterize(pg, buf_w, buf_h, buf_w * bytes_per_pixel, bytes_per_pixel, true, mtx)
222
223 # buf now contains raw BGRA bitmap.
224 puts "Example 8: Successfully rasterized into memory buffer."
225
226 #--------------------------------------------------------------------------------
227 # Example 9) Export raster content to PNG using different image smoothing settings.
228 text_doc = PDFDoc.new(input_path + "lorem_ipsum.pdf")
229 text_doc.InitSecurityHandler
230
231 draw.SetImageSmoothing(false, false)
232 filename = "raster_text_no_smoothing.png"
233 draw.Export(text_doc.GetPageIterator.Current, output_path + filename)
234 puts "Example 9 a): " + filename + ". Done."
235
236 filename = "raster_text_smoothed.png"
237 # default quality bilinear resampling
238 draw.SetImageSmoothing(true, false)
239 draw.Export(text_doc.GetPageIterator.Current, output_path + filename)
240 puts "Example 9 b): " + filename + ". Done."
241
242 filename = "raster_text_high_quality.png"
243 # high quality area resampling
244 draw.SetImageSmoothing(true, true)
245 draw.Export(text_doc.GetPageIterator.Current, output_path + filename)
246 puts "Example 9 c): " + filename + ". Done."
247
248 #--------------------------------------------------------------------------------
249 # Example 10) Export separations directly, without conversion to an output colorspace
250
251 separation_doc = PDFDoc.new(input_path + "op_blend_test.pdf")
252 separation_doc.InitSecurityHandler
253 separation_hint = hint_set.CreateDict
254 separation_hint.PutName("ColorSpace", "Separation")
255 draw.SetDPI(96)
256 draw.SetImageSmoothing(true, true)
257 draw.SetOverprint(PDFRasterizer::E_op_on)
258
259 filename = "merged_separations.png"
260 draw.Export(separation_doc.GetPageIterator.Current, output_path + filename, "PNG")
261 puts "Example 10 a): " + filename + ". Done."
262
263 filename = "separation"
264 draw.Export(separation_doc.GetPageIterator.Current, output_path + filename, "PNG", separation_hint)
265 puts "Example 10 b): " + filename + "_[ink].png. Done."
266
267 filename = "separation_NChannel.tif"
268 draw.Export(separation_doc.GetPageIterator.Current, output_path + filename, "TIFF", separation_hint)
269 puts "Example 10 c): " + filename + ". Done."
270 PDFNet.Terminate
1'---------------------------------------------------------------------------------------
2' Copyright (c) 2001-2024 by Apryse Software Inc. All Rights Reserved.
3' Consult legal.txt regarding legal and license information.
4'---------------------------------------------------------------------------------------
5Imports System
6Imports System.Drawing
7Imports System.Drawing.Imaging
8Imports System.Runtime.InteropServices
9
10Imports pdftron
11Imports pdftron.Common
12Imports pdftron.SDF
13Imports pdftron.PDF
14
15' <summary>
16'---------------------------------------------------------------------------------------
17' The following sample illustrates how to convert PDF documents to various raster image
18' formats (such as PNG, JPEG, BMP, TIFF), as well as how to convert a PDF page to GDI+ Bitmap
19' for further manipulation and/or display in WinForms applications.
20'---------------------------------------------------------------------------------------
21' </summary>
22Module PDFDrawTestVB
23 Dim pdfNetLoader As PDFNetLoader
24 Sub New()
25 pdfNetLoader = pdftron.PDFNetLoader.Instance()
26 End Sub
27
28 ' The main entry point for the application.
29 Sub Main()
30
31 ' The first step in every application using PDFNet is to initialize the
32 ' library and set the path to common PDF resources. The library is usually
33 ' initialized only once, but calling Initialize() multiple times is also fine.
34 PDFNet.Initialize(PDFTronLicense.Key)
35
36 ' Try
37 ' Optional: Set ICC color profiles to fine tune color conversion
38 ' for PDF 'device' color spaces. You can use your own ICC profiles.
39 ' Standard Adobe color profiles can be download from Adobes site:
40 ' http://www.adobe.com/support/downloads/iccprofiles/iccprofiles_win.html
41 '
42 ' Simply drop all *.icc files in PDFNet resource folder or you specify
43 ' the full pathname.
44 '---
45 ' PDFNet.SetResourcesPath("../../../../resources")
46 ' PDFNet.SetColorManagement()
47 ' PDFNet.SetDefaultDeviceCMYKProfile("USWebCoatedSWOP.icc") ' will search in PDFNet resource folder.
48 ' PDFNet.SetDefaultDeviceRGBProfile("AdobeRGB1998.icc")
49
50 ' Optional: Set predefined font mappings to override default font
51 ' substitution for documents with missing fonts. For example:
52 '---
53 ' PDFNet.AddFontSubst("StoneSans-Semibold", "C:/WINDOWS/Fonts/comic.ttf")
54 ' PDFNet.AddFontSubst("StoneSans", "comic.ttf") ' search for 'comic.ttf' in PDFNet resource folder.
55 ' PDFNet.AddFontSubst(PDFNet.CharacterOrdering.e_Identity, "C:/WINDOWS/Fonts/arialuni.ttf")
56 ' PDFNet.AddFontSubst(PDFNet.CharacterOrdering.e_Japan1, "C:/Program Files/Adobe/Acrobat 7.0/Resource/CIDFont/KozMinProVI-Regular.otf")
57 ' PDFNet.AddFontSubst(PDFNet.CharacterOrdering.e_Japan2, "c:/myfonts/KozMinProVI-Regular.otf")
58 '
59 ' If fonts are in PDFNet resource folder, it is not necessary to specify
60 ' the full path name. For example,
61 '---
62 ' PDFNet.AddFontSubst(PDFNet.CharacterOrdering.e_Korea1, "AdobeMyungjoStd-Medium.otf")
63 ' PDFNet.AddFontSubst(PDFNet.CharacterOrdering.e_CNS1, "AdobeSongStd-Light.otf")
64 ' PDFNet.AddFontSubst(PDFNet.CharacterOrdering.e_GB1, "AdobeMingStd-Light.otf")
65 ' Catch e As PDFNetException
66 ' Console.WriteLine(e.Message)
67 ' End Try
68
69 ' Relative path to the folder containing test files.
70 Dim input_path As String = "../../../../TestFiles/"
71 Dim output_path As String = "../../../../TestFiles/Output/"
72
73 Using draw As PDFDraw = New PDFDraw ' PDFDraw class is used to rasterize PDF pages.
74
75 '--------------------------------------------------------------------------------
76 ' Example 1) Convert the first PDF page to PNG at 92 DPI.
77 ' A three step tutorial to convert PDF page to an image.
78 Try
79 ' A) Open the PDF document.
80 Using doc As PDFDoc = New PDFDoc(input_path + "tiger.pdf")
81 ' Initialize the security handler, in case the PDF is encrypted.
82 doc.InitSecurityHandler()
83
84 ' B) The output resolution is set to 92 DPI.
85 draw.SetDPI(92)
86
87 ' C) Rasterize the first page in the document and save the result as PNG.
88 Dim pg As Page = doc.GetPage(1)
89 draw.Export(pg, output_path + "tiger_92dpi.png")
90
91 Console.WriteLine("Example 1: tiger_92dpi.png")
92
93 ' Export the same page as TIFF
94 draw.Export(pg, output_path + "tiger_92dpi.tif", "TIFF")
95 End Using
96 Catch e As PDFNetException
97 Console.WriteLine(e.Message)
98 End Try
99
100
101 '--------------------------------------------------------------------------------
102 ' Example 2) Convert the all pages in a given document to JPEG at 72 DPI.
103 Console.WriteLine("Example 2:")
104 Dim hint_set As ObjSet = New ObjSet ' A collection of rendering 'hits'.
105 Try
106 Using doc As PDFDoc = New PDFDoc(input_path + "newsletter.pdf")
107 ' Initialize the security handler, in case the PDF is encrypted.
108 doc.InitSecurityHandler()
109
110 draw.SetDPI(72) ' Set the output resolution is to 72 DPI.
111
112 ' Use optional encoder parameter to specify JPEG quality.
113 Dim encoder_param As SDF.Obj = hint_set.CreateDict()
114 encoder_param.PutNumber("Quality", 80)
115
116 ' Traverse all pages in the document.
117 Dim itr As PageIterator = doc.GetPageIterator()
118
119 While itr.HasNext()
120 Dim outname As String = String.Format("newsletter{0:d}.jpg", itr.GetPageNumber())
121 Console.WriteLine(outname)
122 draw.Export(itr.Current(), output_path + outname, "JPEG", encoder_param)
123 itr.Next()
124 End While
125
126 Console.WriteLine("Done.")
127 End Using
128 Catch e As PDFNetException
129 Console.WriteLine(e.Message)
130 End Try
131
132
133 ' Examples(3 - 6)
134 Try
135 ' Common code for remaining samples.
136 Using tiger_doc As PDFDoc = New PDFDoc(input_path + "tiger.pdf")
137 ' Initialize the security handler, in case the PDF is encrypted.
138 tiger_doc.InitSecurityHandler()
139 Dim page As Page = tiger_doc.GetPage(1)
140
141 '--------------------------------------------------------------------------------
142 ' Example 3) Convert the first page to GDI+ Bitmap. Also, rotate the
143 ' page 90 degrees and save the result as TIFF.
144 draw.SetDPI(100) ' Set the output resolution is to 100 DPI.
145 draw.SetRotate(page.Rotate.e_90) ' Rotate all pages 90 degrees clockwise.
146
147 Dim bmp As System.Drawing.Bitmap = draw.GetBitmap(page)
148 ' Save the raw RGB data to disk.
149 System.IO.File.WriteAllBytes(output_path + "tiger_100dpi_rot90.raw", BitmapToByteArray(bmp))
150
151 Console.WriteLine("Example 3: tiger_100dpi_rot90.raw")
152 draw.SetRotate(page.Rotate.e_0) ' Disable image rotation for remaining samples.
153
154 '--------------------------------------------------------------------------------
155 ' Example 4) Convert PDF page to a fixed image size. Also illustrates some
156 ' other features in PDFDraw class such as rotation, image stretching, exporting
157 ' to grayscale, or monochrome.
158
159 ' Initialize render 'gray_hint' parameter, that is used to control the
160 ' rendering process. In this case we tell the rasterizer to export the image as
161 ' 1 Bit Per Component (BPC) image.
162 Dim mono_hint As Obj = hint_set.CreateDict()
163 mono_hint.PutNumber("BPC", 1)
164
165 ' SetImageSize can be used instead of SetDPI() to adjust page scaling
166 ' dynamically so that given image fits into a buffer of given dimensions.
167 draw.SetImageSize(1000, 1000) ' Set the output image to be 1000 wide and 1000 pixels tall
168 draw.Export(page, output_path + "tiger_1000x1000.png", "PNG", mono_hint)
169 Console.WriteLine("Example 4: tiger_1000x1000.png")
170
171 draw.SetImageSize(200, 400) ' Set the output image to be 200 wide and 300 pixels tall
172 draw.SetRotate(page.Rotate.e_180) ' Rotate all pages 90 degrees clockwise.
173
174 ' 'gray_hint' tells the rasterizer to export the image as grayscale.
175 Dim gray_hint As Obj = hint_set.CreateDict()
176 gray_hint.PutName("ColorSpace", "Gray")
177
178 draw.Export(page, output_path + "tiger_200x400_rot180.png", "PNG", gray_hint)
179 Console.WriteLine("Example 4: tiger_200x400_rot180.png")
180
181 draw.SetImageSize(400, 200, False) ' The third parameter sets 'preserve-aspect-ratio' to false.
182 draw.SetRotate(page.Rotate.e_0) ' Disable image rotation.
183 draw.Export(page, output_path + "tiger_400x200_stretch.jpg", "JPEG")
184 Console.WriteLine("Example 4: tiger_400x200_stretch.jpg")
185
186
187 '--------------------------------------------------------------------------------
188 ' Example 5) Zoom into a specific region of the page and rasterize the
189 ' area at 200 DPI and as a thumbnail (i.e. a 50x50 pixel image).
190 page.SetCropBox(New Rect(216, 522, 330, 600)) ' Set the page crop box.
191
192 ' Select the crop region to be used for drawing.
193 draw.SetPageBox(page.Box.e_crop)
194 draw.SetDPI(900) ' Set the output image resolution to 900 DPI.
195 draw.Export(page, output_path + "tiger_zoom_900dpi.png", "PNG")
196 Console.WriteLine("Example 5: tiger_zoom_900dpi.png")
197
198 draw.SetImageSize(50, 50) ' Set the thumbnail to be 50x50 pixel image.
199 draw.Export(page, output_path + "tiger_zoom_50x50.png", "PNG")
200 Console.WriteLine("Example 6: tiger_zoom_50x50.png")
201 End Using
202 Catch e As PDFNetException
203 Console.WriteLine(e.Message)
204 End Try
205
206 Dim cmyk_hint As Obj = hint_set.CreateDict()
207 cmyk_hint.PutName("ColorSpace", "CMYK")
208
209 '--------------------------------------------------------------------------------
210 ' Example 7) Convert the first PDF page to CMYK TIFF at 92 DPI.
211 ' A three step tutorial to convert PDF page to an image.
212 Try
213 ' A) Open the PDF document.
214 Using doc As New PDFDoc(input_path & "tiger.pdf")
215 ' Initialize the security handler, in case the PDF is encrypted.
216 doc.InitSecurityHandler()
217
218 ' B) The output resolution is set to 92 DPI.
219 draw.SetDPI(92)
220
221 ' C) Rasterize the first page in the document and save the result as TIFF.
222 Dim pg As Page = doc.GetPage(1)
223 draw.Export(pg, output_path & "out1.tif", "TIFF", cmyk_hint)
224 Console.WriteLine("Example 7: out1.tif")
225 End Using
226 Catch e As PDFNetException
227 Console.WriteLine(e.Message)
228 End Try
229
230 '--------------------------------------------------------------------------------
231 ' Example 8) PDFRasterizer can be used for more complex rendering tasks, such as
232 ' strip by strip or tiled document rendering. In particular, it is useful for
233 ' cases where you cannot simply modify the page crop box (interactive viewing,
234 ' parallel rendering). This example shows how you can rasterize the south-west
235 ' quadrant of a page.
236 Using rast As PDFRasterizer = New PDFRasterizer
237 Try
238 ' A) Open the PDF document.
239 Using doc As PDFDoc = New PDFDoc(input_path & "tiger.pdf")
240 ' Initialize the security handler, in case the PDF is encrypted.
241 doc.InitSecurityHandler()
242
243 ' B) Get the page matrix
244 Dim pg As Page = doc.GetPage(1)
245 Dim box As Page.Box = Page.Box.e_crop
246 Dim mtx As Matrix2D = pg.GetDefaultMatrix(True, box)
247
248 ' We want to render a quadrant, so use half of width and height
249 Dim pg_w As Double = pg.GetPageWidth(box) / 2
250 Dim pg_h As Double = pg.GetPageHeight(box) / 2
251
252 ' C) Scale matrix from PDF space to buffer space
253 Dim dpi As Double = 96.0
254 Dim scale As Double = dpi / 72.0 ' PDF space is 72 dpi
255 Dim buf_w As Double = Math.Floor(scale * pg_w)
256 Dim buf_h As Double = Math.Floor(scale * pg_h)
257 Dim bytes_per_pixel As Integer = 4 ' RGBA buffer
258 Dim buf_size As Double = buf_w * buf_h * bytes_per_pixel
259 mtx.Translate(0, -pg_h) ' translate by '-pg_h' since we want south-west quadrant
260 mtx = (New Matrix2D(scale, 0, 0, scale, 0, 0)) * mtx
261
262 ' D) Rasterize page into memory buffer, according to our parameters
263 Dim buf As Byte() = rast.Rasterize(pg, CType(buf_w, Integer), CType(buf_h, Integer), CType(buf_w * bytes_per_pixel, Integer), bytes_per_pixel, True, mtx)
264
265
266 End Using
267 Console.WriteLine("Example 8: Successfully rasterized into memory buffer.")
268 Catch e As PDFNetException
269 Console.WriteLine(e.Message)
270 End Try
271 End Using
272
273 '--------------------------------------------------------------------------------
274 ' Example 9) Export raster content to PNG using different image smoothing settings.
275 Try
276 ' A) Open the PDF document.
277 Using doc As New PDFDoc(input_path & "lorem_ipsum.pdf")
278 ' Initialize the security handler, in case the PDF is encrypted.
279 doc.InitSecurityHandler()
280
281 ' B) The output resolution is set to 92 DPI.
282 draw.SetDPI(92)
283
284 ' C) Rasterize the first page in the document and save the result as TIFF.
285 Dim pg As Page = doc.GetPage(1)
286 ' Rasterize it without image smoothing
287 Dim filename As String = "raster_text_no_smoothing.png"
288 draw.SetImageSmoothing(False, False)
289 draw.Export(pg, output_path + filename)
290 Console.WriteLine("Example 9 a): " + filename + ". Done.")
291
292 ' Rasterize it with image smoothing
293 filename = "raster_text_smoothed.png"
294 draw.SetImageSmoothing(True, False)
295 draw.Export(pg, output_path + filename)
296 Console.WriteLine("Example 9 b): " + filename + ". Done.")
297
298 'rasterize it with high quality area resampling
299 filename = "raster_text_high_quality.png"
300 draw.SetImageSmoothing(True, True)
301 draw.Export(pg, output_path + filename)
302 Console.WriteLine("Example 9 c): " + filename + ". Done.")
303 End Using
304 Catch e As PDFNetException
305 Console.WriteLine(e.Message)
306 End Try
307
308 '--------------------------------------------------------------------------------
309 ' Example 10) Export separations directly, without conversion to an output colorspace
310 Try
311 Using separation_doc As New PDFDoc(input_path & "op_blend_test.pdf")
312
313 separation_doc.InitSecurityHandler()
314
315 Dim separation_hint As Obj = hint_set.CreateDict()
316 separation_hint.PutName("ColorSpace", "Separation")
317 draw.SetDPI(96)
318 draw.SetImageSmoothing(True, True)
319 'set overprint preview to always on
320 draw.SetOverprint(PDFRasterizer.OverprintPreviewMode.e_op_on)
321
322 Dim filename As String = "merged_separations.png"
323 draw.Export(separation_doc.GetPage(1), output_path & filename, "PNG")
324 Console.WriteLine("Example 10 a): " & filename + ". Done.")
325
326 filename = "separation"
327 draw.Export(separation_doc.GetPage(1), output_path & filename, "PNG", separation_hint)
328 Console.WriteLine("Example 10 b): " & filename & "_[ink].png. Done.")
329
330 filename = "separation_NChannel.tif"
331 draw.Export(separation_doc.GetPage(1), output_path & filename, "TIFF", separation_hint)
332 Console.WriteLine("Example 10 c): " & filename & ". Done.")
333 End Using
334
335 Catch e As PDFNetException
336 Console.WriteLine(e.Message)
337 End Try
338 End Using
339 PDFNet.Terminate()
340 End Sub
341
342
343 Public Function BitmapToByteArray(ByVal bitmap As Bitmap) As Byte()
344 Dim bmpdata As BitmapData = Nothing
345 Try
346 bmpdata = bitmap.LockBits(New Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, bitmap.PixelFormat)
347 Dim numbytes As Integer = (bmpdata.Stride * bitmap.Height)
348 Dim bytedata() As Byte = New Byte((numbytes) - 1) {}
349 Dim ptr As IntPtr = bmpdata.Scan0
350 Marshal.Copy(ptr, bytedata, 0, numbytes)
351 Return bytedata
352 Finally
353 If (Not (bmpdata) Is Nothing) Then
354 bitmap.UnlockBits(bmpdata)
355 End If
356
357 End Try
358
359 End Function
360
361End Module
Did you find this helpful?
Trial setup questions?
Ask experts on DiscordNeed other help?
Contact SupportPricing or product questions?
Contact Sales