无法使用 PHPWord TemplateProcessor 下载 word docx

Sha*_*awn 3 php phpword

我可以使用 PHPWord 生成下载一个从头开始生成的 Word 文档: 创建 PhpWord 对象:

$phpWord = new \PhpOffice\PhpWord\PhpWord();
Run Code Online (Sandbox Code Playgroud)

添加部分和行(省略)并创建标题:

$datetime = date('Y_M_d_G_i');
$filename = 'receipt_' . $datetime . '.docx';
header("Content-Description: File Transfer");
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
header('Content-Transfer-Encoding: binary');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Expires: 0');
Run Code Online (Sandbox Code Playgroud)

从 phpWord 对象创建一个 writer:

$xmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
Run Code Online (Sandbox Code Playgroud)

写入输出:

$xmlWriter->save("php://output");
Run Code Online (Sandbox Code Playgroud)

我未能做的是从服务器上的模板下载文档: 创建 TemplateProcessor 有效:没有错误并且 PHP 将 $templateProcessor 识别为该类的对象:

$templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor(asset_url() . 'templates/receipt_template.docx');
Run Code Online (Sandbox Code Playgroud)

但我不知道如何写入输出。如果我可以生成 PhpWord 对象,那么我可以使用 IOFactory::createWriter 方法,但 TemplateProcessor 没有返回 PhpWord 对象的方法。

我能得到的最接近的是尝试从 IOFactory::load 创建 $phpWord 文档。但这只是创建了一个空白文档

$phpWord = \PhpOffice\PhpWord\IOFactory::load($templateProcessor->save());
Run Code Online (Sandbox Code Playgroud)

小智 8

<?
require_once "../include/PHPWord-develop/bootstrap.php";

$templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor('contrato01.docx');

$templateProcessor->setValue('variable01', 'Sun');
$templateProcessor->setValue('variable02', 'Mercury');

//#####################################################
// Save File
//#####################################################
//#####################################################
header("Content-Disposition: attachment; filename='ejemplo.docx'");
  $templateProcessor->saveAs('php://output');
//#####################################################
//#####################################################
?>
Run Code Online (Sandbox Code Playgroud)