Replace html using setValue in template Processor PhpWord

PhpWord is a PHP open source library to generate Word files. In this example we learn how to update an existing Word template using template Processor class.

Follow these steps:-

  • Create a custom TemplateProcessor class that extends the generic TemplateProcessor of PhpWord
  • Add a setHtmlBlockValue method, which instantiates a container element
  • Include the Html helper class to parse the HTML markup
<?php

use PhpOffice\PhpWord\Element\TextBox;
use PhpOffice\PhpWord\Shared\Html;
use PhpOffice\PhpWord\Shared\XMLWriter;
use PhpOffice\PhpWord\TemplateProcessor as PhpWordTemplateProcessor;
use PhpOffice\PhpWord\Writer\Word2007\Element\Container;

/**
 * Custom PhpWord template processor.
 *
 * Extends the generic template processor of PhpWord by means to
 * replace a macro with HTML markup content.
 */
class TemplateProcessor extends PhpWordTemplateProcessor {

    
    public function setHtmlBlockValue($search, $markup)
    {
      // Create a dummy container element for the content.
      $wrapper = new TextBox();

      // Parse the given HTML markup and add it as child elements
      // to the container.
      Html::addHtml($wrapper, $markup);

      // Render the child elements of the container.
      $xmlWriter = new XMLWriter();
      $containerWriter = new Container($xmlWriter, $wrapper, false);
      $containerWriter->write();

      // Replace the macro parent block with the rendered contents.
      $this->replaceXmlBlock($search, $xmlWriter->getData(), 'w:p');
    }

}

Use Below code in your files to save docx file

$text_to_insert_in_template = 'My <strong>example string</strong> with html tag.';
$template_path = 'templates/template.docx';

$templateProcessor = new TemplateProcessor($template_path);
$templateProcessor->setHtmlBlockValue('placeholde_name',$html);
$templateProcessor->saveAs('sample.docx');

Leave a Reply

Your email address will not be published. Required fields are marked *