如何在TypeScript环境中使用html-pdf-node包
在Node.js TypeScript项目中使用html-pdf-node的正确方法
1. 安装依赖
先安装核心包和对应的TypeScript类型定义(如果官方提供的话):
npm install html-pdf-node npm install @types/html-pdf-node --save-dev
如果找不到@types/html-pdf-node包,就需要手动创建类型声明文件让TypeScript识别这个包的类型。
2. 替换CommonJS导入为ES模块导入
TypeScript更推荐用ES模块语法,把原示例的require替换成import:
import * as htmlToPdf from 'html-pdf-node';
3. 手动声明类型(无官方@types包时)
在项目根目录创建html-pdf-node.d.ts文件,添加以下类型声明:
declare module 'html-pdf-node' { export interface PdfGenerationOptions { format?: string; args?: string[]; // 可根据官方文档补充其他支持的配置项 } export interface PdfSource { content?: string; // 直接传入HTML内容 url?: string; // 传入目标URL } export function generatePdf( source: PdfSource, options: PdfGenerationOptions ): Promise<Buffer>; }
4. 完整TypeScript示例代码
import * as htmlToPdf from 'html-pdf-node'; import fs from 'fs'; // 配置PDF生成参数,比如格式、浏览器启动参数 const pdfOptions = { format: 'A4', args: ['--no-sandbox', '--disable-setuid-sandbox'] // Docker/CI等环境必须添加 }; // 方式一:使用HTML字符串生成PDF const htmlContentSource = { content: '<h1>Welcome to html-pdf-node</h1><p>这是TypeScript环境下的测试内容</p>' }; htmlToPdf.generatePdf(htmlContentSource, pdfOptions) .then(buffer => { console.log('PDF生成成功,Buffer长度:', buffer.length); // 将Buffer写入本地文件 fs.writeFileSync('output-from-content.pdf', buffer); }) .catch(error => { console.error('PDF生成失败:', error); }); // 方式二:使用URL生成PDF // const urlSource = { url: 'https://example.com' }; // htmlToPdf.generatePdf(urlSource, pdfOptions) // .then(buffer => { // fs.writeFileSync('output-from-url.pdf', buffer); // }) // .catch(error => { // console.error('PDF生成失败:', error); // });
注意事项
- 在Docker、CI环境中运行时,必须添加
--no-sandbox和--disable-setuid-sandbox参数,否则会触发Chrome沙箱机制报错。 - 若遇到类型编译错误,检查类型声明文件是否正确,或确保
@types/html-pdf-node已正确安装。
内容的提问来源于stack exchange,提问作者rodolfo.martins
相关产品推荐
相关产品推荐

