Auto download the file attachment using PHPWord - php

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

Related

PHPWord - corrupted Word file

I want to download a word file from an existing template using PHPWord.
I tried this code but it generate corrupted file:
$file = ROOT . '/web/templates/recu.docx';
$PHPWord = new \PhpOffice\PhpWord\TemplateProcessor($file);
$PHPWord->setValue('Value1', date('d/m/Y'));
$PHPWord->setValue('Value2', "ffff");
$PHPWord->setValue('Value3', "sabrine");
$PHPWord->setValue('Value4', utf8_decode("555555"));
$PHPWord->setValue('Value5', "200000");
$new_file = "recu_".date('d_m_Y_H_i');
$PHPWord->saveAs(ROOT. '/web/uploads/recu/'.$new_file.'.docx');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment;filename="'.$new_file.'.docx"');
$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($PHPWord,
'Word2007');
ob_clean();
$objWriter->save('php://output');
exit;
any suggestions why my code didn't work ?
Try this content header instead:
header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');

PHPWord Download Error (the office open XML file cannot be opened because there are problems with the contents)

I am having a problem with my PHPWord implementation. I am building a feature that will allow users to download content to word and am using PHPWord for this. However, after the document is downloaded I am getting an error while opening:
the office open XML file cannot be opened because there are problems with the contents
I'm only able to preview the contents of the word file after the accepting the recovery procedure, which I think is not something user friendly.
Here is my PHP code.
<?php
require_once '../assets/vendor/autoload.php';
$phpWord = new \PhpOffice\PhpWord\PhpWord();
$section = $phpWord->addSection();
\PhpOffice\PhpWord\Shared\Html::addHtml($section, "Content");
header('Content-Description: File Transfer');
header("Content-Type: application/docx");
header("Content-Transfer-Encoding: binary");
header('Content-Disposition: attachment;filename="test.docx"');
$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
$objWriter->save('test.docx');
?>
This is a very common issue for PHPWord.Hope the following code fragment will solve your problem as it solves mine.
$doc_filename = "Test_Report_". date("d-m-Y").".docx";
// Save file
// Saving the document as OOXML file...
$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
$temp_file_uri = tempnam('', 'anytext');
$objWriter->save($temp_file_uri);
//download code
header('Content-Description: File Transfer');
header("Content-Type: application/docx");//header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.$doc_filename);
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Content-Length: ' . filesize($temp_file_uri));
readfile($temp_file_uri);
unlink($temp_file_uri); // deletes the temporary file
exit;
-Thanks

Save output document in php

I am trying to save the output document in a folder on the server when using php. The code saves it to my computer but I need to save the file inside a folder with a name.
Please check the code:
// Save File
$h2d_file_uri = tempnam('', 'htd');
$objWriter = PHPWord_IOFactory::createWriter($phpword_object, 'Word2007');
$objWriter->save($h2d_file_uri);
// Download the file:
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=example.docx');
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($h2d_file_uri));
ob_clean();
flush();
$status = readfile($h2d_file_uri);
unlink($h2d_file_uri);
exit;
I tried file_put_contents('test.txt', file_get_contents('http://web.com')); but it did not help me. Please tell me how do I save the file in a folder.
Please use this code to save your output in a folder with a name just provide a folder name and file name
$fileName = $_SERVER['DOCUMENT_ROOT'].'/download/muraripradip.docx';
$objWriter = PHPWord_IOFactory::createWriter($phpword_object, 'Word2007');
It looks like you are doing a lot of stuff that you don't need. Unless you want to download the file, you can skip all the code from:
// Download the file: - And below that point
It looks like you could just alter the existing code a little:
Turn this code:
// Save File
$h2d_file_uri = tempnam('', 'htd');
$objWriter = PHPWord_IOFactory::createWriter($phpword_object, 'Word2007');
$objWriter->save($h2d_file_uri);
Into this:
// Save File
$h2d_file_uri = $_SERVER['DOCUMENT_ROOT'].'/docs/some_file_name.docx';
$objWriter = PHPWord_IOFactory::createWriter($phpword_object, 'Word2007');
$objWriter->save($h2d_file_uri);
If will then be saved into the http://domian.tld/docs/some_file_name.docx folder. You could save it somewhere the public is not allowed to access.

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

PHP Header download PDF

I've made a page where you can go and write text in a "textarea" and then when you click download you download that file as a .txt file. I've done the same thing to some other extensions and that is working fine. But it won't work with .PDF, nothing I read works. Here is the snippet I use for the .PDF downloading:
<?php
if($fileFormat == ".pdf"){
$content = $_POST['text'];
$name = stripslashes($_POST['name']);
$nameAndExt = $name.".pdf";
print strip_tags($content);
header('Content-type: application/pdf');
header('Content-Disposition: attachment; filename="'.$nameAndExt.'"');
header('Content-Transfer-Encoding: binary ');
}
?>
I'm grateful for any answear, thanks!
// hold the filename for use elsewhere so you don't have to append .pdf every time
$filename = "$id.pdf";
// create the file
$pdf->output( $filename );
// set up the headers
header("Content-Description: File Transfer");
header("Content-disposition: attachment; filename={$filename}");
header("Content-Type: application/pdf");
header("Content-Transfer-Encoding: binary");
header('Content-Length: ' . filesize($file));
// push the buffer to the client and exit
ob_clean();
flush();
// read the file and push to the output stream
readfile( $filename );
// remove the file from the filesystem
unlink( $filename );
exit();
I would recommend a class like TCPDF, see http://www.tcpdf.org/. I used it couple of times and it's quite nice (open source).

Categories