Using PHPWord elements in a TemplateProcessor

Viewed 1081

I have a Word template with several macros (customer name, address, etc) as well as some generated tables which works fine. One of the macros I need to populate is data from a TinyMCE field on a web form, which generates data as HTML.

I looked at https://github.com/rkorebrits/HTMLtoOpenXML however the HTML I need to inject comes out of a TinyMCE editor and can include things like tables.

I was able to write the HTML to disk and use https://github.com/unoconv/unoconv to covert it into a .docx file, and then use PHPWord to extract the elements, however I can't seem to inject those elements into a TemplateProcessor as they're the wrong type!

Any help would be appreciated.

/**
 * Converts HTML data into XML elements for use in Word
 *
 * @param string $html
 * @return \PhpOffice\PhpWord\Element\Section
 */
public function convertHTML($html)
{
    global $config;

    $format = "<html><head></head><body>%s</body></html>";
    $temphtml = tempnam($config['tmp_dir'], 'PHPWord');
    $tempdocx = tempnam($config['tmp_dir'], 'PHPWord');
    $elements = [];

    // Write the HTML to disk
    $fp = fopen($temphtml, 'w');
    fprintf($fp, $format, $html);
    fclose($fp);

    // Convert the HTML to Word
    $unoconv = Unoconv::create();
    $unoconv->transcode($temphtml, 'docx', $tempdocx);

    // Parse the word doc
    $word = IOFactory::load($tempdocx);
    $sections = $word->getSections();
    foreach ($sections as $section) {
        $elements = array_merge($elements, $section->getElements());
    }

    unlink($temphtml);
    unlink($tempdocx);

    $section = $word->addSection();
    foreach ($elements as $element) {
        $section->addElement($element);
    }

    return $section;
}

And then in my template processing, I have something like:

// See if we're dealing with a TinyMCE field
$def = $bean->getFieldDefinition($varArray[0]);
if ($def['type'] === 'tinymce') {
    // Convert the HTML from the TinyMCE field into Word elements
    $section = $this->convertHTML($bean->{$varArray[0]});
    $this->setComplexValue($var, $section);
} else {
    // Just treat it like a normal text value
    $this->setValue($var, $bean->{$varArray[0]});
}

$template->setComplexValue() fails as the result is of type PhpOffice\PhpWord\Element\Section and setComplexValue only accepts PhpOffice\PhpWord\Writer\Word2007\Element*, so I think I've hit a dead end.

0 Answers
Related