PDFDraw

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}

Did you find this helpful?

Trial setup questions?

Ask experts on Discord

Need other help?

Contact Support

Pricing or product questions?

Contact Sales