记php/python使用wkhtmltopdf生成pdf文件

环境:centos7 + php7.3(thinkphp6)

wkhtmltopdf: https://wkhtmltopdf.org/index.html

------------

坑点:

1.linux系统 html生成的pdf中文乱码(解决方法参考:https://juejin.cn/post/7069749157329633311)

主要就是将windows中文字体复制到 /usr/share/fonts/ 内,然后清理一遍字体缓存

2.wkhtmltopdf中访问的网址url中多个参数连接符&问题

使用英文双引号括起来

3.php使用exec()时,不支持中文文件名问题

在调用的时候添加下编码

示例代码:

// 使用 $set_charset 使 exec 支持中文
//
$set_charset = 'export.UTF-8'; $set_charset = 'export LANG=en_US.UTF-8;';
$fileUrl = '/home/pdf/123/中文名.pdf';
// 访问的url中多个参数连接符 & 前后要用英文双引号包围起来(这里由于字符串用双引号括起来了,所以 & 前后使用了转义字符 \" )
exec($set_charset."wkhtmltopdf --javascript-delay 3000 http://www.test.com?param1=abc\"&\"param2=123 {$fileUrl} 2>&1", $out, $res);
// var_dump(mb_convert_encoding($out, 'UTF-8', 'UTF-8,GBK,GB2312,BIG5'));

 

=============分割线=============

下面是python处理方式

环境:centos7 + python3.8

我的处理方式是把 html内容写到一个 html 文件中,直接访问这个文件进行生成。当然 wkhtmltopdf 支持直接访问url 生成pdf

# 注意为了避免中文错误,这里要用 utf-8
with open(file=html_fpath, mode="w", encoding='utf-8') as f:
    if pagecontent: # html内容
        f.write(pagecontent)
# html_fpath 是访问目标 html 文件路径,也可以是一个 url 链接
# pdf_path 是生成的pdf 目标文件路径
# 延迟3秒,然后 显性使用参数 encoding utf-8 避免中文字符不兼容
os.system('wkhtmltopdf --javascript-delay 3000 --encoding utf-8 %s %s' % (html_fpath, pdf_path))

 =============分割线=============

linux系统下中文乱码或中文空白问题

1.去windows系统盘,windows/Fonts/ 找到微软雅黑字体,SIMSUN 字体,上传到 linux系统 /usr/share/fonts/[自建]chinese/]内,上面坑点1中已有对应描述

2.命令行分别执行下面三句:

mkfontscale
mkfontdir
fc-cache -fv
最后使用 fc-list查看已安装字体(有的可能还需要重启下系统)

 

posted @ 2023-06-30 11:37  动灵  阅读(431)  评论(0编辑  收藏  举报