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 Xamarin SDK and PDF Conversion Library.
1//---------------------------------------------------------------------------------------
2// Copyright (c) 2001-2021 by PDFTron Systems Inc. All Rights Reserved.
3// Consult legal.txt regarding legal and license information.
4//---------------------------------------------------------------------------------------
5
6using System;
7using System.Drawing;
8using System.Runtime.InteropServices;
9
10using pdftron;
11using pdftron.Common;
12using pdftron.PDF;
13using pdftron.SDF;
14
15using NUnit.Framework;
16
17namespace MiscellaneousSamples
18{
19 /// <summary>
20 //---------------------------------------------------------------------------------------
21 // The following sample illustrates how to convert PDF documents to various raster image
22 // formats (such as PNG, JPEG, BMP, TIFF), as well as how to convert a PDF page to GDI+ Bitmap
23 // for further manipulation and/or display in WinForms applications.
24 //---------------------------------------------------------------------------------------
25 /// </summary>
26 [TestFixture]
27 public class PDFDrawTest
28 {
29
30 /// <summary>
31 /// The main entry point for the application.
32 /// </summary>
33 [Test]
34 public static void Sample()
35 {
36 // The first step in every application using PDFNet is to initialize the
37 // library and set the path to common PDF resources. The library is usually
38 // initialized only once, but calling Initialize() multiple times is also fine.
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 const string input_path = "TestFiles/";
78
79
80 using (PDFDraw draw = new PDFDraw())
81 {
82 //--------------------------------------------------------------------------------
83 // Example 1) Convert the first PDF page to PNG at 92 DPI.
84 // A three step tutorial to convert PDF page to an image.
85 try
86 {
87 // A) Open the PDF document.
88 using (PDFDoc doc = new PDFDoc(Utils.GetAssetTempFile(input_path + "tiger.pdf")))
89 {
90 // Initialize the security handler, in case the PDF is encrypted.
91 doc.InitSecurityHandler();
92
93 // B) The output resolution is set to 92 DPI.
94 draw.SetDPI(92);
95
96 // C) Rasterize the first page in the document and save the result as PNG.
97 Page pg = doc.GetPage(1);
98 draw.Export(pg, Utils.CreateExternalFile("tiger_92dpi.png"));
99
100 Console.WriteLine("Example 1: tiger_92dpi.png");
101
102 // Export the same page as TIFF
103 draw.Export(pg, Utils.CreateExternalFile("tiger_92dpi.tif"), "TIFF");
104 }
105 }
106 catch (PDFNetException e) {
107 Console.WriteLine(e.Message);
108 Assert.True(false);
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(Utils.GetAssetTempFile(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(), Utils.CreateExternalFile(output_filename), "JPEG", encoder_param);
134 }
135 }
136
137 Console.WriteLine("Done.");
138 }
139 catch (PDFNetException e)
140 {
141 Console.WriteLine(e.Message);
142 Assert.True(false);
143 }
144
145 try // Examples 3-6
146 {
147 // Common code for remaining samples.
148 using (PDFDoc tiger_doc = new PDFDoc(Utils.GetAssetTempFile(input_path + "tiger.pdf")))
149 {
150 // Initialize the security handler, in case the PDF is encrypted.
151 tiger_doc.InitSecurityHandler();
152 Page page = tiger_doc.GetPage(1);
153
154 //--------------------------------------------------------------------------------
155 // Example 3) Convert the first page to GDI+ Bitmap. Also, rotate the
156 // page 90 degrees and save the result as RAW.
157 draw.SetDPI(100); // Set the output resolution is to 100 DPI.
158 draw.SetRotate(Page.Rotate.e_90); // Rotate all pages 90 degrees clockwise.
159
160 BitmapInfo buf = draw.GetBitmap(page, PDFDraw.PixelFormat.e_rgb, false);
161
162 // Save the raw RGB data to disk.
163 string filename = "tiger_100dpi_rot90.raw";
164
165 System.IO.File.WriteAllBytes(Utils.CreateExternalFile(filename), buf.Buffer);
166
167 Console.WriteLine("Example 3: tiger_100dpi_rot90.raw");
168 draw.SetRotate(Page.Rotate.e_0); // Disable image rotation for remaining samples.
169
170 //--------------------------------------------------------------------------------
171 // Example 4) Convert PDF page to a fixed image size. Also illustrates some
172 // other features in PDFDraw class such as rotation, image stretching, exporting
173 // to grayscale, or monochrome.
174
175 // Initialize render 'gray_hint' parameter, that is used to control the
176 // rendering process. In this case we tell the rasterizer to export the image as
177 // 1 Bit Per Component (BPC) image.
178 Obj mono_hint=hint_set.CreateDict();
179 mono_hint.PutNumber("BPC", 1);
180
181 // SetImageSize can be used instead of SetDPI() to adjust page scaling
182 // dynamically so that given image fits into a buffer of given dimensions.
183 draw.SetImageSize(1000, 1000); // Set the output image to be 1000 wide and 1000 pixels tall
184 draw.Export(page, Utils.CreateExternalFile("tiger_1000x1000.png"), "PNG", mono_hint);
185 Console.WriteLine("Example 4: tiger_1000x1000.png");
186
187 draw.SetImageSize(200, 400); // Set the output image to be 200 wide and 300 pixels tall
188 draw.SetRotate(Page.Rotate.e_180); // Rotate all pages 90 degrees clockwise.
189
190 // 'gray_hint' tells the rasterizer to export the image as grayscale.
191 Obj gray_hint=hint_set.CreateDict();
192 gray_hint.PutName("ColorSpace", "Gray");
193
194 draw.Export(page, Utils.CreateExternalFile("tiger_200x400_rot180.png"), "PNG", gray_hint);
195 Console.WriteLine("Example 4: tiger_200x400_rot180.png");
196
197 draw.SetImageSize(400, 200, false); // The third parameter sets 'preserve-aspect-ratio' to false.
198 draw.SetRotate(Page.Rotate.e_0); // Disable image rotation.
199 draw.Export(page, Utils.CreateExternalFile("tiger_400x200_stretch.jpg"), "JPEG");
200 Console.WriteLine("Example 4: tiger_400x200_stretch.jpg");
201
202 //--------------------------------------------------------------------------------
203 // Example 5) Zoom into a specific region of the page and rasterize the
204 // area at 200 DPI and as a thumbnail (i.e. a 50x50 pixel image).
205 page.SetCropBox(new Rect(216, 522, 330, 600)); // Set the page crop box.
206
207 // Select the crop region to be used for drawing.
208 draw.SetPageBox(Page.Box.e_crop);
209 draw.SetDPI(900); // Set the output image resolution to 900 DPI.
210 draw.Export(page, Utils.CreateExternalFile("tiger_zoom_900dpi.png"), "PNG");
211 Console.WriteLine("Example 5: tiger_zoom_900dpi.png");
212
213 // -------------------------------------------------------------------------------
214 // Example 6)
215 draw.SetImageSize(50, 50); // Set the thumbnail to be 50x50 pixel image.
216 draw.Export(page, Utils.CreateExternalFile("tiger_zoom_50x50.png"), "PNG");
217 Console.WriteLine("Example 6: tiger_zoom_50x50.png");
218 }
219 }
220 catch (PDFNetException e)
221 {
222 Console.WriteLine(e.Message);
223 Assert.True(false);
224 }
225
226 Obj cmyk_hint = hint_set.CreateDict();
227 cmyk_hint.PutName("ColorSpace", "CMYK");
228
229 //--------------------------------------------------------------------------------
230 // Example 7) Convert the first PDF page to CMYK TIFF at 92 DPI.
231 // A three step tutorial to convert PDF page to an image.
232 try
233 {
234 // A) Open the PDF document.
235 using (PDFDoc doc = new PDFDoc(Utils.GetAssetTempFile(input_path + "tiger.pdf")))
236 {
237 // Initialize the security handler, in case the PDF is encrypted.
238 doc.InitSecurityHandler();
239
240 // B) The output resolution is set to 92 DPI.
241 draw.SetDPI(92);
242
243 // C) Rasterize the first page in the document and save the result as TIFF.
244 Page pg = doc.GetPage(1);
245 draw.Export(pg, Utils.CreateExternalFile("out1.tif"), "TIFF", cmyk_hint);
246 Console.WriteLine("Example 7: out1.tif");
247 }
248 }
249 catch (PDFNetException e)
250 {
251 Console.WriteLine(e.Message);
252 Assert.True(false);
253 }
254
255 //--------------------------------------------------------------------------------
256 // Example 8) Export raster content to PNG using different image smoothing settings.
257 try
258 {
259 // A) Open the PDF document.
260 using (PDFDoc doc = new PDFDoc(Utils.GetAssetTempFile(input_path + "tiger.pdf")))
261 {
262 // Initialize the security handler, in case the PDF is encrypted.
263 doc.InitSecurityHandler();
264
265 // B) Get the page matrix
266 Page pg = doc.GetPage(1);
267 Page.Box box = Page.Box.e_crop;
268 Matrix2D mtx = pg.GetDefaultMatrix(true, box);
269 // We want to render a quadrant, so use half of width and height
270 double pg_w = pg.GetPageWidth(box) / 2;
271 double pg_h = pg.GetPageHeight(box) / 2;
272
273 // C) Scale matrix from PDF space to buffer space
274 double dpi = 96.0;
275 double scale = dpi / 72.0; // PDF space is 72 dpi
276 int buf_w = (int) (Math.Floor(scale * pg_w));
277 int buf_h = (int) (Math.Floor(scale * pg_h));
278 int bytes_per_pixel = 4; // BGRA buffer
279 int buf_size = buf_w * buf_h * bytes_per_pixel;
280 mtx.Translate(0, -pg_h); // translate by '-pg_h' since we want south-west quadrant
281 mtx = new Matrix2D(scale, 0, 0, scale, 0, 0) * mtx;
282
283 // D) Rasterize page into memory buffer, according to our parameters
284 byte[] buf;
285 PDFRasterizer rast = new PDFRasterizer();
286 buf = rast.Rasterize(pg, buf_w, buf_h, buf_w * bytes_per_pixel, bytes_per_pixel, true, mtx);
287
288 // buf now contains raw BGRA bitmap.
289 Console.WriteLine("Example 8: Successfully rasterized into memory buffer.");
290 }
291 }
292 catch (PDFNetException e)
293 {
294 Console.WriteLine(e.Message);
295 Assert.True(false);
296 }
297 //--------------------------------------------------------------------------------
298 // Example 9) Export raster content to PNG using different image smoothing settings.
299 try
300 {
301 using (PDFDoc text_doc = new PDFDoc(Utils.GetAssetTempFile(input_path + "lorem_ipsum.pdf")))
302 {
303 text_doc.InitSecurityHandler();
304
305 draw.SetImageSmoothing(false, false);
306 string filename = "raster_text_no_smoothing.png";
307 draw.Export(text_doc.GetPageIterator().Current(), Utils.CreateExternalFile(filename));
308 Console.WriteLine("Example 9 a): " + filename + ". Done.");
309
310 filename = "raster_text_smoothed.png";
311 draw.SetImageSmoothing(true, false /*default quality bilinear resampling*/);
312 draw.Export(text_doc.GetPageIterator().Current(), Utils.CreateExternalFile(filename));
313 Console.WriteLine("Example 9 b): " + filename + ". Done.");
314
315 filename = "raster_text_high_quality.png";
316 draw.SetImageSmoothing(true, true /*high quality area resampling*/);
317 draw.Export(text_doc.GetPageIterator().Current(), Utils.CreateExternalFile(filename));
318 Console.WriteLine("Example 9 c): " + filename + ". Done.");
319 }
320 }
321 catch (Exception e)
322 {
323 Console.WriteLine(e.Message);
324 Assert.True(false);
325 }
326
327 //--------------------------------------------------------------------------------
328 // Example 10) Export separations directly, without conversion to an output colorspace
329 try
330 {
331 using (PDFDoc separation_doc = new PDFDoc(Utils.GetAssetTempFile(input_path + "op_blend_test.pdf")))
332 {
333 separation_doc.InitSecurityHandler();
334 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.OverprintPreviewMode.e_op_on);
339
340 string filename = "merged_separations.png";
341 draw.Export(separation_doc.GetPageIterator().Current(), Utils.CreateExternalFile(filename), "PNG");
342 Console.WriteLine("Example 10 a): " + filename + ". Done.");
343
344 filename = "separation";
345 draw.Export(separation_doc.GetPageIterator().Current(), Utils.CreateExternalFile(filename), "PNG", separation_hint);
346 Console.WriteLine("Example 10 b): " + filename + "_[ink].png. Done.");
347
348 filename = "separation_NChannel.tif";
349 draw.Export(separation_doc.GetPageIterator().Current(), Utils.CreateExternalFile(filename), "TIFF", separation_hint);
350 Console.WriteLine("Example 10 c): " + filename + ". Done.");
351 }
352 }
353 catch (PDFNetException e)
354 {
355 Console.WriteLine(e.Message);
356 Assert.True(false);
357 }
358
359 } // using PDFDraw
360 }
361
362 }
363}
Did you find this helpful?
Trial setup questions?
Ask experts on DiscordNeed other help?
Contact SupportPricing or product questions?
Contact Sales