PHP 使用 Headless Chrome 把 HTML 生成 PDF

可以使用 wkhtmltopdf

这里使用 chrome-php/chrome: Instrument headless chrome/chromium instances from PHP 来实现。

1
composer require chrome-php/chrome
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
namespace App\Services;

use HeadlessChromium\BrowserFactory;

class HtmlToPdfConverter
{
/**
* Render a PDF from the given HTML.
*/
public static function render(string $html): string
{
$browser = (new BrowserFactory())->createBrowser([
'windowSize' => [1920, 1080]
]);

$page = $browser->createPage();

$page->setHtml($html);

return base64_decode(
$page->pdf([
'printBackground' => true
])->getBase64()
);
}
}
1
2
3
4
5
6
7
8
9
10
use App\Services\HtmlToPdfConverter;

Route::get('/html-to-pdf', function () {
$pdf = HtmlToPdfConverter::render('<h1>Hello World</h1>');

return response($pdf, 200, [
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'inline; filename="hello.pdf"'
]);
});

参考:

Convert HTML to PDF using Headless Chrome in PHP — Amit Merchant — A blog on PHP, JavaScript, and more