2016-06-08 41 views
1

我可以使用PHPWord生成下載從頭產生的word文檔: 創建PhpWord對象:無法下載字DOCX使用PHPWord TemplateProcessor

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

添加部和行(ommitted)和創建頭:

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

創建一個作家出phpWord對象:

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

寫入到輸出:

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

我做不到的事情是從服務器上的模板下載一個文件: 創建TemplateProcessor工作:沒有錯誤和PHP承認$ templateProcessor作爲類的一個對象:

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

但我不能解決如何寫入輸出。如果我可以生成PhpWord對象,那麼我可以使用IOFactory :: createWriter方法,但TemplateProcessor沒有返回PhpWord對象的方法。

我能得到的最接近的是嘗試創建一個$ phpWord文檔出IOFactory :: load。但是,這僅僅是創建一個空白文檔

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

從快速不期而遇的TemplateProcessor它看起來像它不提供用於任何東西。一個簡單的解決方法是在模板處理器修改後存儲文件,然後加載IOFactory加載文件,然後提供服務(如果服務器不需要,則在文件之後解除鏈接) – ejuhjav

+0

這就是我決定的方法採取:我使用TemplateProcessor-> saveAs()方法將其保存到一個目錄。然後我使用codeigniter特定的命令來強制下載文件。每次我進入控制器時,我都會刪除以前保存的任何文件。 – Shawn

回答

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