-2
是否有任何Microsoft Word文檔操作庫允許打開已經創建的Word文檔並向其中插入外部圖像? phpoffice/phpword和PHPWord似乎都無法處理任務。如何使用PHP將圖像插入Word文檔?
是否有任何Microsoft Word文檔操作庫允許打開已經創建的Word文檔並向其中插入外部圖像? phpoffice/phpword和PHPWord似乎都無法處理任務。如何使用PHP將圖像插入Word文檔?
好的,基於@Mark Baker的回答。我創建了一個子類,這樣就不需要覆蓋原始的TemplateProcessor。
<?php
class TemplateProcessor extends \PhpOffice\PhpWord\TemplateProcessor
{
/**
* Content of document rels (in XML format) of the temporary document.
*
* @var string
*/
private $temporaryDocumentRels;
public function __construct($documentTemplate)
{
parent::__construct($documentTemplate);
$this->temporaryDocumentRels = $this->zipClass->getFromName('word/_rels/document.xml.rels');
}
/**
* Set a new image
*
* @param string $search
* @param string $replace
*/
public function setImageValue($search, $replace){
// Sanity check
if (!file_exists($replace)) {
throw new \Exception("Image not found at:'$replace'");
}
// Delete current image
$this->zipClass->deleteName('word/media/' . $search);
// Add a new one
$this->zipClass->addFile($replace, 'word/media/' . $search);
}
/**
* Search for the labeled image's rId
*
* @param string $search
*/
public function seachImagerId($search){
if (substr($search, 0, 2) !== '${' && substr($search, -1) !== '}') {
$search = '${' . $search . '}';
}
$tagPos = strpos($this->temporaryDocumentRels, $search);
$rIdStart = strpos($this->temporaryDocumentRels, 'r:embed="',$tagPos)+9;
$rId=strstr(substr($this->temporaryDocumentRels, $rIdStart),'"', true);
return $rId;
}
/**
* Get img filename with it's rId
*
* @param string $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;
}
public function setImageValueAlt($searchAlt, $replace)
{
$this->setImageValue($this->getImgFileName($this->seachImagerId($searchAlt)),$replace);
}
}
這樣,我只有做你跟PHPWord有什麼問題
<?php
$template = new TemplateProcessor('path/to/my/template.docx');
$template->setImageValueAlt('myPicturePlacehoder', '/tmp/pictureToReplace.png');
?它應該是相當能夠做你需要的東西 –
並注意phpoffice/phpword是PHPWord的官方回購 –
你能分享一個片段或文檔URL,我們可以找到一個如何做到這一點的例子嗎?我們一直無法找到一個可行的例子,我們發現一個錯誤表明這是不可能的。 – rreyes1979