龙空技术网

PHP转换HTML为PDF文档的方法和常见问题

ian有话说 104

前言:

而今你们对“php将html转化为word”大概比较注重,你们都需要知道一些“php将html转化为word”的相关资讯。那么小编也在网摘上收集了一些有关“php将html转化为word””的相关知识,希望姐妹们能喜欢,小伙伴们一起来了解一下吧!

公司的某项业务需要与用户线上签订协议,即用户在线手写一个签名,后台将公司公章信息和用户的签名以及合同信息生成一份PDF文件,供用户查看和下载。

比对了一些插件,我们最终决定使用dompdf这个插件,插件的github在这里:。

1. 使用方法

安装可以使用composer或者直接下载源代码,使用require或者include引入。具体的使用方式,可以参考以下示例代码。

// 引入命名空间use Dompdf\Dompdf;// 初始化dompdf对象$dompdf = new Dompdf();// 加载html文档内容$dompdf->loadHtml('hello world');// 设置纸张类型和方向$dompdf->setPaper('A4', 'landscape');// 渲染HTML为PDF$dompdf->render();// 流输出$dompdf->stream();

2. 常见问题和解决办法

2.1 中文乱码的问题

插件对于字体和编码问题是这样形容的:

PDF documents internally support the following fonts: Helvetica, Times-Roman, Courier, Zapf-Dingbats, & Symbol. These fonts only support Windows ANSI encoding. In order for a PDF to display characters that are not available in Windows ANSI, you must supply an external font. Dompdf will embed any referenced font in the PDF so long as it has been pre-loaded or is accessible to dompdf and reference in CSS @font-face rules. See the font overview for more information on how to use fonts.The DejaVu TrueType fonts have been pre-installed to give dompdf decent Unicode character coverage by default. To use the DejaVu fonts reference the font in your stylesheet, e.g. body { font-family: DejaVu Sans; } (for DejaVu Sans). The following DejaVu 2.34 fonts are available: DejaVu Sans, DejaVu Serif, and DejaVu Sans Mono.

尝试了一下,默认带的字体是无法渲染中文的,使用CSS的@font-face引入会报错(也可能是我打开方式不对)。这样就只好自己引入一个字体了。

插件给了一个安装语言文件的工具,地址再这里:。

使用步骤:

下载或者复制load_font.php文件,放到dompdf文件夹内,与src和test文件夹同级修改load_font.php文件中引入的autoload.php为项目实际的位置在命令行中执行php load_font.php simkai /path/to/simkai.ttf

这样,我们就可以在html文档的css中使用font-family属性来指定字体了。

html { font-family: simkai;}

2.2 图片无法展示

插件应该是无法直接显示网络图片,所以需要将图片转换为BASE64格式才能显示。

将HTML文档中的所有图片转换为BASE64的方式:

function imgToBase64($html) { $html = preg_replace_callback('/<img(?:.*?)src="(.*?)"(?:.*?)\/?>/', function($matches) { $imageInfo = getimagesize($matches[1]); $base64 = "" . chunk_split(base64_encode(file_get_contents($matches[1]))); $base64_image = 'data:' . $imageInfo['mime'] . ';base64,' . $base64; return str_replace($matches[1], $base64_image, $matches[0]); }, $html); return $html;}

这样转换其实性能影响挺大的,感觉性能不太好可以加一下缓存。

标签: #php将html转化为word #php将html转化为图片 #php html pdf #php文档pdf #php代码转html代码