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.
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With