PDF to Image Conversion Using PHP

Banner for a MediaJam post

Eugene Musebe

Introduction

There are numerous PDF readers, and applications accessible for free on the internet that can help you open and view PDF document files. But, to really make changes to a PDF, you need something more advanced. This article demonstrates a PDF converter tool to convert PDF to image and how Cloudinary can be vital to achieving such a process.

Github

Access the project's codebase on Github.

Phpsandbox

Click this link to view the working application demo Phpsandbox

Prerequisites

Entry-level html and php knowledge.

Setting Up the Sample Project

Create a new folder: phppdf2png Inside the new folder's terminal use the command composer init. You must have PHP and composer downloaded to your machine.

Follow the composer procedure which will help handle the necessary project dependencies. When asked to search for a package, search for Cloudinary

Cloudinary

Cloudinary refers to an end-to-end image and video management solution for websites and mobile apps, covering everything from image and video uploads, storage, manipulations, optimizations to delivery. Our app will use the media file online upload feature. To begin, click here to set up a new account or log in to an existing one. We use the environment keys from the user dashboard to integrate Cloudinary with our project. We will create a file named env and use the guide below to fill in the project configuration.

1CLOUDINARY_NAME=
2 CLOUDINARY_API_KEY=
3 CLOUDINARY_API_SECRET=
4 GOOGLE_API_KE=

Our app will include 2 sections; html and PHP. Start by creating a directory index.php and including the following:

1"index.php"
2
3
4<!doctype html>
5<html lang="en">
6 <head>
7 <meta charset="utf-8">
8 <meta name="viewport" content="width=device-width, initial-scale=1">
9 <title>PHP PDF to Image</title>
10
11 <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous">
12 <meta name="theme-color" content="#7952b3">
13
14 </head>
15 <body>
16
17
18<div class="container py-3">
19 <header>
20 <div class="pricing-header p-3 pb-md-4 mx-auto text-center">
21 <h3 class="display-4 fw-normal">Php pdf to Image</h3>
22 </div>
23 </header>
24
25 <main>
26 <form action="" method="POST" enctype="multipart/form-data">
27 <div class="form-row">
28 <div class="form-group col-md-4 offset-4">
29 <label class="sr-only">Upload Pdf</label>
30 <input type="file" class="form-control" name="upload_file" placeholder="Select pdf file">
31 </div>
32 </div>
33 <div class="form-row">
34 <div class="form-group col-md-4 offset-4">
35 <label class="sr-only">Page number</label>
36 <input type="text" class="form-control" name="page_no" placeholder="Page number to convert" min="1">
37 </div>
38 </div>
39 <div class="form-row">
40 <div class="form-group col-md-4 offset-4">
41 <button type="submit" class="btn btn btn-dark">Convert to Image</button>
42 </div>
43 </div>
44 </form>
45
46 <div class="col">
47 <?php if(isset($_FILES['upload_file'])){ ?>
48 <img class="img-fluid" src="<?=$resp['url']?>" alt="response">
49 <?php }else { ?>
50 <h2 class="display-6 text-center mb-4">Upload pdf</h2>
51 <?php } ?>
52 </div>
53 </main>
54</div>
55 </body>
56</html>

Above, we create an html web page titled PHP PDF to Image and import bootstrap for the UI styling. It will have a header, an input tag to upload pdf files, a form to insert the page number to convert and a button to activate the conversion. The picture will also be available on a user's Cloudinary media library. The result will look like below:

UI

Now to the php section:

Start by importing cloudinary.

1include_once __DIR__ . '/vendor/autoload.php';
2
3use Cloudinary\Api\Upload\UploadApi;
4use Cloudinary\Configuration\Configuration;

Confirm the post request has all the required parameters with values

1if (isset($_POST['page_no']) && isset($_FILES['upload_file'])){
2
3}

Instantiate Cloudinary SDK instance with credentials from env

1Configuration::instance([
2 'cloud' => [
3 'cloud_name' => getenv("CLOUDINARY_NAME"),
4 'api_key' => getenv("CLOUDINARY_API_KEY"),
5 'api_secret' => getenv("CLOUDINARY_API_SECRET")
6 ],
7 'url' => [
8 'secure' => true
9 ]
10 ]);

Extract the temporary file location for the uploaded file

1$file_tmp= $_FILES['upload_file']['tmp_name'];

Use the file location earlier extracted to generate the base64 encoded string equivalent for the uploaded file.

1$file_tmp= $_FILES['upload_file']['tmp_name'];
2
3$data = file_get_contents($file_tmp);
4$base64 = 'data:application/pdf;base64,' . base64_encode($data);

Upload the base64 string to cloudinary and apply the transformation to convert the file to image png. Additional options have been explained using the comments on the code snippet

1$resp = (new UploadApi())->upload($base64, [
2 'resource_type' => 'image',
3 'format'=> 'png', // for the transformation
4 'async' => false, // api to return the final status within the same session
5 'type' => 'upload',
6 ])

Thats it! Your final code should look like below:

1include_once __DIR__ . '/vendor/autoload.php';
2
3use Cloudinary\Api\Upload\UploadApi;
4use Cloudinary\Configuration\Configuration;
5
6
7// Confirm values for page number to be extracted and the file selection are okay
8if (isset($_POST['page_no']) && isset($_FILES['upload_file'])){
9
10 // Cloudinary instance setup globaly accros the whole application
11 Configuration::instance([
12 'cloud' => [
13 'cloud_name' => getenv("CLOUDINARY_NAME"),
14 'api_key' => getenv("CLOUDINARY_API_KEY"),
15 'api_secret' => getenv("CLOUDINARY_API_SECRET")
16 ],
17 'url' => [
18 'secure' => true
19 ]
20 ]);
21
22 // The the temp file storage location
23 $file_tmp= $_FILES['upload_file']['tmp_name'];
24
25 // get the file contents
26 $data = file_get_contents($file_tmp);
27
28 // base64 encode the file contents
29 $base64 = 'data:application/pdf;base64,' . base64_encode($data);
30
31
32 // Upload the file as png from pdf
33 $resp = (new UploadApi())->upload($base64, [
34 'resource_type' => 'image',
35 'format'=> 'png', // for the transformation
36 'async' => false, // api to return the final status within the same session
37 'type' => 'upload',
38 ]
39 );
40
41}
42
43<!doctype html>
44<html lang="en">
45 <head>
46 <meta charset="utf-8">
47 <meta name="viewport" content="width=device-width, initial-scale=1">
48 <title>PHP PDF to Image</title>
49
50 <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous">
51 <meta name="theme-color" content="#7952b3">
52
53 </head>
54 <body>
55
56
57<div class="container py-3">
58 <header>
59 <div class="pricing-header p-3 pb-md-4 mx-auto text-center">
60 <h3 class="display-4 fw-normal">Php pdf to Image</h3>
61 </div>
62 </header>
63
64 <main>
65 <form action="" method="POST" enctype="multipart/form-data">
66 <div class="form-row">
67 <div class="form-group col-md-4 offset-4">
68 <label class="sr-only">Upload Pdf</label>
69 <input type="file" class="form-control" name="upload_file" placeholder="Select pdf file">
70 </div>
71 </div>
72 <div class="form-row">
73 <div class="form-group col-md-4 offset-4">
74 <label class="sr-only">Page number</label>
75 <input type="text" class="form-control" name="page_no" placeholder="Page number to convert" min="1">
76 </div>
77 </div>
78 <div class="form-row">
79 <div class="form-group col-md-4 offset-4">
80 <button type="submit" class="btn btn btn-dark">Convert to Image</button>
81 </div>
82 </div>
83 </form>
84
85 <div class="col">
86 <?php if(isset($_FILES['upload_file'])){ ?>
87 <img class="img-fluid" src="<?=$resp['url']?>" alt="response">
88 <?php }else { ?>
89 <h2 class="display-6 text-center mb-4">Upload pdf</h2>
90 <?php } ?>
91 </div>
92 </main>
93</div>
94 </body>
95</html>

You've successfully created a pdf to image php converter. Enjoy the experience

Eugene Musebe

Software Developer

I’m a full-stack software developer, content creator, and tech community builder based in Nairobi, Kenya. I am addicted to learning new technologies and loves working with like-minded people.