如何使用PHP将图像插入Word文档?

时间:2015-10-07 14:47:16

标签: php ms-word

是否有任何Microsoft Word文档操作库允许打开已创建的Word文档并将外部图像插入其中? phpoffice / phpword和PHPWord似乎都无法处理任务。

1 个答案:

答案 0 :(得分:2)

好的,基于@Mark Ba​​ker的回答。我创建了一个子类,这样就不需要覆盖原来的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);
    }
}

这样我只需做

<?php
$template = new TemplateProcessor('path/to/my/template.docx');
$template->setImageValueAlt('myPicturePlacehoder', '/tmp/pictureToReplace.png');
相关问题