Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add image in a .docx with PHPWord using TemplateProcessor

Tags:

php

docx

phpword

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.

like image 282
sandrita Avatar asked Nov 09 '22 17:11

sandrita


1 Answers

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');
like image 172
user 1007017 Avatar answered Nov 15 '22 05:11

user 1007017