D
D
Dmitry Chilikin2021-04-14 15:24:00
PHP
Dmitry Chilikin, 2021-04-14 15:24:00

How to convert HTML with images to DOCX in PHPWord?

Good afternoon!
You need to generate a single Word DOCX document. The library used is PHPOffice/PHPWord . Version 0.18

There is a block in the initial template:


${additional_block}
${block}
${/additional_block}

to host dynamic pages.

To implement this functionality, I first open the template, fill it with the necessary data (via setValue), then I add the blocks I need through the loop. The block content is HTML text from the TinyMCE plugin.

Code snippet:
/* additional_block */
    $m = new \Mustache_Engine(array('entity_flags' => ENT_QUOTES));
    
    $templateProcessor->cloneBlock('additional_block', count($db_contract_docs), true, true);
    $i = 1;
    foreach ($db_contract_docs as $docs){
      /* Подставим значения через шаблонизатор */			
      $template = $m->render($docs->template, $params); 
      
      $phpWord = new PhpWord('Word2007');
      /* Создадим новую страницу */
      $section = $phpWord->addSection();
      
      
      /* Конвертируем HTML в Word */
      \PhpOffice\PhpWord\Shared\Html::addHtml($section, $template, false);
            
      $xmlWriter = new XMLWriter(XMLWriter::STORAGE_MEMORY, './', WordSettings::hasCompatibility());
      $containerWriter = new Container($xmlWriter, $section);
      $containerWriter->write();
      
      $htmlAsXml = $xmlWriter->getData();
      
      WordSettings::setOutputEscapingEnabled(false);
      
      $templateProcessor->setValue('block#' . ($i), $htmlAsXml);
      $templateProcessor->addImageToRelations();
      WordSettings::setOutputEscapingEnabled(true);
      
      $i++;
    }
    
    header("Content-Disposition: attachment; filename=contract_$contract.docx");
    $templateProcessor->saveAs('php://output');


After executing this code, a Word file is generated for download, which opens successfully.

But if you add a picture () through the editor, then the picture is inserted, but the resource is not written to the Word file (archive) (to the Media folder and is not written to document.xml.rels). This causes a file content error. As a result, the file opens, but there is no image in it. Perhaps another method needs to be called?

Please help.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question