Unable to download word docx using PHPWord TemplateProcessor - php

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());

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

Related

Codeigniter 4 with PHPWord loadTemplate

I have a problem loading a template doc in Codeigniter using PHPWord. The code below works but the downloaded word file is empty. I think the problem is that the location of the template is incorrect. Can anyone show/teach me how should I properly locate the template file. The template file file is located in public/template/ folder.
$phpWord = new \PhpOffice\PhpWord\PhpWord();
$document = $phpWord->loadTemplate(./template/filedoc.docx);
$document->setValue('fullName', 'John Doe');
$document->setValue('date', date("F j Y"));
$xmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
$xmlWriter->save("php://output");
header("Content-Description: File Transfer");
header('Content-Disposition: attachment; filename="output.docx"');
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');
Update:
loadTemplate is now working fine no errors, the problem now is, why is it that the downloaded doc file is empty. Can anyone help?
$document = new \PhpOffice\PhpWord\TemplateProcessor(template/filedoc.docx)
$document->setValue('fullName', 'John Doe');
$document->setValue('date', date("F j Y"));
$document->saveAs('output.docx');
Change the code based on the current PHPWord documentaion for template processing. The output on the code above is still the same, empty document or rather unreadable by MSWord. Help...
constant APPPATH
The path to the app directory.
Instead of:
// ...
$document = $phpWord->loadTemplate(./template/filedoc.docx); ❌
// ...
Use this:
// ...
$document = $phpWord->loadTemplate(APPPATH . "public/template/filedoc.docx"); ✅
// ...
works for me
$phpWord = new \PhpOffice\PhpWord\PhpWord();
$section = $phpWord->addSection();
$titleText = $section->addTextRun(array('alignment' => \PhpOffice\PhpWord\SimpleType\Jc::END));
$titleText->addText('helooo ', array('size' => 12, 'rtl' => true));
$section->addTextBreak(0.5);
$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
$objWriter->save("demo.docx'");
its create file in public folder

PHPWord on server corrupt document with mention of some parts are missing

I have installed PHPWord on my computer with Composer and Wamp64.
using a template, on my computer the template is well modified, and the recording of the file is perfect.
On the infomaniak server, I have a message that the file is corrupted and that there are some parts missing.
I can't find the reason. here is my code.
Please help me find the source of the problem
<?php
$docModele = 'print/modele_cdd_as_2.docx';
require_once '../PhpWord/bootstrap.php';
use\PhpOffice\PhpWord\PhpWord;
// Creating the new document...
$PHPWord = new \PhpOffice\PhpWord\PhpWord();
header('Content-type: application/json; charset=UTF-8');
/* Note: any element you append to a document must reside inside of a Section. */
$document = $PHPWord->loadTemplate($docModele);
$document->setValue('date_debut', $date_debut);
$document->setValue('identite', $identite.' ');
$document->setValue('date_naissance', $date_naissance);
$document->setValue('lieu_naissance', $lieu_naissance);
$document->setValue('dpt_naissance', $dpt_naissance);
$document->setValue('adresse1', $adresse1);
$document->setValue('cp', $cp);
$document->setValue('ville', $ville);
$document->setValue('no_ss', $no_ss);
$document->setValue('jour_debut', $jour_debut);
$document->setValue('date_fin', $date_fin);
$document->setValue('remplace', $remplace);
$document->setValue('motif_txt', $motif_txt);
$document->setValue('essai', $essai);
$document->setValue('indice', $indice);
$document->setValue('valeur_point', $valeur_point);
$document->setValue('brut', $brut);
$document->setValue('majoration', $majoration);
$document->setValue('date_contrat', $date_contrat);
//XML Writer compatibility
\PhpOffice\PhpWord\Settings::setCompatibility(false);
//#####################################################
// Save File
//#####################################################
//#####################################################
ob_clean();
$filename = 'nom_du_fichier.docx';
header("Content-Disposition: attachment; filename=$filename");
$document->saveAs('php://output');
//#####################################################
//#####################################################
exit;
$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($PHPWord, 'Word2007');
// création du fichier
$objWriter->save($filename);
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.$filename);
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($filename));
ob_clean();
flush();
readfile($filename);
unlink($filename); // deletes the temporary file
?>

PHPWord name spaces / classes & functions

I'm aware this might be more a question of understanding PHP Namespaces,etc...but I still can't get my head around the following:
I have an MVC controller with the below usages:
use PhpOffice\PhpWord\PhpWord;
use PhpOffice\PhpWord\Style\Paper;
use PhpOffice\PhpWord\Style\Language;
...and the following function:
public function word(){
$phpword= new PhpWord();
$settings=$phpword->getSettings();
//$languageFrFr = new Language('FR_FR');
//$settings->setThemeFontLang($languageFrFr);
$docInfo=$phpword->getDocInfo();
$docInfo->setCreator('JMB');
$docInfo->setCreated(date("d-m-Y"));
$paper = new Paper();
$paper->setSize( 'A4' );
$section = $phpword->addSection();
$section->addText('An example dummy text...');
$file = 'test.docx';
header("Content-Description: File Transfer");
header('Content-Disposition: attachment; filename="' . $file . '"');
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');
$xmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpword, 'Word2007');
$xmlWriter->save("php://output");
This works perfectly (eg the WORD file & it's content are output correctly...
UNTIL...I uncomment & try to set the 'ThemeFontLang' : function hangs when I load:
$languageFrFr = new Language('FR_FR');
Any clue why this is happening, and how I could avoid / bypass the long paths\namespaces definitions inside my function ?
Many thanks,
JMB

create pdf to docx file using PHPword

I am using for creating a .docx file PHP word, I have one pdf file .its creating .docx file but when I tried to open this file in window machine its not opening. On Linux machine its showing correctly . I tried many thing for that.
That is my code:-
spl_autoload_unregister(array('YiiBase','autoload'));
Yii::import('application.extensions.PHPWord.PHPWord',true);
require_once('PHPWord/PHPWord.php');
$PHPWord = new PHPWord();
spl_autoload_register(array('YiiBase','autoload'));
$document = $PHPWord->loadTemplate("/var/www/frontsite/agemodern/uploads/roadmaps/".$file);
$document->setValue('Value1', 'Sun');
$newfile='ageModern Roadmap - '.date('m-d-Y',time()).' - '.time().'.docx';
$document = PHPWord_IOFactory::createWriter($PHPWord, 'Word2007');
$document->save("/var/www/frontsite/agemodern/uploads/roadmaps/".$newfile);
and this is my phpword file code:-
$zip_name=$strFilename;
if(file_exists($zip_name))
{
$filename=$zip_name;
//header("Content-Type: application/force-download");
header('Content-Type: application/octet-stream');
//header("Content-Type: application/download");
header("Content-Disposition: attachment; filename=\"{$zip_name}\"");
header('Content-Disposition: attachment; filename="'.$zip_name.'"');
header("Content-Transfer-Encoding: binary ");
readfile($filename);
//readfile($zip_name);
// remove zip file is exists in temp path
unlink($filename);
}
Thank you in advance

Auto download the file attachment using PHPWord

I'm trying to use PHPWord to generate word documents. And the document can be generated successfully. But there is a problem where my generated word document will be saved on the server. How can I make it available to download straight away?
Sample:
$PHPWord = new PHPWord();
//Searching for values to replace
$document = $PHPWord->loadTemplate('doc/Temp1.docx');
$document->setValue('Name', $Name);
$document->setValue('No', $No);
$document->save('php://output'); //it auto save into my 'doc' directory.
How can i link to the header to download it as follows:
header("Content-Disposition: attachment; filename='php://output'"); //not sure how to link this filename to the php://output..
Kindly advise.
php://output is a write-only stream, that writes to your screen (like echo).
So, $document->save('php://output'); will not save the file anywhere on the server, it will just echo it out.
Seems, $document->save, doesn't support stream wrappers, so it literally made a file called "php://output". Try using another file name (I suggest a temp file, as you just want to echo it out).
$temp_file = tempnam(sys_get_temp_dir(), 'PHPWord');
$document->save($temp_file);
In the header, the filename field is what PHP tells the browser the file is named, it doesn't have to be a name of a file on the server. It's just the name the browser will save it as.
header("Content-Disposition: attachment; filename='myFile.docx'");
So, putting it all together:
$PHPWord = new PHPWord();
//Searching for values to replace
$document = $PHPWord->loadTemplate('doc/Temp1.docx');
$document->setValue('Name', $Name);
$document->setValue('No', $No);
// // save as a random file in temp file
$temp_file = tempnam(sys_get_temp_dir(), 'PHPWord');
$document->save($temp_file);
// Your browser will name the file "myFile.docx"
// regardless of what it's named on the server
header("Content-Disposition: attachment; filename='myFile.docx'");
readfile($temp_file); // or echo file_get_contents($temp_file);
unlink($temp_file); // remove temp file
$objWriter = PHPWord_IOFactory::createWriter($PHPWord, 'Word2007');
$filename = 'MyFile.docx';
$objWriter->save($filename);
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.$filename);
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($filename));
flush();
readfile($filename);
unlink($filename); // deletes the temporary file
exit;
This is work for me:
$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007', $download = true);
header("Content-Disposition: attachment; filename='File.docx'");
$objWriter->save("php://output");
now whit Ver 0.13.0
https://github.com/PHPOffice/PHPWord
<?
require_once "../include/PHPWord-develop/bootstrap.php";
$templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor('template.docx');
$templateProcessor->setValue('var01', 'Sun');
$templateProcessor->setValue('var02', 'Mercury');
//#####################################################
// Save File
//#####################################################
//#####################################################
header("Content-Disposition: attachment; filename='output01.docx'");
$templateProcessor->saveAs('php://output');
//#####################################################
//#####################################################
?>
A simple solution for Laravel based on #user3214824 answer.
// ...
$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($PHPWord, 'Word2007');
$doc_name = 'fileName.docx';
$objWriter->save($doc_name); // saving in the public path just for testing
return response()->download(public_path($doc_name))->deleteFileAfterSend(true);
Sorry this came in later. I stumbled on this while trying to solve the same problem. I was able to get it working on Laravel 5 using below:
$file_dir = $template_upload_dir.DIRECTORY_SEPARATOR.'filename.docx';
$tags = array();
if (file_exists($file_dir)) {
$templateProcessor = new TemplateProcessor($file_dir);
$tags = $templateProcessor->getVariables();
$replace = array('');
$templateProcessor->setValue($tags, $replace);
$save_file_name = $fullname.'-'.$inv_code.'-'.date('YmdHis').'.docx';
$templateProcessor->saveAs($save_file_name);
return response()->download($save_file_name)->deleteFileAfterSend(true);
}
Hope it helps someone!!!
// Save File
$objWriter = PHPWord_IOFactory::createWriter($PHPWord, 'Word2007');
header("Content-Disposition: attachment; filename='myFile.docx'");
$objWriter->save("php://output");

Categories