Monday, January 7, 2013

Mail Merge HTML to PDF using PHP and TCPDF


Web pages are by their nature "pageless", in that they don't have defined sheets of pages as does a document that gets printed out or typed up in a word processor. For some web based applications though, creation of such documents is a requirement and there is a simple way to convert a html page into a PDF document for printing or emailing as required.

An example of this might be a web based system for producing documents such as : Quotes, Contract agreements, Invoices, business letters, etc

I am going to provide a very basic cut back method I have used in the past to produce a basic PDF document starting with a very simple dataset and a html template, using PHP and a free library called TCPDF.

I have added any error checking and so forth into this for simplicity sake. I will leave that to you to implement in accordance with your application.

Here goes :
Find the complete script here : https://gist.github.com/4481818

First you will need to create the dataset used to mail merge the document. This is simply an array where the keys are the fields that will be found in the html template and the data for each key is the data that will replace that field.

$merge_data = array(
 '[contactfirstname]' => 'Joe',
 '[contactlastname]' => 'Bloggs',
 '[contactfullname]' => 'Joe Bloggs',
 '[companyname]' => 'Fake Company',
 '[userfirstname]' => 'My',
 '[userlastname]' => 'Lastname',
 '[someotherfield]' => 'Some other data',
 ':)' => '<img src="http://www.veryicon.com/icon/16/System/Oxygen%201/Emotes%20face%20smile.png">',
);

Getting the html could be done in any number of ways. Getting it out of a database, loading from a file on the server or even a url.

$merge_html = file_get_contents('/some/protected/folder/with/permissions/template1.html');

Parsing the document to replace the fields with the appropriate data is also pretty simple.

// MERGE the html with the data in the fields
foreach($merge_data as $key => $value) {
 $merge_html = str_replace($key, $value, $merge_html);
}

After that we load the TCPDF library, extend it to have control over the header and footer and give it the merged html to process.

Please use the link above (https://gist.github.com/4481818) to see the full script, and please forgive the ad.

Got any questions? Ask them in the comments below.

1 comment:

  1. I'm trying to get this to work with a multi array so I can get a page per record I have in the database. I'm having difficulty getting this to happen though. Any suggestions of what I would need to do?

    ReplyDelete