php实现生成并下载word文件到本地

要给最常用出租屋管理系统增加个合同功能,mark下知识点。要生成合同就需要使用phpword。

安装phpword包

通过composer安装phpword包。因为是使用thinkphp架构,安装挺方便的。
直接下载phpword压缩包有问题

composer require phpoffice/phpword

准备一个word模板(docx格式)

准备好word模板后,只需要用变量替换需要替换的值,如下图所示,将房东名替换成${name}。

 

 

前端调用代码

系统前端是使用vue3+element Ui开发的。所以请求用到axios。其中设置responseTyperesponseType 表示服务器响应的数据类型,可以是 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'。默认的 responseType: 'json',
而axios下载文件需要设置responseType: 'blob',

  axios.post(url, data, { headers: { 'X-CSRF-TOKEN': this.token }, responseType: 'blob' })
    .then((res) => {
      const { data, headers } = res
      const contentDisposition = headers['content-disposition']
      const patt = new RegExp('filename=([^;]+\.[^\.;]+);*')
      const result = patt.exec(contentDisposition)
      const filename = decodeURI(JSON.parse(result[1])) // 处理文件名,解决中文乱码问题
      const blob = new Blob([data], { type: headers['content-type'] })
      let dom = document.createElement('a')
      let url = window.URL.createObjectURL(blob)
      dom.href = url
      dom.download = decodeURI(filename)
      dom.style.display = 'none'
      document.body.appendChild(dom)
      dom.click()
      dom.parentNode.removeChild(dom)
      window.URL.revokeObjectURL(url)
    }).catch((err) => { })

PHP处理代码

后端方面的代码如下。Talk is cheap, show me the code.

    public function contract()
    {
        $tmp=new \PhpOffice\PhpWord\TemplateProcessor('static/wordfile/contract.docx');//打开模板
        $tmp->setValue('name', '君常笑');//替换变量name
        $tmp->setValue('mobile', '12');//替换变量mobile
        $tmp->saveAs('../tempfile/简历.docx');//另存为
        $file_url = '../tempfile/简历.docx';
        $file_name=basename($file_url);
        $file_type=explode('.', $file_url);
        $file_type=$file_type[count($file_type)-1];
        $file_type=fopen($file_url, 'r'); //打开文件
        //输入文件标签
        header("Content-type: application/octet-stream");
        header("Accept-Ranges: bytes");
        header("Accept-Length: ".filesize($file_url));
        header("Content-Disposition:attchment; filename=" . json_encode('合同.docx'));
        //输出文件内容
        echo fread($file_type, filesize($file_url));
        fclose($file_type);
    }

one more thing

在传输过程中,可能会出现文件名是乱码的问题。也就是Content-Disposition中filename中文是乱码。解决方法如下:
php端使用json_encode(filename)
前端使用JSON.parse()

、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、

 

php生成PDF文件的方法

使用phpword生成PDF文件还需要引入一个PDF呈现库,这里使用tcpdf

composer require tecnickcom/tcpdf

使用方法

composer安装成功后,即可直接引用

use PhpOffice\PhpWord\PhpWord;
use PhpOffice\PhpWord\IOFactory;
/* 使用 */
$phpWord = new PhpWord();
/* 设置全局默认字体 */
$phpWord->setDefaultFontName('仿宋');
$phpWord->setDefaultFontSize(16);
/* 实例化创建新的内容 */
$section = $phpWord->addSection();
/* 自定义字体样式 */
$titleF = array(
    'name'  => '方正小标宋简体',
    'color' => '000000',
    'size'  => 22,
);
/* 段落样式 */
$titleP = array(
    'alignment' => 'center' //start左对齐,end右对齐
);
/* 添加一段内容 */
$section->addText('把第一段当成文档的标题', $titleF, $titleP);
/* 其他段落样式 */
$contentF = array(
    'name' => '仿宋_GB2312', 'size' => 16, 'color' => '000000'
);
$contentP = array(
    'alignment'  => 'left',
);
 /* 添加文档内容,使用单独格式;*/
 $section->addText(
     '这是内容的第一个段落,可以很长很很很长很长,反正就是一个段落可以很长很长。。反正就是一个段落随便打点字',
     $contentF,
     $contentP
 );
 $section->addText(
     '第二个段落,也是一样使用一样的格式,一次类推说明一下PHPWord是一个用纯PHP编写的库,它提供了一组用于写入和读取不同文档文件格式的类',
     $contentF,
     $contentP
 );
$tcpdfPath = base_path('vendor/tecnickcom/tcpdf');
\PhpOffice\PhpWord\Settings::setPdfRendererPath($tcpdfPath);
\PhpOffice\PhpWord\Settings::setPdfRendererName('TCPDF');
 /* 保存为PDF 此处为windows本地测试环境,所以直接写死路径,仅作保存查看 */
 $objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'PDF');
 $objWriter->save('C:\Users\helloWorld.pdf');
 die('已按路径保存到本地,线上环境时可另外做下载');

注意:setPdfRendererPath的参数是呈现库的位置,需使用tcpdf包的绝对路径。phpword中仅支持DomPDF,TCPDF,MPDF这三种呈现库类库;所以我们这里setPdfRendererName需要设置的值为TCPDF。呈现库类库中默认不支持有中文字体,生成中文字体的pdf文件时,会出现一堆问号乱码的现象

在设置的目录下找到文件,查看生成的文件

 

 

这里就是为什么我们要选择使用tcpdf类库了,tcpdf中支持自定义安装ttf字体文件,注意!其他后缀类型的字体文件是不支持的,需要使用命令行安装所以要把PHP设置为环境变量方便操作;安装字体方法:

切换到 …\tecnickcom\tcpdf\tools ,复制要安装的字体文件到此目录下,在此位置打开命令行:

 

 多个字体文件由,隔开,其他参数说明

 php tcpdf_addfont.php -i .\fangsong.ttf,.\xiaobiaosong.ttf

执行安装成功,可以看到在../fonts文件夹中,已经生成了字体的相关文件

 

 

 

 字体文件名称不支持显示中文,大家安装的字体文件名称需要改成英文。

其他使用参数说明请看

php tcpdf_addfont.php -help

两种字体安装完毕

接着我们把代码中设置的字体名称,改成对应的字体文件名称

$titleF = array(
    //'name'    => '方正小标宋简体', //设置字体名称
    'name'  => 'xiaobiaosong', //改成
    'color' => '000000', //字体颜色
    'size'  => 22,      //字体大小;单位为(磅)
);
------------------------------------
/* 其他段落样式 */
$contentF = array(
    'name' => '仿宋_GB2312', 'size' => 16, 'color' => '000000'
);
改成
$contentF = array(
    'name' => 'fangsong', 'size' => 16, 'color' => '000000'
);

最后执行代码,完成生成PDF文件:

 

总结

生成PDF文件时,字体名称仅支持设置为../fonts目录下的字体,默认是没有中文字体的,使用到其他字体时,需要通过tcpdf_addfont.php进行安装,并设置字体名称安装后的字体文件名称

在phpword中,度量单位通常为twip,磅,英寸。并不能直接设置为字符,毫米等word中其他常用的度量单位;如需要设置量度单位为字符时,需要进行单位转换;


phpword更多使用相关要求查看官方软件包
phpword更多使用说明,属性配置请查看官方说明文档
tcpdf更多使用方法,请查看官方软件包

 

posted @ 2022-11-05 10:51  mingruqi  阅读(1015)  评论(0编辑  收藏  举报