三步用 html-pdf-chrome 把 HTML 转成 PDF:CreateOptions 实战指南
三步用 html-pdf-chrome 把 HTML 转成 PDFCreateOptions 实战指南【免费下载链接】html-pdf-chromeHTML to PDF or image (jpeg, png, webp) converter via Chrome/Chromium项目地址: https://gitcode.com/gh_mirrors/ht/html-pdf-chromehtml-pdf-chrome 是一款基于无头 Chrome 的 HTML 转 PDF 库。它让真实 Chrome 内核渲染你的页面再输出 PDF 或 PNG、JPEG、WebP 图片适合报表生成、数据导出、网页存档等自动化场景。手工转换 HTML 的麻烦在哪先看看没有工具时你平时是怎么干的手动截图浏览器打开页面用截图工具截一张长页面根本截不全分辨率也不可控。打印成 PDF用浏览器打印为 PDF页边距、纸张方向每次都要手点没法写进脚本。定期报表定时任务已经能生成 HTML 模板但转 PDF 并发邮件这一步只能靠人全自动无从谈起。共同点是这些操作要么不可重复要么无法参数化。html-pdf-chrome 的做法是用一行create()调用替代它们所有版式细节都通过CreateOptions对象用代码描述。上手体验三步拿到第一份 PDF第一步安装依赖npm install html-pdf-chrome。第二步让 Chrome 以无头模式监听调试端口chrome --headless --disable-gpu --remote-debugging-port9222第三步调库生成文件import * as htmlPdf from html-pdf-chrome; const options: htmlPdf.CreateOptions { port: 9222, // 指向常驻 Chrome 的调试端口 }; // 传 HTML 字符串或 URL 都可以返回结果对象 const result await htmlPdf.create(h1Hello PDF/h1, options); await result.toFile(first.pdf); // 也可以 toBuffer()/toStream()/toBase64()如果host、port都不传库会为这一次生成临时启动一个 Chrome 实例用完即关。能复用就复用启动开销能省则省。按场景整理配置参数所有可选项集中在CreateOptions接口里类型定义见源码文件src/CreateOptions.ts。逐项背参数效率低按场景分组记更容易。页面版式方向、边距与纸张设置printOptions直接对应 Chrome 的打印参数。scale就像打印机的缩放比例小于 1 时内容整体缩小、能塞进更多行printOptions: { landscape: false, // false 纵向宽表格改 true 横向 paperWidth: 8.27, // 纸张宽度英寸A4 约 8.27 x 11.69 paperHeight: 11.69, marginTop: 0.4, // 四边距单位都是英寸留白太大会浪费纸 marginBottom: 0.4, marginLeft: 0.4, marginRight: 0.4, scale: 1.0, displayHeaderFooter: true, // 页眉页脚模板生效的前提 headerTemplate: span classpageNumber/span, // 内置占位符pageNumber/totalPages/title }参数说明建议值landscape纸张方向报表用false宽表用truepaperWidth/paperHeight纸张尺寸英寸A48.27 x 11.69Letter8.5 x 11marginTop等四个边距页面留白0.3 ~ 0.5scale打印缩放0.8 ~ 1.0headerTemplate/footerTemplate页眉页脚 HTML 模板与displayHeaderFooter一起开启输出格式PDF 还是图片默认输出 PDF只要传了screenshotOptions输出就变成图片。deviceMetrics决定浏览器窗口多大相当于先决定取景框再拍照screenshotOptions: { format: jpeg, // png / jpeg / webp quality: 85, // 仅 jpeg 生效1-100 clip: { x: 0, y: 0, width: 800, height: 600 }, // 只截这一块区域 }, deviceMetrics: { width: 1200, // 视口宽度 height: 800, deviceScaleFactor: 2, // 2 倍像素图更清晰但文件更大 mobile: false, }参数类型说明screenshotOptions.formatpng \| jpeg \| webp图片格式默认 pngscreenshotOptions.qualitynumber仅 jpeg 有效的压缩质量screenshotOptions.clipobject裁剪区域不传则截整个视口deviceMetrics.deviceScaleFactornumber像素密度2 表示 2 倍清晰度页面就绪等待completionTrigger这是新手最容易踩的点页面 JS 还没取完数据PDF 就先转好了产出的是一张空壳。解决办法是用completionTrigger告诉库等到什么信号再打印// 等待 id 为 dataLoaded 的节点出现最多等 10 秒 completionTrigger: new htmlPdf.CompletionTrigger.Element(#dataLoaded, 10000)触发器适用场景Timer(毫秒)内容加载耗时基本固定最省事Element(css选择器)等某个数据节点渲染出来Event(事件名)页面里自己 dispatch 完成事件LifecycleEvent(networkIdle)请求密集等网络空闲Variable(变量名)前端把变量置 true 表示完成Callback(回调名)前端主动调用约定好的回调头部与身份请求头和 Cookie页面需要登录态或带 token 才能拿到数据时用这两项把身份带过去extraHTTPHeaders: { Authorization: Bearer xxx, // 随每次请求发出 }, cookies: [ { name: session, value: abc, domain: .example.com }, // 预置登录态 ], clearCache: true // 加载前清缓存防止渲染到旧内容错误捕获看到页面里发生了什么无头 Chrome 里没人盯着控制台页面报错不会有任何提示。挂上两个回调页面内部的消息会转发到你的 Node 进程runtimeConsoleHandler: (event) { // 页面的 console.log / warn / error 都会到这里 console.log(页面控制台:, event.type, event.args); }, runtimeExceptionHandler: (exception) { // 捕获未处理的异常排查白屏利器 console.error(页面异常:, exception.exceptionDetails); }, timeout: 30000 // 整体超时毫秒防止无限等待两个实战案例案例 1带认证头的报表 PDFconst options: htmlPdf.CreateOptions { port: 9222, printOptions: { landscape: true, // 报表列多用横向 printBackground: true, // 保留表头背景色 marginTop: 0.5, marginBottom: 0.5, marginLeft: 0.5, marginRight: 0.5, }, extraHTTPHeaders: { Authorization: Bearer report-token }, completionTrigger: new htmlPdf.CompletionTrigger.Timer(2000), timeout: 60000, // 数据量大超时放宽 }; const html await renderReportTemplate(); // 模板引擎生成 HTML const pdf await htmlPdf.create(html, options); await pdf.toFile(monthly-report.pdf);案例 2移动端视口截图const options: htmlPdf.CreateOptions { port: 9222, screenshotOptions: { format: jpeg, quality: 85 }, deviceMetrics: { width: 375, // 常见手机视口宽度 height: 667, deviceScaleFactor: 2, mobile: true, // 模拟移动设备CSS 媒体查询按手机端匹配 }, completionTrigger: new htmlPdf.CompletionTrigger.LifecycleEvent(networkIdle), }; const result await htmlPdf.create(https://example.com, options); await result.toFile(mobile-view.jpg);避坑指南 现象导出的 PDF 内容是空壳或半截原因动态内容还没渲染完就触发了转换。 解决按页面特性选completionTrigger——有明确节点用Element请求多用LifecycleEvent(networkIdle)并给足超时时间。现象报连接失败create 直接抛错原因Chrome 没启动或调试端口没开、端口号对不上。 解决先执行chrome --headless --disable-gpu --remote-debugging-port9222再让options.port与之一致。现象PDF 中文乱码原因HTML 没声明字符集渲染时编码猜错。 解决在文档头部加meta charsetUTF-8。现象长时间运行后 Chrome 越来越卡、内存持续增长原因同一个实例反复生成页面内存慢慢累积。 解决用 pm2 这类进程管理器让 Chrome 常驻并崩溃自动拉起同时定期重启实例。现象每生成一份 PDF 要多等好几秒原因没配host/port每次都在临时启动一个新的 Chrome。 解决让 Chrome 常驻CreateOptions里指定端口复用这是无头 Chrome 生成 PDF 最主要的提速手段。速查卡场景关键参数建议值复用常驻 Chromehost/portport: 9222A4 纵向报表printOptions纵向 边距 0.3~0.5 英寸横向宽表printOptions.landscapetrue页码页眉displayHeaderFooter 模板pageNumber/totalPages占位符导出图片screenshotOptionsformat: png/jpeg/webp2 倍清晰度deviceMetrics.deviceScaleFactor2数据驱动页面completionTrigger.Element等待数据节点超时 10 秒请求密集页面completionTrigger.LifecycleEventnetworkIdle需登录态extraHTTPHeaders/cookies传 token 或会话 Cookie长耗时任务timeout30 ~ 60 秒配置的核心其实就三块port决定连哪个 ChromeprintOptions决定版式completionTrigger决定什么时候动手。把这三块理顺html-pdf-chrome 就能覆盖绝大多数 HTML 转 PDF 的需求参数细节可直接阅读src/CreateOptions.ts中的类型定义与注释。【免费下载链接】html-pdf-chromeHTML to PDF or image (jpeg, png, webp) converter via Chrome/Chromium项目地址: https://gitcode.com/gh_mirrors/ht/html-pdf-chrome创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

相关新闻