I created some features to extend Jerome's solution. The problem was that to change the picture, we needed to know this link name in the docx file. It can be difficult to find out for the average user (you need to “unzip” the docx and find the image manually).
My solution allows you to refer to images in alt text (it should be in the usual format: $ {abc}) so you don’t need to know how word names represent a placeholder image, a variable is enough. Here's a link on how to add alt texts: http://accessproject.colostate.edu/udl/modules/word/tut_alt_text.php?display=pg_2
I just modified TemplateProcessor.php
First add this to the class:
private $temporaryDocumentRels;
The constructor function (public function __construct ($ documentTemplate)) should be expanded at the end. Add this:
$this->temporaryDocumentRels = $this->zipClass->getFromName('word/_rels/document.xml.rels');
Now you can read material from document.xml.rels with $ this-> temporDocumentRels
Save Jerome's code:
/** * Set a new image * * @param string $search * @param string $replace */ public function setImageValue($search, $replace){ // Sanity check if (!file_exists($replace)) { return; } // Delete current image $this->zipClass->deleteName('word/media/' . $search); // Add a new one $this->zipClass->addFile($replace, 'word/media/' . $search); }
This function returns with rId the image you marked:
public function seachImagerId($search){ if (substr($search, 0, 2) !== '${' && substr($search, -1) !== '}') { $search = '${' . $search . '}'; } $tagPos = strpos($this->temporaryDocumentMainPart, $search); $rIdStart = strpos($this->temporaryDocumentMainPart, 'r:embed="',$tagPos)+9; $rId=strstr(substr($this->temporaryDocumentMainPart, $rIdStart),'"', true); return $rId; }
And this returns the image file name if you know its rId:
public function getImgFileName($rId){ $tagPos = strpos($this->temporaryDocumentRels, $rId); $fileNameStart = strpos($this->temporaryDocumentRels, 'Target="media/',$tagPos)+14; $fileName=strstr(substr($this->temporaryDocumentRels, $fileNameStart),'"', true); return $fileName; }
Changes made to TemplateProcessor.php.
Now you can replace the image by calling this:
$templateProcessor->setImageValue($templateProcessor->getImgFileName($templateProcessor->seachImagerId("abc")),$replace);
You can also create a function in TemplateProcessor.php that calls it like:
public function setImageValueAlt($searchAlt, $replace){ $this->setImageValue($this->getImgFileName($this->seachImagerId($searchAlt)),$replace); }