I have an instance of a template on PHPWord. Is it possible to replace or add an image? Something like a setImageValue?
$phpWord = new \PhpOffice\PhpWord\Template('a.docx');
$phpWord->setImageValue('IMAGE_PLACEHOLDER', 'a.jpg');
$phpWord->saveAs('b.docx');
Is something like this possible?
Following code is the updated version of the one from TotPeRo (thanks again for your code!), for last phpOffice (0.11) that has evolved a little
Can be called with:
modify the name of the *.docx to *.zip
open the zip folder
view the "
word/media/****
" the imgage name is to replace namefor
setImageValue($search, $replace)
his is pretty much untested. but this is working for me (although mine is slightly different):
add the following function to
PHPWord/Template.php
:create a document with an actual image to be used as a place holder (this solution don't allow setting the with & height of the image or multiple extensions). unzip the the documnt and check for the file name in word/media folder. use this file name as the $id for the save_image function.
you can now use:
If you want to add, remove or replace image in template.docx you can add this to your TemplateProcessor.php file, (it works for me with PhpWord 0.14.0 version):
1.
2.
3. Add this function too:
4. And this:
5. How to use:
I created some functions to extend Jerome's solution. The problem was that in order to change the picture we had to know it's reference name in the docx file. This could be difficult to find out for an average user (you have to "unZip" the docx, and find your picture manually).
My solution makes it possible to reference pictures by alt text (it needs to be in usual format: ${abc} ) so one doesn't have to know how word names the placeholder picture, the variable is enough. Here's a link about how to add alt texts: http://accessproject.colostate.edu/udl/modules/word/tut_alt_text.php?display=pg_2
I only modified TemplateProcessor.php
First add this to the class:
The constructor function (public function __construct($documentTemplate)) needs to be extended at the end. Add this:
Now you can read stuff from document.xml.rels by using $this->temporaryDocumentRels
Keep Jerome's code:
This function returns with the rId of the image you labeled:
And this returns the images filename, if you know it's rId:
The modifications in TemplateProcessor.php are done.
Now you can replace the image by calling this:
You can also create a functionin TemplateProcessor.php that calls it like:
I was looking for a solution to add an image. I read a lot of articles, I only found suitable solutions for older versions. Changing and finalized the decision to get the code.
Let us proceed to change the file TemplateProcessor.php