命令行安装:
composer require dompdf/dompdf
因为dompdf类库不支持中文,所有要下载一个字体: simsun.ttf
然后下载加载字体的基类 load_font.php 放在与lib和src同一目录下。
我的路径是 \dompdf\vendor\dompdf\dompdf 自行寻找一下
类下载路径:https://github.com/dompdf/utils
字体 和 load_font.php 放到同一目录下后运行命令行安装字体:
php load_font.php simsun simsun.ttf
这样就可以导出使用了。
/**
* Notes:
* By: Tommy
* DateTime: 2022/9/2 15:49
* @param $html html字符串
* @param int $height pdf高度
* @param int $width pdf宽度
* @param string $file_name pdf文件名
*/
public function setPdf($html, $height = 800, $width = 800, $file_name = '')
{
//引用类库
require_once dirname(__FILE__) . '/../../../vendor/dompdf/vendor/autoload.php';
$options = new \Dompdf\Options();
$options->setDefaultFont('simsun');
$options->setIsRemoteEnabled(true);
$dompdf = new Dompdf();
$dompdf->loadHtml($html);
// (Optional) Setup the paper size and orientation
//$dompdf->setPaper('A4', 'landscape');
$dompdf->setPaper(array(0, 0, $height, $width), 'landscape');
$options = $dompdf->getOptions();
// Render the HTML as PDF
$dompdf->render();
$dompdf->stream($file_name);
die();
}
$html 生成的html字符串$height pdf 文件的高度$width pdf 文件的宽度$file_name pdf 文件名$options->setDefaultFont('simsun');
声明默认字体为:sinmsun (可以输出中文)
$options->setIsRemoteEnabled(true);
设置图片可以访问线上 默认是 false
$dompdf->loadHtml($html);
记载需要生成pdf的html文件/字符串
$dompdf->setPaper('A4', 'landscape');
设置纸张大小为A4纸
ps:这里注意dompdf不支持分页 如果用A4格式 超出部分会不显示,文档中也有声明:
如果需要生成的pdf内容不确定 或者大于A4大小 那就需要自定义纸张大小:
$dompdf->setPaper(array(0, 0, $height, $width), 'landscape');
数组中的参数可以随意定义 可以满足较多条件使用
$dompdf->render();
将HTML呈现为PDF
$dompdf->stream($file_name);
将生成的PDF输出到浏览器 $file_name 不能为空 ,如果不定义文件名可以直接 $dompdf->stream();
整体用下来还是不错的 使用起来还可以
注意!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
看文档
看文档
看文档
文档地址:https://github.com/dompdf/dompdf#quick-start