php - 使用 TemplateProcessor 使用 PHPWord 在 .docx 中添加图像

标签 php docx phpword

我不知道是否可以使用 TemplateProcessor 在 PHPWord 模板中添加图像。

我有一个文档 (form.docx)。本文档是一个模板。我阅读了字段(例如 ${name})并将其替换为文本。

$template = new TemplateProcessor('form.docx');
$template->setValue('name', $name);

但是现在,我想放一张图片,但我不知道该怎么做。我试试这个:

$img='img.jpg';
$template->setValue('image',$img);

不起作用。我尝试其他形式,创建一个部分并将此部分添加到模板,但这失败了。

$phpWord = new PhpWord();
$section = $phpWord->createSection();   

$section->addImage('img.jpg', array('width'=>210, 'height'=>210, 'align'=>'center'));
$template = new TemplateProcessor('form.docx'); 
$template->setValue('image',$section).

有人知道如何使用模板将图像放入 .docx 中吗?

谢谢。

最佳答案

这应该可以解决问题:

//templatefile.docx 中必须有一个文本 ${foto} 才能工作

$templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor('templatefile.docx');
$templateProcessor->setImageValue('foto', array('path' => 'dummy_foto.jpg', 'width' => 100, 'height' => 100, 'ratio' => true));
$templateProcessor->saveAs('result.docx');

//打开文件

header("Content-disposition: attachment;filename=" .'result.docx' . " ; charset=iso-8859-1");
echo file_get_contents('result.docx');

关于php - 使用 TemplateProcessor 使用 PHPWord 在 .docx 中添加图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28961024/

相关文章:

php - ZipArchive addFromString 在 Windows 上无法正常工作

javascript - 获取上传文件的文件路径

ms-word - 是否有一种合理的方法可以从 Asciidoc 或 Markdown 等轻型标记格式生成 Word 或 OpenOffice 文档?

用于桌面开发的 PHP 和钛

JAVA POI DOCX 替换段落中的文本

apache-flex - 有没有办法在 AS3 中将 DocX、OpenXml 或 RTF 转换为 TextFlow?

php - 使用 PHPWord 动态表行

php - phpWord 中的粗体、间距和缩进文本

php - 什么是 php 中的流和流包装器

php - Laravel - 在 View 中处理 if/else 的有效或逻辑设计模式是什么