• slider image 844
  • slider image 858
  • slider image 868
  • slider image 869
:::


9-7-6 PhpWord 使用樣版生成文件(三)

【前提】

1.sticker_C3770_A.docx (自己做的word檔案)

【程式】如下:

<?php 
require_once 'vendor/autoload.php';

//虛構資料
$data = array("60101","60102","60103");


//模板的路徑,word的版本最好是docx,要不然可能會讀取不了,根據自己的模板位置調整
	$path = 'PhpWordTemplates/sticker_C3770_A.docx'; //自訂樣板

//圖片路徑
	$pic_path = "images/portfolioQRCode/";

//宣告一個模板物件、讀取模板
	$templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor($path);

for ( $a=0 ; $a<count($data) ; $a++ ) {
	$temp_a = $a + 1 ;
	$temp_b = $pic_path . $data[$a] .'.png';
	$templateProcessor->setValue($temp_a, $data[$a]);
	//$templateProcessor->setValue($temp_a.'t', $temp_b);
	$templateProcessor->setImageValue($temp_a.'t', array('path' => $temp_b, 'width' => 100, 'height' => 100, 'ratio' => false));
}

//output
header('Content-Type: application/vnd.ms-word');
header("Content-Disposition: attachment;filename=新檔名.docx");
header('Cache-Control: max-age=0');
$templateProcessor->saveAs('php://output');
?>

 

【補充說明】:

以下這一行,可以用圖片「置換」文字標籤。

$templateProcessor->setImageValue($temp_a.'t', array('path' => $temp_b, 'width' => 100, 'height' => 100, 'ratio' => false));

 


:::

Web Language Select