PHPWord 打印 快递单/合同

北风吹
阅读 323 标签:php  

利用 模板 中放置“占位符”

打开上面定制好的模板,在 文本输入框 中输入 占位符 文本,如:

用户名:${UserName}

身份证:${IDNo}

利用 PHPWord 库,可用动态地 修改替换占位符的内容,参考代码如下:

use common\library\PhpWord\Settings;
use common\library\PhpWord\TemplateProcessor;
 
public function test() {
    // 模板文件
    $tplFile = DATA_PATH . '/contract/template_1.docx';
 
    // 输出 word 文件名
    $fileName = 'phpgo的购卡合同.docx';
 
    // 实例化 模板器
    Settings::setOutputEscapingEnabled(true);
    $templateProcessor = new TemplateProcessor($tplFile);
 
    // 替换 关键字
    $templateProcessor->setValue('UserName', '刘德花22');
    $templateProcessor->setValue('IDNo', '362422199607020812');
    $templateProcessor->setValue('Sex', '女');
 
    // 自动输出下载 word 文件
    $tempFileName = $templateProcessor->save();
    $docxData = file_read($tempFileName);
    unlink($tempFileName);
 
    ob_start();
    header("Cache-Control: public");
    header("Content-type: application/octet-stream");
    header("Accept-Ranges: bytes");
    if (strpos($_SERVER["HTTP_USER_AGENT"], 'MSIE')) {
        header('Content-Disposition: attachment; filename=' . $fileName);
    } else if (strpos($_SERVER["HTTP_USER_AGENT"], 'Firefox')) {
        header('Content-Disposition: attachment; filename=' . $fileName);
    } else {
        header('Content-Disposition: attachment; filename=' . $fileName);
    }
    header("Pragma:no-cache");
    header("Expires:0");
    echo $docxData;
    ob_end_flush();
}
文章来源:网络 版权归原作者所有,如涉及知识产权问题,请权利人联系我们,我们将立即处理.
标签: php
专栏:   PHP教程
北风吹
文章 51 获得 0个赞 共 0个粉丝

推荐阅读 更多精彩内容