Convert to PDF to PNG, JPG, BMP or TIFF - Java Sample Code

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

Did you find this helpful?

Trial setup questions?

Ask experts on Discord

Need other help?

Contact Support

Pricing or product questions?

Contact Sales