Add image in a .docx with PHPWord using TemplateProcessor

sandrita picture sandrita · Mar 10, 2015 · Viewed 9.2k times · Source

I don't know if is possible to add an image in a template with PHPWord using TemplateProcessor.

I have a document (form.docx). This document is a template. I read the fields (${name} for example) and replace it with a text.

$template = new TemplateProcessor('form.docx');
$template->setValue('name', $name);

But now, I want to put an image but I don't know how I do it. I try with this:

$img='img.jpg';
$template->setValue('image',$img);

Doesn't works. I try other form, creating a section and add this section to template but this fails.

$phpWord = new PhpWord();
$section = $phpWord->createSection();   

$section->addImage('img.jpg', array('width'=>210, 'height'=>210, 'align'=>'center'));
$template = new TemplateProcessor('form.docx'); 
$template->setValue('image',$section).

Anyone know how to put an image in a .docx using a template?

Thanks.

Answer

user 1007017 picture user 1007017 · Dec 8, 2019

This should do the trick:

// there has to be a text ${foto} in your templatefile.docx for this to work

$templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor('templatefile.docx');
$templateProcessor->setImageValue('foto', array('path' => 'dummy_foto.jpg', 'width' => 100, 'height' => 100, 'ratio' => true));
$templateProcessor->saveAs('result.docx');

// open the file

header("Content-disposition: attachment;filename=" .'result.docx' . " ; charset=iso-8859-1");
echo file_get_contents('result.docx');