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