Shawn
Shawn

Reputation: 51

Unable to download word docx using PHPWord TemplateProcessor

I can generate download a word document generated from scratch using PHPWord: Create the PhpWord object:

$phpWord = new \PhpOffice\PhpWord\PhpWord();

add sections and rows (ommitted) and create the header:

$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');

create a writer out of the phpWord object:

$xmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');

write to output:

$xmlWriter->save("php://output");

What I have failed to do is download a document from a template on the server: Creating the TemplateProcessor works: No errors and PHP recognizes $templateProcessor as an object of that class:

$templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor(asset_url() . 'templates/receipt_template.docx');

But I cannot work out how to write to output. If I could generate a PhpWord object then I could use the IOFactory:: createWriter method, but TemplateProcessor does not have methods that return a PhpWord object.

The closest I can get is to attempt to create a $phpWord document out of the IOFactory::load. But this just creates a blank document

$phpWord = \PhpOffice\PhpWord\IOFactory::load($templateProcessor->save());

Upvotes: 3

Views: 6088

Answers (1)

burrotauro
burrotauro

Reputation: 151

<?
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');
//#####################################################
//#####################################################
?>

Upvotes: 10

Related Questions