Tag Archive PHPWord

Byphunsanit

PHPWord: รวมไฟล์ word เป็นไฟล์เดียว

เพราะว่าเอกสารที่่ต้องออกมาเป็น report มีความซับซ้อน ทำให้ต้องมีการแยก template เอกสารออกไปไฟล์ย่อยๆ แล้วประกอบขึ้นมาใหม่เป็นเอกสารที่ครบสมบูรณ์ ปัญหาคือ PHPWord มันไม่สามารถรวมเอกสารเป็นไฟล์เดียวกันได้

พระเอกของงานนี้คือ krustnic/DocxMerge จะทำหน้าที่รวมเอกสารให้

<?php
ini_set('max_execution_time', 0);
ini_set('memory_limit', '-1');

include '../vendor/autoload.php';
use DocxMerge\DocxMerge;

$fileName = 'result_' . date('Y-m-d_H-i-s') . '.docx';
$fileNameTemp = sys_get_temp_dir() . $fileName;
$templates = [
    'header.docx',
    'body.docx',
    'footer.docx',
];

/* merge document */
$dm = new DocxMerge();
$dm->merge($templates, $fileNameTemp);

/* download */
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');
readfile($fileNameTemp);

ความจริงส่วนที่ทำหน้าที่รวบรวมไฟล์เวิร์ดแล้วรวมเป็นไฟล์เดียวทำงานง่ายๆ

$dm = new DocxMerge();
$dm->merge($templates, $fileNameTemp);

โดยระบุไฟล์ต้นฉบับเข้าไปใน array $templates และระบุชื่อไฟล์ที่จะรวมไฟล์ ซึ่งควรจะสร้างไว้ใน temporary folder ที่ได้จาก function sys_get_temp_dir ก่อน เพราะทุกครั้งที่จะทำงานจะมีการสร้างไฟล์ขึ้นมา 2 ไฟล์ คือ ชื่อไฟล์ที่ระบุให้สร้างและไฟล์ชื่อสุ่มนามสกุล .tmp ที่จะกลายเป็นขยะตกค้างอยู่ จากกนั้นค่อยคัดลอกหรือ download มาใช้