Home arrow PHP arrow PHP: Addings Images to Wordpress PDFs

PHP: Addings Images to Wordpress PDFs

In this programming tutorial, you will be learning how to use PHP and the R&OS PDF class to convert Wordpress posts to pdf's without losing article images in the process.

By: Codex-M
Rating: starstarstarstarstar / 0
August 11, 2011

print this article



Previously, I published two articles on converting Wordpress posts to PDF files without using a plug-in:

Part 1: http://www.seochat.com/c/a/Search-Engine-Optimization-Help/Convert-a-WordPress-Post-to-PDF-Without-a-Plugin-or-Module/

Part 2: http://www.seochat.com/c/a/Search-Engine-Optimization-Help/Adding-PDF-Conversion-to-Your-WordPress-Website/

In those examples, the scripts worked with one small glitch: they do not have the ability to include the Wordpress post images in the PDF file along with the text content.

As a demonstration of how the original application works, feel free to test this script: http://www.php-developer.org/wp-content/uploads/scripts/postpdfcreator.txt; and download this PHP class: http://www.ros.co.nz/pdf/downloads.php?f=pdfClassesAndFonts_009e.zip. You can also try implementing it on your own test site.

For example if you have this Wordpress post URL: http://www.php-developer.org/test/, the converted PDF file of this post using the original scripts provided above is this: http://www.php-developer.org/wp-content/uploads/tutorials/sample.pdf

You will not be able to see the images included in the PDF file. This tutorial will add this functionality. It will make the PDF equivalent of your Wordpress post as complete as possible with image support. This is a common problem when converting web page content to PDF. For example on this page: http://www.seochat.com/c/a/Search-Engine-Optimization-Help/Transferring-Web-Hosts-for-SEO-Issues/ , try clicking the SEO Chat “PDF Version Of Article” link. You will note that the converted PDF does not include images.

Strategy of Implementation

The first step in the analysis, is to break down the Wordpress post into components or parts such as those shown below (assume a Wordpress post with three images, although this application is designed to work with several images):

This means you can use PHP to grab the post content from the Wordpress database, then filter or segregate the content into different sections (in terms of  text and images) such as shown above. Then, once the content and images are well segregated, each of these components can safely be rendered by the PDF class.

In the R&OS PDF class, the following are important parameters when outputting PDFs in PHP:

Writing text content to PDF:

$pdf->eztext("This is your text",12);

The above line will write the text "This is your text" to a PDF document with font size 12.

Embedding Images to PDF

In this code:


The above line will embed images in the PDF document, with images hosted at this URL: http://www.yourwebsite.com/thisisimage.jpg, using padding set to 0, width to 300, resize to none, and justification to left.

Suppose you want to define two arrays to define the segregated sections as shown in the screenshot above. For the post text blocks, you would assign them in the following manner:

$textblocks= array();
$textblocks[0]= text content for the first block or paragraph.
$textblocks[1]= text content for the second block.
$textblocks[2] = text content for the third block.

For images, it would be:

$imageurls = array();
$imageurls[0] = Image URL for the first image.
$imageurls[1]= Image URL for the second image.

Now that its well defined, you can write it to a PDF document using the R&OS class by following the structure in the previous screenshot:

//Printing the first text block to PDF:
//Printing the first post image to PDF:
//Printing the second text block to PDF:
//Printing the second post image to PDF:
//Printing the third text block to PDF:

You can employ loops in the process to automate this procedure for different Wordpress posts with different number of blocks, as well as with number of images in the post.

The Problem with the PHP Strip Tags Function

If you are using the old script, you might have noticed that if your website content discusses PHP scripts, HTML coding, etc,  they won't be rendered in the PDF document (the same situation with the images) because it uses the PHP strip_tags function: http://php.net/manual/en/function.strip-tags.php

Therefore, a strip_tags function needs to be customized to allow HTML tags, comments and PHP scripts, as discussed in the Wordpress post, to be included in the PDF document. The following PHP function accomplishes this:

function stripTags($text$tags) {
//Title: Don't strip PHP tags function
//Credits: Abdul Al-hasany
// replace php and comments tags so they do not get stripped
$text preg_replace("@<?@""#?#"$text);
$text preg_replace("@<!--@""#!--#"$text);
// strip tags normally
$text strip_tags($text$tags);
// return php and comments tags to their origial form
$text preg_replace("@#?#@""<?"$text);
$text preg_replace("@#!--#@""<!--"$text);

To use it formally in the PHP script. The following is recommended:


Note that this line is similar to the old script, except that the strip_tags function is customized to allow PHP tags and comments. Also the following tags are allowed: <form><html>, and so forth. A very good working example will be shown towards the end of this tutorial, so that you can clearly understand the importance of this function.

The Complete and Revised postpdfcreator.php script: With Image functionality

Now you have a clear idea of what the script is going to accomplish, the following is the complete and revised postpdfcreator.php script with comments. For the best possible learning experience, compare it with the old script. Step 1 to Step 3 are the same as the old script; the rest has been substantially changed. This PHP script can be downloaded at the end of this tutorial.


//STEP1. Define Wordpress database connection parameters
$username = "wordpress_mysql_username";
$password = "wordpress_mysql_password";
$hostname = "wordpress_mysql_hostname";
$database = "wordpress_database_name";
$dbhandle = mysql_connect($hostname, $username, $password)
 or die("Unable to connect to MySQL");
$selected = mysql_select_db($database,$dbhandle)
or die("Could not select $database");

//STEP2. Retrieve GET request and sanitize inputs
$posttitle = mysql_real_escape_string(stripslashes($posttitle));

//STEP3. Retrieve the post content from Wordpress database.

$result = mysql_query("SELECT `post_content` FROM `wp_posts` WHERE `post_title`='$posttitle' AND `post_status`='publish'")
or die(mysql_error());
$row = mysql_fetch_array($result)
or die("Invalid query: " . mysql_error());
$content = $row['post_content'];

//STEP4. Count the total number of characters in the Wordpress post


//STEP5. Count the number of images in the Wordpress post content

$count_images = preg_match_all('/img/',$content,$dummyvar);

//STEP6.Create an array for storing image position in the document


//STEP7. Loop through the document and find out the position of all images. This is done by matching it with “img” for image tag.

while ($i<=$count_images) {
//get image position

//STEP8. Define the Text Blocks array. The use of this array is already discussed in the previous section.


//STEP9. Retrieve the text blocks in the Wordpress post by doing string manipulation.

while ($x<=$addtextblocks) {
//get text blocks and assign to text blocks array
if ($x==-1) {
else {
if ($x==$addtextblocks){
//max out
else {
if ($x==-1) { 
else {

//STEP10. Add the customized strip_tags function.

function stripTags($text, $tags) {
//Title: Don't strip PHP tags function
//Credits: Abdul Al-hasany
//replace php and comments tags so they do not get stripped 
$text = preg_replace("@<\?@", "#?#", $text);
$text = preg_replace("@<!--@", "#!--#", $text);
// strip tags normally
$text = strip_tags($text, $tags);
// return php and comments tags to their origial form
$text = preg_replace("@#\?#@", "<?", $text);
$text = preg_replace("@#!--#@", "<!--", $text);
return $text;

//STEP11. Retrieve the image URLs of the Wordpress post images.
This is done by defining first the $imageurls array.


//Do string manipulation to retrieve the image URLs and store it to $imageurls array.

while ($c<=$count_images) {
//start position to http://

//STEP12. Include the R&OS PDF Class

include ('class.ezpdf.php');
$pdf =& new Cezpdf();

//STEP13. Define the font type. Courier in this example.

//STEP14. Declare loop counter to 0, to be used in Step20.

$z=0;//For text blocks
$e=0;//For images

//STEP15.Count elements in text block array


//STEP16. Count elements in image URLs array

//STEP17. Define the author of the Wordpress blog


//STEP18. Define the URL of the website.

$pdf->eztext("<i>Website: <c:alink:http://www.php-developer.org>PHP Developer.org</c:alink></i>",12);

//STEP19. Define the Post title of the Wordpress post.

$pdf->eztext("Title: <b>$posttitle</b>",12);

//STEP20. Use loops to efficiently render the Wordpress text blocks and images
 to PDF Writer.

while (($z<=$maxtext) && ($e<=$maximages)) {

//Wordpress text block to be written to PDF


//Wordpress post images to be included in the PDF.


//STEP21. Stream the PDF to the user browser.

//STEP22. Close the MySQL connection


Project Files for Downloading and Implementation Tips

You can download the complete project files here:

Implementation Steps

1.) Download and unzip the package.

2.) Open postpdfcreator.php and define the following:
a.) Your Wordpress website MySQL connection parameters.
b.) Your font type (default is Courier).
c.) Your author name.
d.) Your blog URL and name.

2.) Upload postpdfcreator.php to the root directory of your Wordpress website.
3.) Upload the following files also to the root directory of your Wordpress website:

a.) class.ezpdf.php
b.) class.pdf.php
c.) fonts folder

4.) Edit your Wordpress template and add hyperlinks pointing to your postpdfcreator.php PDF creator template. Refer to this page for details: http://www.seochat.com/c/a/Search-Engine-Optimization-Help/Adding-PDF-Conversion-to-Your-WordPress-Website/3/

Follow only step 3 and step 4. As a working demo, you can find a sample here: http://www.php-developer.org/simple-php-proxy-detection-script-and-client-real-ip-address/ . Click “Click to save the PDF version of this post” and you will notice that the generated PDF now includes the post images as well as other details.


>>> More PHP Articles          >>> More By Codex-M

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort


- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates


Dev Shed Tutorial Topics: