【问题标题】:Is there way to insert an image (html) to PHPWord Template?有没有办法将图像(html)插入到 PHPWord 模板中?
【发布时间】:2020-09-27 10:50:43
【问题描述】:

我从 tinymce 获取包含图像和文本(段落)的 html 正文。但是当我尝试将其插入模板时得到空白图像。

Result

这是我的代码:

$phpWord = new \PhpOffice\PhpWord\PhpWord();
$templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor('./template.docx');

$section = $phpWord->addSection();
$content = '<p>Test</p> <img src="https://www.sciencemag.org/sites/default/files/styles/inline__450w__no_aspect/public/sparrow_16x9_0.jpg" />';
Html::addHtml($section, $content);

$xml = getXMLContent($section); 

\PhpOffice\PhpWord\Settings::setOutputEscapingEnabled(false);
$templateProcessor->setValue('test', $xml);
\PhpOffice\PhpWord\Settings::setOutputEscapingEnabled(true);

$templateProcessor->saveAs('./result.docx');

function getXMLContent($section) {
    $xmlWriter = new XMLWriter(XMLWRITER::STORAGE_MEMORY, './', Settings::hasCompatibility());
    $containerWriter = new Container($xmlWriter, $section);
    $containerWriter->write();
    return $xmlWriter->getData();
}

我做错了吗?还是有别的办法?

【问题讨论】:

标签: php phpword


【解决方案1】:

首先,您使用的是哪个版本的 PHPWord? 如果您使用的是最新版本(截至 2020 年 10 月),则可以使用此功能:

https://phpword.readthedocs.io/en/latest/templates-processing.html#setimagevalue

将图像添加到 Word 模板非常简单:

setImageValue(&lt;tag&gt;, &lt;path to file&gt;);

我目前正在尝试修复图像的高度和宽度,但我发现它有问题,图像宽度固定为 3.04cm。

插入图片并设置图片高度和宽度的API:

setImageValue(&lt;tag&gt;, array('path'=&gt;&lt;path to file&gt;,'height'=&gt;&lt;height&gt;,'width'=&gt;&lt;width&gt;);

【讨论】:

    猜你喜欢
    • 2010-12-04
    • 1970-01-01
    • 1970-01-01
    • 2015-02-13
    • 2023-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-26
    相关资源
    最近更新 更多