Upload a PDF and Create Thumbnail Image in PHP

If you want to be able to upload .pdf files to your website and display an image thumbnail of the first page instead of a text link, this should cover the basics of how to achieve just that.

You will require Ghostscript and ImageMagick to be installed on your server - most linux hosting packages already have these installed.

Create a Simple Upload Form

First we need a simple upload for to upload our pdf document:

<form method="post" action="" enctype="multipart/form-data">
	<input type="file" name="pdf" />
	<input type="submit" name="submit" value="Upload" />
</form>

Target Directories

Create a folder to store your uploaded pdf file and name it "pdf". Now create a folder to store your thumbnail image and name it "pdfimage". Once we have the directories, we can set the paths to them in our PHP:

$pdfDirectory = "pdf/";
$thumbDirectory = "pdfimage/";

Next we need to format the file name of the uploaded file:

//get the name of the file
$filename = basename( $_FILES['pdf']['name'], ".pdf");

//remove all characters from the file name other than letters, numbers, hyphens and underscores
$filename = preg_replace("/[^A-Za-z0-9_-]/", "", $filename).".pdf";

//name the thumbnail image the same as the pdf file
$thumb = basename($filename, ".pdf");

The Fun Part

Now we put the .pdf file in to the "pdf" folder and set the variables for the two files. We also execute imageMagick's "convert" to convert the first page of the pdf to a jpg. The pages are an array so we use {$pdfWithPath}[0] for the first page ({$pdfWithPath}[1] would be page 2 and so on...). We set the color space to RGB and by setting the geometry to '200' we are setting the thumbnail to be 200px wide and the height will be proportionally set automatically. And finally, to see your handy work, we echo out the image and link it to the .pdf file:

if(move_uploaded_file($_FILES['pdf']['tmp_name'], $pdfDirectory.$filename)) {

//the path to the PDF file
$pdfWithPath = $pdfDirectory.$filename;

//add the desired extension to the thumbnail
$thumb = $thumb.".jpg";

//execute imageMagick's 'convert', setting the color space to RGB and size to 200px wide
exec("convert \"{$pdfWithPath}[0]\" -colorspace RGB -geometry 200 $thumbDirectory$thumb");
    
//show the image
echo "<p><a href=\"$pdfWithPath\"><img src=\"pdfimage/$thumb\" alt=\"\" /></a></p>";
}

Try It Out - Full Code

Wrap the whole thing in an if() statement to check whether or not the form has been submitted and we can put it all on one page and test it out:

<?php

if (isset($_POST['submit'])){

$pdfDirectory = "pdf/";
$thumbDirectory = "pdfimage/";

//get the name of the file
$filename = basename( $_FILES['pdf']['name'], ".pdf");

//remove all characters from the file name other than letters, numbers, hyphens and underscores
$filename = preg_replace("/[^A-Za-z0-9_-]/", "", $filename).".pdf";

//name the thumbnail image the same as the pdf file
$thumb = basename($filename, ".pdf");

	if(move_uploaded_file($_FILES['pdf']['tmp_name'], $pdfDirectory.$filename)) {
	
 	//the path to the PDF file
    $pdfWithPath = $pdfDirectory.$filename;
    
    //add the desired extension to the thumbnail
    $thumb = $thumb.".jpg";
    
	//execute imageMagick's 'convert', setting the color space to RGB and size to 200px wide
	exec("convert \"{$pdfWithPath}[0]\" -colorspace RGB -geometry 200 $thumbDirectory$thumb");
	    
	//show the image
	echo "<p><a href=\"$pdfWithPath\"><img src=\"pdfimage/$thumb\" alt=\"\" /></a></p>";
	}
}

?>

<form method="post" action="" enctype="multipart/form-data">
	<input type="file" name="pdf" />
	<input type="submit" name="submit" value="Upload" />
</form>

NOTE: It is not recommended that you use this for site visitors to execute without first adding some security, file-type checking etc... This is a barebones example which is safe to use yourself, but as with all upload scripts, you have to plan for attempted hacking and exploits. Also, you may want to think about unique file naming to avoid overwriting files of the same name.

For security reasons, I have not included a live demo.

Leave a Comment

All comments are appreciated. Comments are moderated before appearing on the site, so please don't bother trying leaving spam! Only genuine comments will be shown.

Your Name

Email Address (optional)

What year is it? (Spam Prevention)

Comment

Your Comments

Comment by echelon on 12th June 2014 @ 5:06 pm (GMT)

love the script. Helped me in my project in school. Keep it up. Ur the bomb

Comment by Dean on 16th May 2014 @ 10:05 am (GMT)

@hli - See the Note at the bottom of the article about security.
Swings and roundabouts really. In my case exec() is not disabled but iMagick is not installed.

Comment by hli on 16th May 2014 @ 10:05 am (GMT)

What about security? Why don't you use php's native imagemagick methods?
http://www.php.net/manual/en/book.imagick.php
exec should be disabled on most servers for security reasons!

Comment by ezzeddine on 12th May 2014 @ 11:05 am (GMT)

@Drean , well , it work :D
how can I security my pdf ??

Comment by Dean on 15th April 2014 @ 4:04 pm (GMT)

@ezzeddine did you alter the code at all? What error messages do you see (turn on error reporting. Did it upload? Was the image created? Did you create the directories...correct names etc..?

Comment by ezzeddine on 15th April 2014 @ 12:04 pm (GMT)

the picture did not show, I don't know why????

any help??

Comment by Robert on 18th October 2013 @ 2:10 am (GMT)

thnx the code make wonders

Comment by Kemah on 20th July 2013 @ 6:07 pm (GMT)

Wow, works great! Incredibly simple and awesome code! Thanks!!

Comment by ottakar on 18th May 2013 @ 8:05 pm (GMT)

Thx, this works better than imagick object

If you encountered problem with some black jpg render, try with the "-flatten" option:
"exec("convert \"{$pdfWithPath}[0]\" -flatten -colorspace RGB -geometry 200 $thumbFileWithPath");"

Comment by jayendra on 14th December 2012 @ 10:12 am (GMT)

Thanks to share. I will look into this.

Comment by Pauline on 19th September 2012 @ 11:09 am (GMT)

thanks and it's working. but it's still not directly opening the .pdf file.. :)

Comment by Dean on 19th September 2012 @ 11:09 am (GMT)

You should be inserting the image AND filename into the db on upload:
$query = "INSERT INTO applicants_access(image,filename) VALUES ('$image','$filename')";

Then when you want to display it:
$query = "select image,filename from applicants_access where applicant id = '$applicant_id'";

Then you just need to make your link "/applicants/images/'.$applicant_id.'/'.$filename.'"

Comment by Pauline on 19th September 2012 @ 11:09 am (GMT)

and here's my code for viewing .pdf file,
--------------
<a href="view.php">view</a>
--------------
view.php

<?php
include_once 'include/conn.inc.php';

$applicant_id = $_REQUEST['applicant_id'];

$query = "select image from applicants_access where applicant id = '$applicant_id'";
$src = "/applicants/images/" . $applicant_id;
//This is the directory where images will be saved
$target =$src;

$filename = $target;

$filename = preg_replace("/[^A-Za-z0-9_-]/", "", $filename).".pdf";

$thumb = basename($filename, ".pdf");

//header('Content-type: application/pdf');
//header("Content-Disposition: attachment; filename=\"$src\"");
//
$pdfWithPath = $target.$filename;
//$thumb = $thumb.".jpg";

//show the image
// echo '<a href="/applicants/images/'.$target.'">aade</a>';
echo "<p><a href=\"$src\"><font color='black'>aaaa</font></a></p>";
?>

Comment by Pauline on 19th September 2012 @ 10:09 am (GMT)

Here's my code to create file directory that will store my .pdf file in database.. hmmm, I tried my $target(my directory for inserting image in database) but it's not working.. hmmm..
-------------

$query = "INSERT INTO applicants_access(image) VALUES ('$image')";
$result = mysql_query($query)or die (mysql_error());

$arrayID=$db->fetch_array($db->query("SELECT LAST_INSERT_ID()"));
$id = $arrayID[0];

//this checks to make sure the directory does not already exist
if(!is_dir("images/".$id)){
//if the directory doesn't exist then make it
mkdir("images/".$id);

}

//This is the directory where images will be saved
$target = 'images/' . $id .'/';
$target = $target . basename( $_FILES['image']['name']);

if(move_uploaded_file($_FILES['image']['tmp_name'], $target))
{
header('Location: content.php');
}
else {
}

Comment by Dean on 19th September 2012 @ 10:09 am (GMT)

Does the script not already do that anyway? It should upload and then present you with a thumbnail of the recently uploaded file which is linked to the pdf document. Just make sure that on the line when you create $pdfWithPath variable the $filename variable is actually your filename you created

?>

Comment by Pauline on 19th September 2012 @ 10:09 am (GMT)

hmm what I mean is, I want to call the latest uploaded file..

Comment by Pauline on 19th September 2012 @ 10:09 am (GMT)

hello, its me again.. It works your code here at "/applicants/image/' , but when I open it, it open the directory of all uploaded .pdf files.. and it's listed all uploaded pdf file here http://localhost/applicants/images/400/ .. hmm, what do I need to do? what do you think? hmmm...

Comment by Dean on 19th September 2012 @ 10:09 am (GMT)

@Pauline - if I understand you correctly you will need to store the filename that you generate for each one in a database. i.e. a row with applicants_name, pdf_filename etc... then when you generate the page to display links you simply append the file name in your while{} loop to the path:
while($row = mysql_fetch_assoc($query){
echo '<p>'.$row['applicants_name'].':
<a href="/applicants/image/'.$row['pdf_filename'].'">Download</a></p>';
}

Comment by Pauline on 19th September 2012 @ 10:09 am (GMT)

nice, it works.. but may I ask, I am going to change the $pdfDirectory, linking to the .pdf file stored in /applicants/image/created id folder number, my created folder id number is I set an array that will create their unique folder name... my problem is, how can I retrieve my .pdf file in my created folder in drive c..
thanks for helping me :)

Comment by Dean on 5th September 2012 @ 10:09 am (GMT)

@Adam/Brett: You will have to elaborate on that. I am not sure exactly what you are wanting to do. If you can explain it a bit more clearly I will see what I can do.

Comment by Adam on 5th September 2012 @ 3:09 am (GMT)

Hey this is awesome and exactly what I am looking for... I have the same question as Brett (14th July 2012 @ 6:07am)... would that be hard to code up?

Comment by Taskin on 1st September 2012 @ 7:09 pm (GMT)

Awesome way to explain this ...nice work dude

Comment by Dean on 30th August 2012 @ 10:08 am (GMT)

Make sure that your target directory path is the same as the link to the file. If you use the code exactly as it is on the tutorial, it should work fine.

Comment by ajay on 29th August 2012 @ 8:08 pm (GMT)

thanks man But my pdf file is not opening which is behind the jpg file plss can u explainme wats the prb can be in it.

Comment by Brett on 14th July 2012 @ 6:07 am (GMT)

Hi, your script is excellent, I just have one request that I'm hoping you could help me with?
Can you please provide the PHP code to add each PDF thumbnail to a PHP Page?
At the moment, your script displays the PDF that was just uploaded, then disappears.
So rather displaying the individual Thumb as each PDF is uploaded, the page displays each PDF uploaded before and adds each PDF Thumb for every upload, so you have multiple columns of PDF Thumbs displaying each PDF. Is that hard to code?

Comment by Brett on 12th July 2012 @ 5:07 am (GMT)

Dude, you rock. At first I was like, not working, then Bam, the PDF Thumbnail shows and it's hyperlinked to the PDF! Wow!
Now I just need to work out how to place the uploaded thumbnails into html so I've got an iBook style webpage...
Thanks heaps for sharing.

Comment by rohit on 9th May 2012 @ 3:05 pm (GMT)

Nice work dude,very handy,thanx!

Comment by Henrik on 3rd May 2012 @ 9:05 am (GMT)

This is a lifesaver!

Comment by felipe on 8th February 2012 @ 3:02 pm (GMT)

Very thansk man.

Comment by Gary on 25th January 2012 @ 7:01 pm (GMT)

Thanks Dean, that solved the problem. The script ran perfectly!

Comment by Dean on 25th January 2012 @ 11:01 am (GMT)

Thanks for letting me know Gary. I have fixed the problem now. I had forgotten to include enctype="multipart/form-data" attribute in the form tag. It was failing because that is required when posting files.
Let me know how you get on!

Comment by Gary on 25th January 2012 @ 12:01 am (GMT)

I tried the script and it didn't work. Didn't give any errors, etc. It just skipped back to asking me to pick a file to upload. It didn't upload any files to the folders either. Any suggestions?

Comment by Seven on 18th August 2011 @ 6:08 pm (GMT)

What an asweome way to explain this-now I know everything!

Comment by Debrah on 18th August 2011 @ 6:08 am (GMT)

Oh yeah, faubolus stuff there you!

moo.com business card printing123-reg Domain namesteliad | Rank Better - Earn More

What's All This About?

Deanblog is a collection of articles written by Dean Morgan from Deanzod Limited. The aim of the site is to provide helpful information for everyone from web designers & developers right through to website owners. I will try and keep a good balance of information such as php/mySQL tutorials, html/css tutorials along with marketing ideas and advice for website owners.

Recent Articles