Laravel中Chrome Headless转PDF渲染为移动端视图的问题
Laravel中Chrome Headless转PDF始终以移动端视图渲染问题
在Laravel项目中使用Google Chrome Headless将HTML转换为PDF时,页面始终以移动端视图渲染,无法按照大屏设备视图输出。具体表现为Bootstrap的col-md-3类显示为100%宽度,而非预期的25%,CSS颜色等其他样式正常,仅渲染模式异常。
当前使用的代码
$content = '.......'; $html = view('pdf_wrapper', compact('content'))->render(); // 生成HTML内容的唯一临时文件名 $tempHtmlFile = tempnam(sys_get_temp_dir(), 'chrome_html_') . '.html'; $tempPdfFile = tempnam(sys_get_temp_dir(), 'chrome_pdf_') . '.pdf'; // 将渲染后的HTML内容保存到临时文件 file_put_contents($tempHtmlFile, $html); // Chrome可执行文件路径,可根据服务器环境调整 $chromePath = '/usr/bin/google-chrome'; // 构建无头模式下运行Chrome的命令 $command = sprintf( '%s --headless --disable-gpu --no-sandbox --print-to-pdf=%s --window-size=1920,1080 --disable-mobile-emulation --disable-application-cache --force-device-scale-factor=1 --user-agent="Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/112.0.5615.165 Safari/537.36" %s', escapeshellcmd($chromePath), escapeshellarg($tempPdfFile), escapeshellarg($tempHtmlFile) ); // 执行命令 exec($command); // 将PDF提供给用户下载 header('Content-Type: application/pdf'); header('Content-Disposition: attachment; filename="downloaded.pdf"'); readfile($tempPdfFile); @unlink($tempHtmlFile); // 删除临时HTML文件 @unlink($tempPdfFile); // 提供下载后删除临时PDF文件 exit();
已尝试的解决措施
- 配置Chrome命令参数:
--window-size、--disable-mobile-emulation、--user-agent - 测试不同的viewport元标签:
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=1920">
复现步骤
执行以下命令,将Bootstrap官网转换为PDF,即可复现移动端渲染问题:
/usr/bin/google-chrome --headless --disable-gpu --print-to-pdf=output.pdf --window-size="1920,1080" https://www.getbootstrap.com/
内容的提问来源于stack exchange,提问作者Saroj Shrestha
相关产品推荐
相关产品推荐

