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 UWP SDK and PDF Conversion Library.

1//
2// Copyright (c) 2001-2020 by PDFTron Systems Inc. All Rights Reserved.
3//
4
5using System;
6using System.IO;
7using System.Threading.Tasks;
8using System.Runtime.InteropServices.WindowsRuntime;
9using Windows.Foundation;
10using Windows.Graphics.Imaging;
11using Windows.Storage;
12using Windows.Storage.Streams;
13
14using pdftron.PDF;
15using pdftron.SDF;
16
17using PDFNetUniversalSamples.ViewModels;
18
19namespace PDFNetSamples
20{
21 public sealed class PDFDrawTest : Sample
22 {
23 public PDFDrawTest() :
24 base("PDFDraw", "This sample illustrates how to use the built-in rasterizer in order to render PDF images on the fly and how to save resulting images in PNG and JPEG format.")
25 {
26 }
27
28 public override IAsyncAction RunAsync()
29 {
30 return Task.Run(new System.Action(async () => {
31 WriteLine("--------------------------------");
32 WriteLine("Starting PDFDraw Test...");
33 WriteLine("--------------------------------\n");
34 await this.Run().ConfigureAwait(false);
35 WriteLine("\n--------------------------------");
36 WriteLine("Done PDFDraw Test.");
37 WriteLine("--------------------------------\n");
38 })).AsAsyncAction();
39 }
40
41 async Task Run()
42 {
43 /*
44 try
45 {
46 // Optional: Set ICC color profiles to fine tune color conversion
47 // for PDF 'device' color spaces. You can use your own ICC profiles.
48 // Standard Adobe color profiles can be download from Adobes site:
49 // http://www.adobe.com/support/downloads/iccprofiles/iccprofiles_win.html
50 //
51 // Simply drop all *.icc files in PDFNet resource folder or you specify
52 // the full pathname.
53 //---
54 // PDFNet.SetResourcesPath("../../../../../resources");
55 // PDFNet.SetColorManagement();
56 // PDFNet.SetDefaultDeviceCMYKProfile("USWebCoatedSWOP.icc"); // will search in PDFNet resource folder.
57 // PDFNet.SetDefaultDeviceRGBProfile("AdobeRGB1998.icc");
58
59 // Optional: Set predefined font mappings to override default font
60 // substitution for documents with missing fonts. For example:
61 //---
62 // PDFNet.AddFontSubst("StoneSans-Semibold", "C:/WINDOWS/Fonts/comic.ttf");
63 // PDFNet.AddFontSubst("StoneSans", "comic.ttf"); // search for 'comic.ttf' in PDFNet resource folder.
64 // PDFNet.AddFontSubst(PDFNet.CharacterOrdering.e_Identity, "C:/WINDOWS/Fonts/arialuni.ttf");
65 // PDFNet.AddFontSubst(PDFNet.CharacterOrdering.e_Japan1, "C:/Program Files/Adobe/Acrobat 7.0/Resource/CIDFont/KozMinProVI-Regular.otf");
66 // PDFNet.AddFontSubst(PDFNet.CharacterOrdering.e_Japan2, "c:/myfonts/KozMinProVI-Regular.otf");
67 //
68 // If fonts are in PDFNet resource folder, it is not necessary to specify
69 // the full path name. For example,
70 //---
71 // PDFNet.AddFontSubst(PDFNet.CharacterOrdering.e_Korea1, "AdobeMyungjoStd-Medium.otf");
72 // PDFNet.AddFontSubst(PDFNet.CharacterOrdering.e_CNS1, "AdobeSongStd-Light.otf");
73 // PDFNet.AddFontSubst(PDFNet.CharacterOrdering.e_GB1, "AdobeMingStd-Light.otf");
74 }
75 catch
76 {
77 WriteLine("The specified color profile was not found.");
78 }
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(Path.Combine(InputPath, "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 pdftron.PDF.Page pg = doc.GetPage(1);
99 String output_file_path = Path.Combine(OutputPath, "tiger_92dpi.png");
100 draw.Export(pg, output_file_path);
101 WriteLine(String.Format("Example 1: Result saved in {0}", output_file_path));
102 await AddFileToOutputList(output_file_path).ConfigureAwait(false);
103
104 // Export the same page as TIFF
105 output_file_path = Path.Combine(OutputPath, "tiger_92dpi.tif");
106 draw.Export(pg, output_file_path, "TIFF");
107 await AddFileToOutputList(output_file_path).ConfigureAwait(false);
108 }
109 }
110 catch (Exception e)
111 {
112 WriteLine(GetExceptionMessage(e));
113 }
114
115 //--------------------------------------------------------------------------------
116 // Example 2) Convert the all pages in a given document to JPEG at 72 DPI.
117 ObjSet hint_set = new ObjSet(); // A collection of rendering 'hits'.
118 WriteLine("Example 2:");
119
120 try
121 {
122 using (PDFDoc doc = new PDFDoc(Path.Combine(InputPath, "newsletter.pdf")))
123 {
124 // Initialize the security handler, in case the PDF is encrypted.
125 doc.InitSecurityHandler();
126
127 draw.SetDPI(72); // Set the output resolution is to 72 DPI.
128
129 // Use optional encoder parameter to specify JPEG quality.
130 Obj encoder_param = hint_set.CreateDict();
131 encoder_param.PutNumber("Quality", 80);
132
133 // Traverse all pages in the document.
134 for (PageIterator itr = doc.GetPageIterator(); itr.HasNext(); itr.Next())
135 {
136 string output_file_path = string.Format(@"{0}\newsletter{1:d}.jpg", OutputPath, itr.GetPageNumber());
137 WriteLine(String.Format("\nResult saved in {0}", output_file_path));
138 draw.Export(itr.Current(), output_file_path, "JPEG", encoder_param);
139 await AddFileToOutputList(output_file_path).ConfigureAwait(false);
140 }
141 }
142 }
143 catch (Exception e)
144 {
145 WriteLine(GetExceptionMessage(e));
146 }
147
148 try // Examples 3-5
149 {
150 // Common code for remaining samples.
151
152 using (PDFDoc tiger_doc = new PDFDoc(Path.Combine(InputPath, "tiger.pdf")))
153 {
154 // Initialize the security handler, in case the PDF is encrypted.
155 tiger_doc.InitSecurityHandler();
156 pdftron.PDF.Page page = tiger_doc.GetPage(1);
157
158 //--------------------------------------------------------------------------------
159 // Example 3) Convert the first page to WriteableBitmap. Also, rotate the
160 // page 90 degrees and save the result as TIFF.
161 draw.SetDPI(100); // Set the output resolution is to 100 DPI.
162 draw.SetRotate(pdftron.PDF.PageRotate.e_90); // Rotate all pages 90 degrees clockwise.
163
164 StorageFolder storageFolder = ApplicationData.Current.TemporaryFolder;
165 StorageFile outputFile = await storageFolder.CreateFileAsync("tiger_100dpi_rot90.tif", CreationCollisionOption.ReplaceExisting);
166
167 var bmpInfo = await draw.GetRawBitmapAsync(page).AsTask().ConfigureAwait(false);
168 byte[] pixels = bmpInfo.Buffer;
169 int height = bmpInfo.Height;
170 int width = bmpInfo.Width;
171
172 int offset;
173
174 for (int row = 0; row < height; row++)
175 {
176 for (int col = 0; col < width; col++)
177 {
178 offset = (row * width * 4) + (col * 4);
179 byte B = pixels[offset];
180 byte G = pixels[offset + 1];
181 byte R = pixels[offset + 2];
182 byte A = pixels[offset + 3];
183
184 // convert to RGBA format for BitmapEncoder
185 pixels[offset] = R; // Red
186 pixels[offset + 1] = G; // Green
187 pixels[offset + 2] = B; // Blue
188 pixels[offset + 3] = A; // Alpha
189 }
190 }
191 IRandomAccessStream writeStream = await outputFile.OpenAsync(FileAccessMode.ReadWrite);
192 BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.TiffEncoderId, writeStream);
193 encoder.SetPixelData(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Premultiplied, (uint)width, (uint) height, 96, 96, pixels);
194 await encoder.FlushAsync().AsTask().ConfigureAwait(false);
195 await writeStream.GetOutputStreamAt(0).FlushAsync().AsTask().ConfigureAwait(false);
196
197 //bmp.Save(output_path + "tiger_100dpi_rot90.tif", System.Drawing.Imaging.ImageFormat.Tiff);
198 //Message += String.Format("\nExample 3: Result saved in {0}", output_path + "tiger_100dpi_rot90.tif");
199 draw.SetRotate(pdftron.PDF.PageRotate.e_0); // Disable image rotation for remaining samples.
200
201 //--------------------------------------------------------------------------------
202 // Example 4) Convert PDF page to a fixed image size. Also illustrates some
203 // other features in PDFDraw class such as rotation, image stretching, exporting
204 // to grayscale, or monochrome.
205
206 // Initialize render 'gray_hint' parameter, that is used to control the
207 // rendering process. In this case we tell the rasterizer to export the image as
208 // 1 Bit Per Component (BPC) image.
209 Obj mono_hint = hint_set.CreateDict();
210 mono_hint.PutNumber("BPC", 1);
211
212 // SetImageSize can be used instead of SetDPI() to adjust page scaling
213 // dynamically so that given image fits into a buffer of given dimensions.
214 String output_file_path = Path.Combine(OutputPath, "tiger_1000x1000.png");
215 draw.SetImageSize(1000, 1000); // Set the output image to be 1000 wide and 1000 pixels tall
216 draw.Export(page, output_file_path, "PNG", mono_hint);
217 await AddFileToOutputList(output_file_path).ConfigureAwait(false);
218 WriteLine(String.Format("\nExample 4: Result saved in {0}", output_file_path));
219
220 draw.SetImageSize(200, 400); // Set the output image to be 200 wide and 300 pixels tall
221 draw.SetRotate(pdftron.PDF.PageRotate.e_180); // Rotate all pages 90 degrees clockwise.
222
223 // 'gray_hint' tells the rasterizer to export the image as grayscale.
224 Obj gray_hint = hint_set.CreateDict();
225 gray_hint.PutName("ColorSpace", "Gray");
226
227 output_file_path = Path.Combine(OutputPath, "tiger_200x400_rot180.png");
228 draw.Export(page, output_file_path, "PNG", gray_hint);
229 WriteLine(String.Format("\nExample 4: Result saved in {0}", output_file_path));
230 await AddFileToOutputList(output_file_path).ConfigureAwait(false);
231
232 draw.SetImageSize(400, 200, false, true); // The third parameter sets 'preserve-aspect-ratio' to false.
233 draw.SetRotate(pdftron.PDF.PageRotate.e_0); // Disable image rotation.
234 output_file_path = Path.Combine(OutputPath, "tiger_400x200_stretch.jpg");
235 draw.Export(page, output_file_path, "JPEG");
236 WriteLine(String.Format("\nExample 4: Result saved in {0}", output_file_path));
237 await AddFileToOutputList(output_file_path).ConfigureAwait(false);
238
239 //--------------------------------------------------------------------------------
240 // Example 5) Zoom into a specific region of the page and rasterize the
241 // area at 200 DPI and as a thumbnail (i.e. a 50x50 pixel image).
242 page.SetCropBox(new pdftron.PDF.Rect(216, 522, 330, 600)); // Set the page crop box.
243
244 // Select the crop region to be used for drawing.
245 draw.SetPageBox(pdftron.PDF.PageBox.e_crop);
246 draw.SetDPI(900); // Set the output image resolution to 900 DPI.
247 output_file_path = Path.Combine(OutputPath, "tiger_zoom_900dpi.png");
248 draw.Export(page, output_file_path, "PNG");
249 WriteLine(String.Format("\nExample 5: Result saved in {0}", output_file_path));
250 await AddFileToOutputList(output_file_path).ConfigureAwait(false);
251
252 draw.SetImageSize(50, 50); // Set the thumbnail to be 50x50 pixel image.
253 output_file_path = Path.Combine(OutputPath, "tiger_zoom_50x50.png");
254 draw.Export(page, output_file_path, "PNG");
255 WriteLine(String.Format("\nExample 6: Result saved in {0}", output_file_path));
256 await AddFileToOutputList(output_file_path).ConfigureAwait(false);
257 }
258 }
259 catch (Exception e)
260 {
261 WriteLine(GetExceptionMessage(e));
262 }
263
264 Obj cmyk_hint = hint_set.CreateDict();
265 cmyk_hint.PutName("ColorSpace", "CMYK");
266
267 //--------------------------------------------------------------------------------
268 // Example 7) Convert the first PDF page to CMYK TIFF at 92 DPI.
269 // A three step tutorial to convert PDF page to an image.
270 try
271 {
272 // A) Open the PDF document.
273 using (PDFDoc doc = new PDFDoc(Path.Combine(InputPath, "tiger.pdf")))
274 {
275 // Initialize the security handler, in case the PDF is encrypted.
276 doc.InitSecurityHandler();
277
278 // B) The output resolution is set to 92 DPI.
279 draw.SetDPI(92);
280
281 // C) Rasterize the first page in the document and save the result as TIFF.
282 String output_file_path = Path.Combine(OutputPath, "out1.tif");
283 pdftron.PDF.Page pg = doc.GetPage(1);
284 draw.Export(pg, output_file_path, "TIFF", cmyk_hint);
285 WriteLine(String.Format("\nExample 7: Result saved in {0}", output_file_path));
286 await AddFileToOutputList(output_file_path).ConfigureAwait(false);
287 }
288 }
289 catch (Exception e)
290 {
291 WriteLine(GetExceptionMessage(e));
292 }
293 // using PDFDraw
294 }
295 }
296 }
297}

Did you find this helpful?

Trial setup questions?

Ask experts on Discord

Need other help?

Contact Support

Pricing or product questions?

Contact Sales