Create dynamic documents from your templates and PHP

The replace method of Docxpresso offers you a really powerfull way to modify the contents of a given template allowing you to have full control of the final formatting of your business report or document.

Although it may take you a little longer to master all its functionality we believe that you are really going to love it because it will greatly simplify your work in multiple ocassions.

Use document templates to generate PDF

The fact that you can safely rely on your own document templates to generate documentation in PDF or any other available format will streamline the interconnection between the design and content producing tasks that are generally carried out by different members of your team.

Before getting into the details we would like to summarize some of the things that you can do with a few lines of code. You may:

  • Replace placeholder variables and/or natural text by plain text, enriched text or even full document fragments.
  • Replicate table rows, list items or paragraphs with custom content.
  • Replace and resize placeholder images.
  • Use directly HTML5 code or parse line breaks.
  • Clone full sections of your document and repopulate its contents with all of the above.

Basically there are no limits to what you can do to your template with the assurance that the final document will fully respect your branding and design!!.

Well, that is enough for the marketing side of the equation an let us get into business.

The public API of the replace method can be summarized as follows:

Signature

public replace ($vars[, $options])

Parameters

  • $vars (type: array). This array has as keys the names of the variables we wish to replace and as values arrays with the following structure:
    • value (type: mixed). It can be:
      • a string or a DocumentFragment object or
      • an array which entries are strings or DocumentFragment objects.
    • html (type: boolean, default: true). If true detects if the content is plain text or a HTML code. If given, it overwrites for that variable the html global method option if any.
    • parse-line-breaks (type: boolean). If true parses line breaks. If the method detects that the string is HTML the default is false, otherwise defaults to true. If given, it overwrites for that variable the parse-line-breaks global method option if any.
    • block-type (type: boolean, default: false). If true removes and replaces the containing paragraph. If given, it overwrites for that variable the block-type global method option if any.
    • image (type: boolean, default: false). Set only to true if the variable name is associated with the title of a placeholder image. If given, it overwrites for that variable the element option if any.
    • match (type: integer). If it is defined and if the ‘value’ option is not an array only the selected match will be replaced, i.e. if match equals 1 the first appearance of the variable will be replaced and the others will be ignored. If given, it overwrites for that variable the match global method option if any.
    • width (type: string). An optional new width for image replacement. The format must be like in CSS, i.e. 100px or 2cm, 3in, etcetera.
    • height (type: string). An optional new height for image replacement. The format must be like in CSS, i.e. 100px or 2cm, 3in, etcetera.
  • $options (type: array). This array has the following available keys and values:
    • format (type: array, default: array(‘{{‘, ‘}}’)). An array with two entries giving the chosen openning and closing symbol for template variables. The default value is array(‘{{‘, ‘}}’) but any other combination of symbols is possible, even array(”, ”) that is equivalent to plain text, although this is not recommended unless strictly necessary.
    • element (type: string, default: text). The element level at which we want to carry out the replacement, possible values are:
      • text: it will just replace the variable by text,
      • paragraph: it will clone the containing paragraph as many times as required,
      • list: it will clone the list items as many time as required,
      • table: the table rows that contain the placeholder variables will be cloned as many times as required,
      • image: the variable name will be searched in the title attribute of the image.
    • html (type: boolean, default: true). If true detects if the content is plain text or a HTML code. It may be overwritten for a single value in the $vars array.
    • parse-line-breaks (type: boolean). If true parses line breaks. If the method detects that the string is HTML the default is false, otherwise defaults to true. It may be overwritten for a single value in the $vars array.
    • block-type (type: boolean, default: false). If true removes and replaces the containing paragraph. It may be overwritten for a single value in the $vars array.
    • match (type: integer). If given and if the ‘value’ option is not an array only the selected match will be replaced, i.e. if match equals 1 the first appearance of the variable will be replaced and the others will be ignored. It may be overwritten for a single value in the $vars array.
    • target (type: string, default: document). Restricts the scope of replacement. The possible values are: document, header or footer.

At first sight the plethora of options may seem a little overwhelming. That is the price we have to pay for maximum flexibility. Nevertheless like we will show in the following things are simpler than the may seem at first sight.

Repairing broken variables

Whenever using MS Word to edit your Docxpresso templates it may well happen that MS Word breaks internally the placeholder variable inserting “<span>” tags that are not visible from the Word user interface thus breaking the replace method.

Although this problem may be easilly circumvented by rewriting the affected variables we have introduced an auxiliary repairVariable method that does the work for you.

So if the replace method fails for any of your variables you should add at the very beginning of your script the following line of code:

$doc = new Docxpresso\createDocument(array('template' => 'path_to_your_template.odt'));
$doc->repairVariables();

If you are using a placeholder varaible delimiters other than the default double curly brackets you should call the repairVariables method passing an array with the used delimiters. For example, when using double square brackets one should write instead:
$docx->repairVariables(array(‘[[‘,’]]’)).

Examples of use

Although the possible scenarios of use are practically endless we will try in the following to offer a few examples that will give you a good starting point for more sophisticated tasks.

Let us start with a basic example that however covers all most obvious situations. We are going to replace some data in this template with the help of the following script:

<?php
/**
 * This sample script replaces some content in a template
 */
require_once 'pathToDOCXPRESSO/CreateDocument.inc';
$doc = new Docxpresso\createDocument(array('template' => 'template_replace_general.odt'));
$format = '.pdf';//.pdf, .doc, .docx, .odt, .rtf
//replace single variable
$doc->replace(array('variable' => array('value' => 'replaced text')));
//replace natural text
$doc->replace(array('replace me, please' => array('value' => 'another text')), array('format' => array('','')));
//populate the list
$doc->replace(array('item' => array('value' => array('first', 'second', 'third'))), array('element' => 'list'));
//populate the table
$vars =array('product' => array('value' => array('Smart phone', 'MP3 player', 'Camera')),
             'price' => array('value' => array('430.00', '49.99', '198,49')),
);
$doc->replace($vars, array('element' => 'table'));	
//replace single variable by different values
$doc->replace(array('test' => array('value' => array('one', 'two', 'three'))));
//and now a variable in the header
$doc->replace(array('example_header' => array('value' => 'header text')), array('target' => 'header'));
//include in the render method the path where you want your document to be saved
$doc->render('replaced_content' . $format); 
//echo a link to the generated document
echo 'You may download the generated document from the link below:<br/>';
echo '<a href="' . 'replaced_content' . $format . '">Download document</a>';

DOWNLOAD:download pdfdownload docdownload docxdownload odtdownload rtf

Let us now slightly modify the previous script so we can perform the replacement with HTML5+CSS formatted content:

<?php
/**
 * This sample script replaces some content in a template using HTML code
 */
require_once 'pathToDOCXPRESSO/CreateDocument.inc';
$doc = new Docxpresso\createDocument(array('template' => 'template_replace_general.odt'));
$format = '.pdf';//.pdf, .doc, .docx, .odt, .rtf
//replace single variable
$doc->replace(array('variable' => array('value' => 'replaced <b>text</b>')));
//replace natural text
$doc->replace(array('replace me, please' => array('value' => '<a href="http://www.Docxpresso.com">external link</a>')), array('format' => array('','')));
//populate the list
$doc->replace(array('item' => array('value' => array('first', '<i>second</i>', 'third'))), array('element' => 'list'));
//populate the table
$vars =array('product' => array('value' => array('Smart phone', 'MP3 player', 'Camera')),
             'price' => array('value' => array('430.00', '49.99', '198,49')),
);
$doc->replace($vars, array('element' => 'table'));	
//replace single variable by different values
$doc->replace(array('test' => array('value' => array('one', '<span style="color:red">two in red</span>', 'three'))));
//and now a variable in the header
$doc->replace(array('example_header' => array('value' => '<span style="color:red">header text also in red</span>')), array('target' => 'header'));
//include in the render method the path where you want your document to be saved
$doc->render('replaced_content_HTML' . $format); 
//echo a link to the generated document
echo 'You may download the generated document from the link below:<br/>';
echo '<a href="' . 'replaced_content_HTML' . $format . '">Download document</a>'; 

DOWNLOAD:download pdfdownload docdownload docxdownload odtdownload rtf

Let us now proceed with another template that includes a more sophisticated table with rowspans and formatting:

<?php
/**
 * This sample script replaces some content in a complex table
 */
require_once 'pathToDOCXPRESSO/CreateDocument.inc';
$doc = new Docxpresso\CreateDocument(array('template' => 'table_template_replace.odt'));
$format = '.pdf';//.pdf, .doc, .docx, .odt, .rtf
//populate the table
$vars =array('name' => array('value' => array('Smart phone', 'MP3 player <i style="color: red">(out of stock)</i>', 'Camera')),
			 'reference' => array('value' => array('345-H26-CC', '115-H27-CC', '225-J76-CD')),
			 'currency' => array('value' => array('$', '€', '$')),
             'price' => array('value' => array('430.00', '49.99', '198.49')),
);
$doc->replace($vars, array('element' => 'table'));	
//include in the render method the path where you want your document to be saved
$doc->render('replace_table' . $format); 
//echo a link to the generated document
echo 'You may download the generated document from the link below:<br/>';
echo '<a href="' . 'replace_table' . $format . '">Download document</a>'; 

DOWNLOAD:download pdfdownload docdownload docxdownload odtdownload rtf

We will now perform a “block” replacement that allows to substitute a placeholder variable by arbitrary content. For this purpose we will use the following template that includes twice the {{block_variable}} placeholder variable that will be replaced by an HTML5+CSS table:

<?php
/**
 * This sample script replaces "block-type" content
 */
require_once 'pathToDOCXPRESSO/CreateDocument.inc';
$doc = new Docxpresso\createDocument(array('template' => 'template_block_replace.odt'));
$format = '.pdf';//.pdf, .doc, .docx, .odt, .rtf
//replace single variable
$html ='
<html>
    <head>
    <style>
    * {font-family: Arial; font-size: 10pt}
     p {margin-bottom: 10pt}
     th {background-color: #5B9BD5; padding: 3px 7px}
     th p {color: #f6f6f6; font-weight: bold; font-size: 10pt; margin: 0}
     td {padding: 3px 7px; border: 0.5pt solid #ffffff}
     td p {color: #333; font-size: 10pt; margin: 0}
     .nice {width: 12cm; margin: auto}
     .firstCol {background-color: #5B9BD5;}
     .firstCol p {color: #f6f6f6; font-weight: bold; font-size: 10pt; margin: 0}
     .even {background-color: #BDD6EE;}
     .odd {background-color: #DEEAF6}
    </style>
    </head>
    <body>
        <table class="nice">
            <tr>
                <th><p>First Column</p></th>
                <th><p>Second Column</p></th>
                <th><p>Third Column</p></th>
            </tr>
            <tr>
                <td class="firstCol"><p>Row 1</p></td>
                <td class="even"><p>C_1_1</p></td>
                <td class="even"><p>C_1_2</p></td>
            </tr>
            <tr>
                <td class="firstCol"><p>Row 2</p></td>
                <td class="odd"><p>C_2_1</p></td>
                <td class="odd"><p>C_2_2</p></td>
            </tr>
            <tr>
                <td class="firstCol"><p>Row 3</p></td>
                <td class="even"><p>C_3_1</p></td>
                <td class="even"><p>C_3_2</p></td>
            </tr>	
        </table>
    </body>
</html>';
$doc->replace(array('block_variable' => array('value' => $html)), array('block-type' => true));
//include in the render method the path where you want your document to be saved
$doc->render('replaced_block_HTML' . $format); 
//echo a link to the generated document
echo 'You may download the generated document from the link below:<br/>';
echo '<a href="' . 'replaced_block_HTML' . $format . '">Download document</a>'; 

DOWNLOAD:download pdfdownload docdownload docxdownload odtdownload rtf

You may also check by yourself that setting the match option to 1 or 2 only the first or second ocurrence of {{block_variable}} wil be replaced offering us a high degree of flexibility when mixing the replace and clone methods to generate arbitrary complex document content.

Replacing images

The replacement of images follows a similar pattern.

We may replace images that have been previously tagged by including the placeholder variable into the title of the image (right click the image in your document and check for the title/description attribute and insert the variable, i.e. {{myImage}} and {{myImage_2}} in the example at hand.

The following sample code uses this template that includes a couple of tagged images. We will replace both:

<?php
/**
 * This sample script replaces some images within the document
 */
require_once 'pathToDOCXPRESSO/CreateDocument.inc';
$doc = new Docxpresso\CreateDocument(array('template' => 'image_template_replace.odt'));
$format = '.pdf';//.pdf, .doc, .docx, .odt, .rtf
//replace images
$doc->replace(array('myImage' => array('value' => 'new.jpg', 'image' => true)));
//in the second one we will change the original image dimensions
$doc->replace(array('myImage_2' => array('value' => 'new_2.jpg', 'image' => true, 'width' => '400px', 'height' => '200px')));
//include in the render method the path where you want your document to be saved
$doc->render('replace_image' . $format); 
//echo a link to the generated document
echo 'You may download the generated document from the link below:<br/>';
echo '<a href="' . 'replace_image' . $format . '">Download document</a>'; 

DOWNLOAD:download pdfdownload docdownload docxdownload odtdownload rtf

Beware that if you use in your template the same “placeholder image” more than once all copies will be replaced simultaneously so avoid that practice unless that is the result you wish to achieve.

Replace chart data

A carefully crafted chart may require quite a lot of work so it may show useful to be able to just replace its data without the hassle of generating the whole chart from scratch.

The Templates subpackage, to which the replace method also belongs, offers us the replaceChartData method that allows us to modify the chart data preserving the original chart options and design.

Its public API is given by:

Signature

public replaceChartData ($var, $options)

Parameters

  • $var (type: string). It should be the name used for the chart title. You may leave it empty if you prefer to select the chart via the match option.
  • $options (type: array). This array has the following available keys and values:
    • data (type: array), it can be an array with different formats:
      • pie and donut charts: array(     ‘category_1’ => 3,     ‘category_2’ => 5,     ‘category_3’ => 4.3, )
      • bar, column, area , line, scatter, (filled-)radar and column-line charts: array(     ‘series’ => array(‘series_1’, ‘series_2’),     ‘category_1’ => array(20,40),     ‘category_2’ => array(30,10),     ‘category_3’ => array(12.5, 54), )
      • bubble charts: Not supported.
    • format (type: array, default: array(‘{{‘, ‘}}’)). An array with two entries giving the chosen openning and closing symbol for template variables. The default value is array(‘{{‘, ‘}}’) but any other combination of symbols is possible, even array(”, ”), although this is not recommended unless strictly necessary.
    • match (type: integer, default: 1). If given only the selected match will be replaced, i.e. if match equals 1 only the first chart with the given title will be replaced.

Notice that only the chart values which categories coincide with the data array keys will be replaced.

Let us now use this template that includes a nicely formatted chart:

<?php
/**
 * This sample script replaces the data from a chart
 */
require_once 'pathToDOCXPRESSO/CreateDocument.inc';
$doc = new Docxpresso\CreateDocument(array('template' => 'template_replace_chartdata.odt'));
$format = '.pdf';//.pdf, .doc, .docx, .odt, .rtf
$data = array( 
    'series' => array('Series 1', 'Series 2', 'Series 3'),
    'Category 1' => array(10,20, 10), 
    'Category 2' => array(30,10, 30), 
    'Category 3' => array(12.5, 50, 5),
    'Category 4' => array(40, 10, 10),
);
$doc->replaceChartData('', array('data' => $data));
//include in the render method the path where you want your document to be saved
$doc->render('replaced_chart' . $format); 
//echo a link to the generated document
echo 'You may download the generated document from the link below:<br/>';
echo '<a href="' . 'replaced_chart' . $format . '">Download document</a>'; 

DOWNLOAD:download pdfdownload docdownload docxdownload odtdownload rtf