Team LiB
Previous Section Next Section

Generating Dynamic RTF Documents

When people think of RTF, it is in reference to the format supported by almost all major word processors. Surprisingly, despite its widespread support, there is an inclination to ignore this format when considering methods of generating printable documents. In reality, the RTF format is an extremely convenient method of generating printable documentation if the proper technique is used.

RTF documents, from a programmer's standpoint, are quite similar to HTML or XML documents in the sense that RTF is implemented using a markup language. Although vastly alien in structure to the facilities provided by common markup languages such as HTML, as you will see shortly, the similarities will prove quite useful in their generation.

To give you an idea of what a very simple RTF document looks like, let's look at one:

{\f0 Arial;}
{\f1 Times New Roman;}
\f0\fs60 PHP Unleashed\par
\f1\fs20 This is a simple RTF document, not bad, eh?\par

As you can see, this document could have easily been generated using a simple text editor. When opened up in a word processor such as Open Office, Microsoft Word, or any other major word processor, it is rendered as follows.

However, as simple as the preceding RTF example is, it is by no means representative of the vast majority of RTF documents generated. Most RTF documents are incredibly complex and difficult to decipher by hand or even with a computer application.

Figure 28.1. An example of a trivial RTF document when rendered.

Although RTF documents can be quite difficult to fully implement, one extremely important fact can be taken from our simplistic example. Because the actual content of the document is stored as plain text within the RTF file, almost any word processing application can be used to generate a template that can be filled in via a third entity such as a PHP script.

With this in mind, generating dynamic RTF documents can be broken into these simple steps:

Generate a template document with placeholders for dynamic content using your favorite word processor.

Open the template document in PHP.

Replace the placeholder strings within the document with the desired dynamic content.

Save the generated document or display it.

As you can see, there is little here that requires a great deal of effort from a development perspective. To start, a template must be generated. For our purposes, I'll be generating dynamic content for the following document:

Figure 28.2. A form letter example saved in RTF.

In this document, I have placed a number of placeholders, each of them in the format %%PLACEHOLDER%%, in which PLACEHOLDER is a unique string for each value to be filled in within the document. In the RTF document itself, each of these placeholders looks something like the following:

\par {\ltrch\Dear %%PREFIX%% %%LASTNAME%%,}

Now that the document has been generated, the process is simply a matter of opening the template from within a PHP script and making the necessary modifications. This entire process can be reduced to a single function I have provided, populate_RTF(), which is shown in Listing 28.1:

Listing 28.1. Generating RTF Documents from a Template

    function populate_RTF($vars, $doc_file) {

        $replacements = array ('\\' => "\\\\",
                               '{'  => "\{",
                               '}'  => "\}");

        $document = file_get_contents($doc_file);
        if(!$document) {
            return false;

        foreach($vars as $key=>$value) {
            $search = "%%".strtoupper($key)."%%";

            foreach($replacements as $orig => $replace) {
                $value = str_replace($orig, $replace, $value);

            $document = str_replace($search, $value, $document);

        return $document;


This function takes two parametersthe first, $vars, is an array of key/value pairs representing the placeholder and value for that placeholder. The second parameter, $doc_file, represents the template file to populate. Upon execution, this function returns a string representing the new RTF document with all the provided fields filled in. Therefore, assuming the template RTF file was stored in the file system as joboffer.rtf, an example of its use is shown in Listing 28.2:

Listing 28.2. Using the populate_RTF() Function


    /* Definition of the populate_RTF() function omitted */

    $deadline = mktime(0,0,0,date('m'),date('d')+14, date('Y'));

    $vars = array('date'     => date("F d, Y"),
                  'fullname' => 'John Coggeshall',
                  'address'  => '1210 Hancock',
                  'cityinfo' => 'Flint, MI 49449',
                  'prefix'   => 'Mr.',
                  'lastname' => 'Coggeshall',
                  'jobtitle' => 'PHP Developer',
                  'wage'     => '$5,000',
                  'location' => 'Somewhere, MI',
                  'responddate' => date('F, d, Y', $deadline));

    $new_rtf = populate_RTF($vars, "joboffer.rtf");
    $fr = fopen('output.rtf', 'w') ;
    fwrite($fr, $new_rtf);


When this script is executed, the result will be the generation of the output.rtf file, shown in Figure 28.3:

Figure 28.3. The template RTF document populated with data from PHP.


In this case, the document was written to a file. However, it also could have been displayed to a browser by sending an appropriate header via the header() function and using the echo statement:

header("Content-type: application/msword");
header("Content-disposition: inline;      filename=joboffer.rtf");
header("Content-length: " . strlen($new_rtf));
echo $new_rtf;

As with any file system operation, the user under which PHP executes (either from the Web server or the console) must have appropriate permissions to both read and write files using this function.

As you can see, generating RTF documents from a template is an extremely easy way to create printable documents with full formatting, images, and so on from within PHP. In fact, the only special consideration that must be taken within the populate_RTF() function is to ensure that characters that have special meaning (such as the } and { characters) are appropriately escaped.

As easy as it is to generate RTF documents in this fashion, the format has some significant limitations. RTF formatted documents provide no way to prevent them from being modified by a third party; they also rely to a certain extent on the word processing package being used to render the document appropriately. This is especially true when working with non-mainstream fonts that may not be available on the rendering machine. To overcome these issues, at least to a certain degree, the Portable Document Format (PDF), which I will focus on for the remainder of the chapter, is much better suited.

    Team LiB
    Previous Section Next Section