【问题标题】:How to Insert an image into a Word Document using PHP? [closed]如何使用 PHP 将图像插入 Word 文档? [关闭]
【发布时间】:2015-10-07 14:47:15
【问题描述】:

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

【问题讨论】:

  • 您在使用 PHPWord 时遇到了什么问题?它应该能够满足您的需求
  • 请注意 phpoffice/phpword 是 PHPWord 的官方仓库
  • 您能否分享一个 sn-p 或文档 URL,我们可以在其中找到如何操作的示例?我们无法找到一个可行的示例,但我们确实发现了一个错误,表明它是不可能的。
  • 你有什么问题?您可以阅读现有的 Word 文档吗?插入图片有问题吗?再次保存文档有问题吗?
  • 这是未解决的问题:github.com/PHPOffice/PHPWord/issues/260

标签: php ms-word


【解决方案1】:

好的,基于@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');

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-26
    相关资源
    最近更新 更多