PHP生成pdf方法
主要使用PHP的扩展 【 “spatie/browsershot”: “3.57”】
使用这个扩展生成PDF需要环境安装以下依赖
1:NPM【版本:9.2.0】
2:NODE【版本:v18.19.1】
3:puppeteer【npm install -g puppeteer】
下面是示例代码:示例是脚本生成pdf的方法;
扩展也可以是接口形式直接输出给浏览器生成pdf,这种,方式不需要安装依赖。
use console\base\ConsoleBaseController;
use Spatie\Browsershot\Browsershot;class PtdfController extends ConsoleBaseController
{public function actionIndex(){$html = 'html代码';$savePath = __DIR__ . '/../../runtime/';$fileName = realpath($savePath)."/20250526.pdf";$browsershot = Browsershot::html($html); // 如果是URL页面,则使用 Browsershot::url()// 配置PDF输出选项$browsershot->setOption('format', 'A4') // 设置纸张大小->setOption('margin', ['top' => '20px', 'right' => '20px', 'bottom' => '20px', 'left' => '20px']) // 设置页边距->showBackground() // 显示背景图形->waitUntilNetworkIdle() // 等待网络空闲后截图->save($fileName); // 保存PDF到指定路径echo "PDF has been saved to {$fileName}";}
}