PDFDraw

Sample Java 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 Android SDK and PDF Conversion Library.

1//---------------------------------------------------------------------------------------
2// Copyright (c) 2001-2019 by PDFTron Systems Inc. All Rights Reserved.
3// Consult legal.txt regarding legal and license information.
4//---------------------------------------------------------------------------------------
5
6package com.pdftron.android.pdfnetsdksamples.samples;
7
8import com.pdftron.android.pdfnetsdksamples.OutputListener;
9import com.pdftron.android.pdfnetsdksamples.PDFNetSample;
10import com.pdftron.android.pdfnetsdksamples.R;
11import com.pdftron.android.pdfnetsdksamples.util.Utils;
12import com.pdftron.common.Matrix2D;
13import com.pdftron.pdf.PDFDoc;
14import com.pdftron.pdf.PDFDraw;
15import com.pdftron.pdf.PDFRasterizer;
16import com.pdftron.pdf.Page;
17import com.pdftron.pdf.PageIterator;
18import com.pdftron.pdf.Rect;
19import com.pdftron.sdf.Obj;
20import com.pdftron.sdf.ObjSet;
21
22import java.io.FileOutputStream;
23import java.nio.ByteBuffer;
24import java.nio.IntBuffer;
25import java.util.ArrayList;
26
27public class PDFDrawTest extends PDFNetSample {
28
29 private static OutputListener mOutputListener;
30
31 private static ArrayList<String> mFileList = new ArrayList<>();
32
33 public PDFDrawTest() {
34 setTitle(R.string.sample_pdfdraw_title);
35 setDescription(R.string.sample_pdfdraw_description);
36 }
37
38 @Override
39 public void run(OutputListener outputListener) {
40 super.run(outputListener);
41 mOutputListener = outputListener;
42 mFileList.clear();
43 printHeader(outputListener);
44 try {
45 // The first step in every application using PDFNet is to initialize the
46 // library and set the path to common PDF resources. The library is usually
47 // initialized only once, but calling Initialize() multiple times is also fine.
48
49 // Optional: Set ICC color profiles to fine tune color conversion
50 // for PDF 'device' color spaces...
51
52 //PDFNet.setResourcesPath("../../../resources");
53 //PDFNet.setColorManagement();
54 //PDFNet.setDefaultDeviceCMYKProfile("D:/Misc/ICC/USWebCoatedSWOP.icc");
55 //PDFNet.setDefaultDeviceRGBProfile("AdobeRGB1998.icc"); // will search in PDFNet resource folder.
56
57 // ----------------------------------------------------
58 // Optional: Set predefined font mappings to override default font
59 // substitution for documents with missing fonts...
60
61 // PDFNet.addFontSubst("StoneSans-Semibold", "C:/WINDOWS/Fonts/comic.ttf");
62 // PDFNet.addFontSubst("StoneSans", "comic.ttf"); // search for 'comic.ttf' in PDFNet resource folder.
63 // PDFNet.addFontSubst(PDFNet.e_Identity, "C:/WINDOWS/Fonts/arialuni.ttf");
64 // PDFNet.addFontSubst(PDFNet.e_Japan1, "C:/Program Files/Adobe/Acrobat 7.0/Resource/CIDFont/KozMinProVI-Regular.otf");
65 // PDFNet.addFontSubst(PDFNet.e_Japan2, "c:/myfonts/KozMinProVI-Regular.otf");
66 // PDFNet.addFontSubst(PDFNet.e_Korea1, "AdobeMyungjoStd-Medium.otf");
67 // PDFNet.addFontSubst(PDFNet.e_CNS1, "AdobeSongStd-Light.otf");
68 // PDFNet.addFontSubst(PDFNet.e_GB1, "AdobeMingStd-Light.otf");
69
70 PDFDraw draw = new PDFDraw(); // PDFDraw class is used to rasterize PDF pages.
71 ObjSet hint_set = new ObjSet();
72
73 //--------------------------------------------------------------------------------
74 // Example 1) Convert the first page to PNG and TIFF at 92 DPI.
75 // A three step tutorial to convert PDF page to an image.
76 try (PDFDoc doc = new PDFDoc((Utils.getAssetTempFile(INPUT_PATH + "tiger.pdf").getAbsolutePath()))) {
77 // A) Open the PDF document.
78
79 // Initialize the security handler, in case the PDF is encrypted.
80 doc.initSecurityHandler();
81
82 // B) The output resolution is set to 92 DPI.
83 draw.setDPI(92);
84
85 // C) Rasterize the first page in the document and save the result as PNG.
86 Page pg = doc.getPage(1);
87 draw.export(pg, (Utils.createExternalFile("tiger_92dpi.png", mFileList).getAbsolutePath()));
88 // output "tiger_92dpi.png"
89
90 mOutputListener.println("Example 1: tiger_92dpi.png");
91
92 // Export the same page as TIFF
93 draw.export(pg, (Utils.createExternalFile("tiger_92dpi.tif", mFileList).getAbsolutePath()), "TIFF");
94 // output "tiger_92dpi.tif"
95 } catch (Exception e) {
96 mOutputListener.printError(e.getStackTrace());
97 }
98
99 //--------------------------------------------------------------------------------
100 // Example 2) Convert the all pages in a given document to JPEG at 72 DPI.
101 mOutputListener.println("Example 2:");
102 try (PDFDoc doc = new PDFDoc((Utils.getAssetTempFile(INPUT_PATH + "newsletter.pdf").getAbsolutePath()))) {
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 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(); ) {
114 Page current = itr.next();
115 String filename = "newsletter" + current.getIndex() + ".jpg";
116 mOutputListener.println(filename);
117 draw.export(current, Utils.createExternalFile(filename, mFileList).getAbsolutePath(), "JPEG", encoder_param);
118 }
119
120 mOutputListener.println("Done.");
121 } catch (Exception e) {
122 mOutputListener.printError(e.getStackTrace());
123 }
124
125 FileOutputStream fos = null;
126 // Examples 3-5
127 try (PDFDoc tiger_doc = new PDFDoc((Utils.getAssetTempFile(INPUT_PATH + "tiger.pdf").getAbsolutePath()))) {
128 // Common code for remaining samples.
129 // Initialize the security handler, in case the PDF is encrypted.
130 tiger_doc.initSecurityHandler();
131 Page page = tiger_doc.getPageIterator().next();
132
133 //--------------------------------------------------------------------------------
134 // Example 3) Convert the first page to raw bitmap. Also, rotate the
135 // page 90 degrees and save the result as RAW.
136 draw.setDPI(100); // Set the output resolution is to 100 DPI.
137 draw.setRotate(Page.e_90); // Rotate all pages 90 degrees clockwise.
138
139 // create a Java image
140 android.graphics.Bitmap image = draw.getBitmap(page);
141
142 //
143 int width = image.getWidth(), height = image.getHeight();
144 int[] arr = new int[width * height];
145 image.getPixels(arr, 0, width, 0, 0, width, height);
146 // pg.grabPixels();
147
148 // convert to byte array
149 ByteBuffer byteBuffer = ByteBuffer.allocate(arr.length * 4);
150 IntBuffer intBuffer = byteBuffer.asIntBuffer();
151 intBuffer.put(arr);
152 byte[] rawByteArray = byteBuffer.array();
153 // finally write the file
154 fos = new FileOutputStream(Utils.createExternalFile("tiger_100dpi_rot90.raw", mFileList).getAbsolutePath());
155 fos.write(rawByteArray);
156 mOutputListener.println("Example 3: tiger_100dpi_rot90.raw");
157
158 draw.setRotate(Page.e_0); // Disable image rotation for remaining samples.
159
160 //--------------------------------------------------------------------------------
161 // Example 4) Convert PDF page to a fixed image size. Also illustrates some
162 // other features in PDFDraw class such as rotation, image stretching, exporting
163 // to grayscale, or monochrome.
164
165 // Initialize render 'gray_hint' parameter, that is used to control the
166 // rendering process. In this case we tell the rasterizer to export the image as
167 // 1 Bit Per Component (BPC) image.
168 Obj mono_hint = hint_set.createDict();
169 mono_hint.putNumber("BPC", 1);
170
171 // SetImageSize can be used instead of SetDPI() to adjust page scaling
172 // dynamically so that given image fits into a buffer of given dimensions.
173 draw.setImageSize(1000, 1000); // Set the output image to be 1000 wide and 1000 pixels tall
174
175 draw.export(page, (Utils.createExternalFile("tiger_1000x1000.png", mFileList).getAbsolutePath()), "PNG", mono_hint);
176 mOutputListener.println("Example 4: tiger_1000x1000.png");
177
178 draw.setImageSize(200, 400); // Set the output image to be 200 wide and 300 pixels tall
179 draw.setRotate(Page.e_180); // Rotate all pages 90 degrees clockwise.
180
181 // 'gray_hint' tells the rasterizer to export the image as grayscale.
182 Obj gray_hint = hint_set.createDict();
183 gray_hint.putName("ColorSpace", "Gray");
184
185 draw.export(page, (Utils.createExternalFile("tiger_200x400_rot180.png", mFileList).getAbsolutePath()), "PNG", gray_hint);
186 mOutputListener.println("Example 4: tiger_200x400_rot180.png");
187
188 draw.setImageSize(400, 200, false); // The third parameter sets 'preserve-aspect-ratio' to false.
189 draw.setRotate(Page.e_0); // Disable image rotation.
190 draw.export(page, (Utils.createExternalFile("tiger_400x200_stretch.jpg", mFileList).getAbsolutePath()), "JPEG");
191 // output "tiger_400x200_stretch.jpg"
192 mOutputListener.println("Example 4: tiger_400x200_stretch.jpg");
193
194 //--------------------------------------------------------------------------------
195 // Example 5) Zoom into a specific region of the page and rasterize the
196 // area at 200 DPI and as a thumbnail (i.e. a 50x50 pixel image).
197 Rect zoom_rect = new Rect(216, 522, 330, 600);
198 page.setCropBox(zoom_rect); // Set the page crop box.
199
200 // Select the crop region to be used for drawing.
201 draw.setPageBox(Page.e_crop);
202 draw.setDPI(900); // Set the output image resolution to 900 DPI.
203 draw.export(page, (Utils.createExternalFile("tiger_zoom_900dpi.png", mFileList).getAbsolutePath()), "PNG");
204 // output "tiger_zoom_900dpi.png"
205 mOutputListener.println("Example 5: tiger_zoom_900dpi.png");
206
207 // -------------------------------------------------------------------------------
208 // Example 6)
209 draw.setImageSize(50, 50); // Set the thumbnail to be 50x50 pixel image.
210 draw.export(page, (Utils.createExternalFile("tiger_zoom_50x50.png", mFileList).getAbsolutePath()), "PNG");
211 // output "tiger_zoom_50x50.png"
212 mOutputListener.println("Example 6: tiger_zoom_50x50.png");
213 } catch (Exception e) {
214 mOutputListener.printError(e.getStackTrace());
215 } finally {
216 if (fos != null) {
217 try {
218 fos.close();
219 } catch (Exception ignored) {
220 }
221 }
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 (PDFDoc doc = new PDFDoc(Utils.getAssetTempFile(INPUT_PATH + "tiger.pdf").getAbsolutePath())) {
231 // A) Open the PDF document.
232
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, Utils.createExternalFile("out1.tif", mFileList).getAbsolutePath(), "TIFF", cmyk_hint);
242 // output "out1.tif"
243 mOutputListener.println("Example 7: out1.tif");
244 } catch (Exception e) {
245 mOutputListener.printError(e.getStackTrace());
246 }
247
248 //--------------------------------------------------------------------------------
249 // Example 8) PDFRasterizer can be used for more complex rendering tasks, such as
250 // strip by strip or tiled document rendering. In particular, it is useful for
251 // cases where you cannot simply modify the page crop box (interactive viewing,
252 // parallel rendering). This example shows how you can rasterize the south-west
253 // quadrant of a page.
254 try (PDFDoc doc = new PDFDoc(Utils.getAssetTempFile(INPUT_PATH + "tiger.pdf").getAbsolutePath())) {
255 // A) Open the PDF document.
256 // Initialize the security handler, in case the PDF is encrypted.
257 doc.initSecurityHandler();
258
259 // B) Get the page matrix
260 Page pg = doc.getPage(1);
261 int box = Page.e_crop;
262 Matrix2D mtx = pg.getDefaultMatrix(true, box, 0);
263 // We want to render a quadrant, so use half of width and height
264 double pg_w = pg.getPageWidth(box) / 2;
265 double pg_h = pg.getPageHeight(box) / 2;
266
267 // C) Scale matrix from PDF space to buffer space
268 double dpi = 96.0;
269 double scale = dpi / 72.0; // PDF space is 72 dpi
270 double buf_w = Math.floor(scale * pg_w);
271 double buf_h = Math.floor(scale * pg_h);
272 int bytes_per_pixel = 4; // BGRA buffer
273 mtx.translate(0, -pg_h); // translate by '-pg_h' since we want south-west quadrant
274 mtx = (new Matrix2D(scale, 0, 0, scale, 0, 0)).multiply(mtx);
275
276 // D) Rasterize page into memory buffer, according to our parameters
277 PDFRasterizer rast = new PDFRasterizer();
278 byte[] buf = rast.rasterize(pg, (int) buf_w, (int) buf_h, (int) buf_w * bytes_per_pixel, bytes_per_pixel, true, mtx, null);
279
280 mOutputListener.println("Example 8: Successfully rasterized into memory buffer.");
281 } catch (Exception e) {
282 mOutputListener.printError(e.getStackTrace());
283 }
284
285 //--------------------------------------------------------------------------------
286 // Example 9) Export raster content to PNG using different image smoothing settings.
287 try (PDFDoc text_doc = new PDFDoc(Utils.getAssetTempFile(INPUT_PATH + "lorem_ipsum.pdf").getAbsolutePath())) {
288 text_doc.initSecurityHandler();
289
290 draw.setImageSmoothing(false, false);
291 String filename = "raster_text_no_smoothing.png";
292 draw.export(text_doc.getPageIterator().next(), Utils.createExternalFile(filename, mFileList).getAbsolutePath());
293 mOutputListener.println("Example 9 a): " + filename + ". Done.");
294
295 filename = "raster_text_smoothed.png";
296 draw.setImageSmoothing(true, false /*default quality bilinear resampling*/);
297 draw.export(text_doc.getPageIterator().next(), Utils.createExternalFile(filename, mFileList).getAbsolutePath());
298 mOutputListener.println("Example 9 b): " + filename + ". Done.");
299
300 filename = "raster_text_high_quality.png";
301 draw.setImageSmoothing(true, true /*high quality area resampling*/);
302 draw.export(text_doc.getPageIterator().next(), Utils.createExternalFile(filename, mFileList).getAbsolutePath());
303 mOutputListener.println("Example 9 c): " + filename + ". Done.");
304 } catch (Exception e) {
305 mOutputListener.printError(e.getStackTrace());
306 }
307
308 //--------------------------------------------------------------------------------
309 // Example 10) Export separations directly, without conversion to an output colorspace
310 try (PDFDoc separation_doc = new PDFDoc(Utils.getAssetTempFile(INPUT_PATH + "op_blend_test.pdf").getAbsolutePath())) {
311 separation_doc.initSecurityHandler();
312
313 Obj separation_hint = hint_set.createDict();
314 separation_hint.putName("ColorSpace", "Separation");
315 draw.setDPI(96);
316 draw.setImageSmoothing(true, true);
317 // set overprint preview to always on
318 draw.setOverprint(1);
319
320 String filename = new String("merged_separations.png");
321 draw.export(separation_doc.getPage(1), Utils.createExternalFile(filename, mFileList).getAbsolutePath(), "PNG");
322 mOutputListener.println("Example 10 a): " + filename + ". Done.");
323
324 filename = new String("separation");
325 draw.export(separation_doc.getPage(1), Utils.createExternalFile(filename, mFileList).getAbsolutePath(), "PNG", separation_hint);
326 mOutputListener.println("Example 10 b): " + filename + "_[ink].png. Done.");
327
328 filename = new String("separation_NChannel.tif");
329 draw.export(separation_doc.getPage(1), Utils.createExternalFile(filename, mFileList).getAbsolutePath(), "TIFF", separation_hint);
330 mOutputListener.println("Example 10 c): " + filename + ". Done.");
331 } catch (Exception e) {
332 mOutputListener.printError(e.getStackTrace());
333 }
334
335 // Calling Terminate when PDFNet is no longer in use is a good practice, but
336 // is not required.
337 } catch (Exception e) {
338 mOutputListener.printError(e.getStackTrace());
339 }
340
341 for (String file : mFileList) {
342 addToFileList(file);
343 }
344 printFooter(outputListener);
345 }
346
347}

Did you find this helpful?

Trial setup questions?

Ask experts on Discord

Need other help?

Contact Support

Pricing or product questions?

Contact Sales