Convert to PDF to PNG, JPG, BMP or TIFF - PHP 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<?php
2//---------------------------------------------------------------------------------------
3// Copyright (c) 2001-2023 by Apryse Software Inc. All Rights Reserved.
4// Consult LICENSE.txt regarding license information.
5//---------------------------------------------------------------------------------------
6if(file_exists("../../../PDFNetC/Lib/PDFNetPHP.php"))
7include("../../../PDFNetC/Lib/PDFNetPHP.php");
8include("../../LicenseKey/PHP/LicenseKey.php");
9
10// Relative path to the folder containing the test files.
11$input_path = getcwd()."/../../TestFiles/";
12$output_path = $input_path."Output/";
13
14//---------------------------------------------------------------------------------------
15// The following sample illustrates how to convert PDF documents to various raster image
16// formats (such as PNG, JPEG, BMP, TIFF, etc), as well as how to convert a PDF page to
17// GDI+ Bitmap for further manipulation and/or display in WinForms applications.
18//---------------------------------------------------------------------------------------
19
20 // The first step in every application using PDFNet is to initialize the
21 // library and set the path to common PDF resources. The library is usually
22 // initialized only once, but calling Initialize() multiple times is also fine.
23 PDFNet::Initialize($LicenseKey);
24 PDFNet::GetSystemFontList(); // Wait for fonts to be loaded if they haven't already. This is done because PHP can run into errors when shutting down if font loading is still in progress.
25
26 // Optional: Set ICC color profiles to fine tune color conversion
27 // for PDF 'device' color spaces...
28
29 // PDFNet::SetResourcesPath("../../../resources");
30 // PDFNet::SetColorManagement();
31 // PDFNet::SetDefaultDeviceCMYKProfile("D:/Misc/ICC/USWebCoatedSWOP.icc");
32 // PDFNet::SetDefaultDeviceRGBProfile("AdobeRGB1998.icc"); // will search in PDFNet resource folder.
33
34 // ----------------------------------------------------
35 // Optional: Set predefined font mappings to override default font
36 // substitution for documents with missing fonts...
37
38 // PDFNet::AddFontSubst("StoneSans-Semibold", "C:/WINDOWS/Fonts/comic.ttf");
39 // PDFNet::AddFontSubst("StoneSans", "comic.ttf"); // search for 'comic.ttf' in PDFNet resource folder.
40 // PDFNet::AddFontSubst(PDFNet::e_Identity, "C:/WINDOWS/Fonts/arialuni.ttf");
41 // PDFNet::AddFontSubst(PDFNet::e_Japan1, "C:/Program Files/Adobe/Acrobat 7.0/Resource/CIDFont/KozMinProVI-Regular.otf");
42 // PDFNet::AddFontSubst(PDFNet::e_Japan2, "c:/myfonts/KozMinProVI-Regular.otf");
43 // PDFNet::AddFontSubst(PDFNet::e_Korea1, "AdobeMyungjoStd-Medium.otf");
44 // PDFNet::AddFontSubst(PDFNet::e_CNS1, "AdobeSongStd-Light.otf");
45 // PDFNet::AddFontSubst(PDFNet::e_GB1, "AdobeMingStd-Light.otf");
46 $draw = new PDFDraw();
47
48 //--------------------------------------------------------------------------------
49 // Example 1) Convert the first page to PNG and TIFF at 92 DPI.
50 // A three step tutorial to convert PDF page to an image.
51
52 // A) Open the PDF document.
53 $doc = new PDFDoc($input_path."tiger.pdf");
54
55 // Initialize the security handler, in case the PDF is encrypted.
56 $doc->InitSecurityHandler();
57
58 // B) The output resolution is set to 92 DPI.
59 $draw->SetDPI(92);
60
61 // C) Rasterize the first page in the document and save the result as PNG.
62 $ir = $doc->GetPageIterator();
63 $draw->Export($ir->Current(), $output_path."tiger_92dpi.png");
64
65 echo nl2br("Example 1: tiger_92dpi.png\n");
66
67 // Export the same page as TIFF
68 $draw->Export($ir->Current(), $output_path."tiger_92dpi.tif", "TIFF");
69
70 //--------------------------------------------------------------------------------
71 // Example 2) Convert the all pages in a given document to JPEG at 72 DPI.
72 echo nl2br("Example 2:\n");
73 $hint_set = new ObjSet(); // A collection of rendering 'hits'.
74
75 $doc = new PDFDoc($input_path."newsletter.pdf");
76 // Initialize the security handler, in case the PDF is encrypted.
77 $doc->InitSecurityHandler();
78
79 $draw->SetDPI(72); // Set the output resolution is to 72 DPI.
80
81 // Use optional encoder parameter to specify JPEG quality.
82 $encoder_param=$hint_set->CreateDict();
83 $encoder_param->PutNumber("Quality", 80);
84
85 // Traverse all pages in the document.
86 for ($itr=$doc->GetPageIterator(); $itr->HasNext(); $itr->Next()) {
87 $filename = "newsletter".$itr->Current()->GetIndex().".jpg";
88 echo nl2br($filename."\n");
89 $draw->Export($itr->Current(), $output_path.$filename, "JPEG", $encoder_param);
90 }
91
92 echo nl2br("Done.\n");
93
94 // Examples 3-5
95
96 // Common code for remaining samples.
97 $tiger_doc = new PDFDoc($input_path."tiger.pdf");
98 // Initialize the security handler, in case the PDF is encrypted.
99 $tiger_doc->InitSecurityHandler();
100 $page = $tiger_doc->GetPage(1);
101
102 //--------------------------------------------------------------------------------
103 // Example 3) Convert the first page to raw bitmap. Also, rotate the
104 // page 90 degrees and save the result as RAW.
105 $draw->SetDPI(100); // Set the output resolution is to 100 DPI.
106 $draw->SetRotate(Page::e_90); // Rotate all pages 90 degrees clockwise.
107
108 $bmp = $draw->GetBitmap($page, PDFDraw::e_rgb);
109
110 // Save the raw RGB data to disk.
111 file_put_contents($output_path."tiger_100dpi_rot90.raw", $bmp->GetBuffer());
112
113 echo nl2br("Example 3: tiger_100dpi_rot90.raw\n");
114 $draw->SetRotate(Page::e_0); // Disable image rotation for remaining samples.
115
116 //--------------------------------------------------------------------------------
117 // Example 4) Convert PDF page to a fixed image size. Also illustrates some
118 // other features in PDFDraw class such as rotation, image stretching, exporting
119 // to grayscale, or monochrome.
120
121 // Initialize render 'gray_hint' parameter, that is used to control the
122 // rendering process. In this case we tell the rasterizer to export the image as
123 // 1 Bit Per Component (BPC) image.
124 $mono_hint=$hint_set->CreateDict();
125 $mono_hint->PutNumber("BPC", 1);
126
127 // SetImageSize can be used instead of SetDPI() to adjust page scaling
128 // dynamically so that given image fits into a buffer of given dimensions.
129 $draw->SetImageSize(1000, 1000); // Set the output image to be 1000 wide and 1000 pixels tall
130 $draw->Export($page, $output_path."tiger_1000x1000.png", "PNG", $mono_hint);
131 echo nl2br("Example 4: tiger_1000x1000.png\n");
132
133 $draw->SetImageSize(200, 400); // Set the output image to be 200 wide and 300 pixels tall
134 $draw->SetRotate(Page::e_180); // Rotate all pages 90 degrees clockwise.
135
136 // 'gray_hint' tells the rasterizer to export the image as grayscale.
137 $gray_hint=$hint_set->CreateDict();
138 $gray_hint->PutName("ColorSpace", "Gray");
139
140 $draw->Export($page, $output_path."tiger_200x400_rot180.png", "PNG", $gray_hint);
141 echo nl2br("Example 4: tiger_200x400_rot180.png\n");
142
143 $draw->SetImageSize(400, 200, false); // The third parameter sets 'preserve-aspect-ratio' to false.
144 $draw->SetRotate(Page::e_0); // Disable image rotation.
145 $draw->Export($page, $output_path."tiger_400x200_stretch.jpg", "JPEG");
146 echo nl2br("Example 4: tiger_400x200_stretch.jpg\n");
147
148 //--------------------------------------------------------------------------------
149 // Example 5) Zoom into a specific region of the page and rasterize the
150 // area at 200 DPI and as a thumbnail (i.e. a 50x50 pixel image).
151 $zoom_rect = new Rect(216.0, 522.0, 330.0, 600.0);
152 $page->SetCropBox($zoom_rect); // Set the page crop box.
153
154 // Select the crop region to be used for drawing.
155 $draw->SetPageBox(Page::e_crop);
156 $draw->SetDPI(900); // Set the output image resolution to 900 DPI.
157 $draw->Export($page, $output_path."tiger_zoom_900dpi.png", "PNG");
158 echo nl2br("Example 5: tiger_zoom_900dpi.png\n");
159
160
161 // -------------------------------------------------------------------------------
162 // Example 6)
163 $draw->SetImageSize(50, 50); // Set the thumbnail to be 50x50 pixel image.
164 $draw->Export($page, $output_path."tiger_zoom_50x50.png", "PNG");
165 echo nl2br("Example 6: tiger_zoom_50x50.png\n");
166
167 $cmyk_hint = $hint_set->CreateDict();
168 $cmyk_hint->PutName("ColorSpace", "CMYK");
169
170 //--------------------------------------------------------------------------------
171 // Example 7) Convert the first PDF page to CMYK TIFF at 92 DPI.
172 // A three step tutorial to convert PDF page to an image
173 // A) Open the PDF document.
174 $doc = new PDFDoc($input_path."tiger.pdf");
175 // Initialize the security handler, in case the PDF is encrypted.
176 $doc->InitSecurityHandler();
177
178 // B) The output resolution is set to 92 DPI.
179 $draw->SetDPI(92);
180
181 // C) Rasterize the first page in the document and save the result as TIFF.
182 $pg = $doc->GetPage(1);
183 $draw->Export($pg, $output_path."out1.tif", "TIFF", $cmyk_hint);
184 echo nl2br("Example 7: out1.tif\n");
185
186 $doc->Close();
187
188 //--------------------------------------------------------------------------------
189 // Example 8) PDFRasterizer can be used for more complex rendering tasks, such as
190 // strip by strip or tiled document rendering. In particular, it is useful for
191 // cases where you cannot simply modify the page crop box (interactive viewing,
192 // parallel rendering). This example shows how you can rasterize the south-west
193 // quadrant of a page.
194 // A) Open the PDF document.
195 $doc = new PDFDoc($input_path."tiger.pdf");
196 // Initialize the security handler, in case the PDF is encrypted.
197 $doc->InitSecurityHandler();
198
199 // B) Get the page matrix
200 $pg = $doc->GetPage(1);
201 $box = Page::e_crop;
202 $mtx = $pg->GetDefaultMatrix(true, $box);
203 // We want to render a quadrant, so use half of width and height
204 $pg_w = $pg->GetPageWidth($box) / 2;
205 $pg_h = $pg->GetPageHeight($box) / 2;
206
207 // C) Scale matrix from PDF space to buffer space
208 $dpi = 96.0;
209 $scale = $dpi / 72.0; // PDF space is 72 dpi
210 $buf_w = (int)($scale * $pg_w);
211 $buf_h = (int)($scale * $pg_h);
212 $bytes_per_pixel = 4; // BGRA buffer
213 $buf_size = $buf_w * $buf_h * $bytes_per_pixel;
214 $mtx->Translate(0, -$pg_h); // translate by '-pg_h' since we want south-west quadrant
215 $mtx = new Matrix2D($scale, 0.0, 0.0, $scale, 0.0, 0.0);
216 $mtx->Multiply($mtx);
217
218 // D) Rasterize page into memory buffer, according to our parameters
219 $rast = new PDFRasterizer();
220 $buf = $rast->Rasterize($pg, $buf_w, $buf_h, $buf_w * $bytes_per_pixel, $bytes_per_pixel, true, $mtx);
221
222 // buf now contains raw BGRA bitmap.
223 echo nl2br("Example 8: Successfully rasterized into memory buffer.\n");
224
225 //--------------------------------------------------------------------------------
226 // Example 9) Export raster content to PNG using different image smoothing settings.
227 $text_doc = new PDFDoc($input_path."lorem_ipsum.pdf");
228 $text_doc->InitSecurityHandler();
229
230 $draw->SetImageSmoothing(false, false);
231 $filename = "raster_text_no_smoothing.png";
232 $ir = $text_doc->GetPageIterator();
233 $draw->Export($ir->Current(), $output_path.$filename);
234 echo nl2br("Example 9 a): ".$filename.". Done.\n");
235
236 $filename = "raster_text_smoothed.png";
237 $draw->SetImageSmoothing(true, false /*default quality bilinear resampling*/);
238 $draw->Export($ir->Current(), $output_path.$filename);
239 echo nl2br("Example 9 b): ".$filename.". Done.\n");
240
241 $filename = "raster_text_high_quality.png";
242 $draw->SetImageSmoothing(true, true /*high quality area resampling*/);
243 $draw->Export($ir->Current(), $output_path.$filename);
244 echo nl2br("Example 9 c): ".$filename.". Done.\n");
245
246 //--------------------------------------------------------------------------------
247 // Example 10) Export separations directly, without conversion to an output colorspace
248 $separation_doc = new PDFDoc($input_path."op_blend_test.pdf");
249 $separation_doc->InitSecurityHandler();
250 $separation_hint = $hint_set->CreateDict();
251 $separation_hint->PutName("ColorSpace", "Separation");
252 $draw->SetDPI(96);
253 $draw->SetImageSmoothing(true, true);
254 $draw->SetOverprint(PDFRasterizer::e_op_on);
255
256 $filename = "merged_separations.png";
257 $ir = $separation_doc->GetPageIterator();
258 $draw->Export($ir->Current(), $output_path.$filename, "PNG");
259 echo nl2br("Example 10 a): ".$filename.". Done.\n");
260
261 $filename = "separation";
262 $draw->Export($ir->Current(), $output_path.$filename, "PNG", $separation_hint);
263 echo nl2br("Example 10 b): ".$filename."_[ink].png. Done.\n");
264
265 $filename = "separation_NChannel.tif";
266 $draw->Export($ir->Current(), $output_path.$filename, "TIFF", $separation_hint);
267 echo nl2br("Example 10 c): ".$filename.". Done.\n");
268 PDFNet::Terminate();
269?>

Did you find this helpful?

Trial setup questions?

Ask experts on Discord

Need other help?

Contact Support

Pricing or product questions?

Contact Sales