这是一个基于 Node.js 开发的 Web 服务,主要功能是将 HTML 内容转换为 PDF 文件。项目使用了 Express 作为 Web 框架,Puppeteer 作为 PDF 生成引擎,提供了简单易用的 API 接口。前端开发人员提供了一个简单而强大的 HTML 转 PDF 解决方案,特别适合需要生成报表、订单等业务场景的应用。
后端框架 :Express.js , PDF 生成 :Puppeteer , 开发工具 :Nodemon(热更新),跨域支持 :CORS
创建 node js 项目 安装依赖
项目git地址
cd my-node-project // 你的文件夹
npm init
npm install cors express puppeteer nodemon
npm run dev
项目结构
├── modules/
│ ├── pdfGenerator.js # PDF 生成核心模块
├── public/ # 静态资源目录
├── pdfs/ # PDF 输出目录
├── app.js # 应用主入口
├── index.html # 首页
└── package.json # 项目配置文件
API 接口
POST /generatepdf/htmlToPdf
项目中使用 接口
try {
const response: any = await axios.post('http://localhost:3000/generatepdf/htmlToPdf', {
fileName: 'pdf文件名',
html: rssRef.value.innerHTML,
styles: '.pdfDom{line-height:30px;color:#000;width:800px;margin:0auto;padding:20px;box-sizing:border-box;font-size:14px;}...........'
},)
console.log(response.data, 'PDF生成成功')
//将服务器返回的 base64 数据转换为字节数组
const byteArray = new Uint8Array(response.data.data.split(',').map(Number))
//创建 PDF 类型的 Blob 对象
const blob = new Blob([byteArray], { type: 'application/pdf' });
console.log(blob)
// 转为文件对象
const file = new File([blob], 'filename.pdf', {
type: 'application/pdf',
lastModified: Date.now(),
});
console.log(file)
} catch (error) {
console.error('生成PDF失败:', error)
message.error('生成PDF失败,请重试')
}
请求参数:
- html : HTML 内容
- styles : 自定义样式
- fileName : 输出文件名
响应格式:
{
"success": true,
"message": "PDF生成成功",
"data": "base64编码的PDF内容"
}
核心功能
主要通过 pdfGenerator.js
模块实现,核心功能包括:
- HTML 内容转换为 PDF
- 自定义 PDF 页面大小(A4)
- 自定义页面边距
- 支持背景打印
- 支持自定义缩放
通过接口调用 传参 实现生成pdf
const puppeteer = require("puppeteer");
const path = require("path");
// HTML内容生成PDF
async function generatePdfFromHtml(html, outputDir, fileName) {
let browser;
try {
// 启动浏览器
browser = await puppeteer.launch({
headless: "new",
args: ["--no-sandbox", "--disable-setuid-sandbox"],
});
const page = await browser.newPage();
// 设置视口
await page.setViewport({
width: 1920,
height: 1080,
deviceScaleFactor: 1,
});
// 加载HTML内容
await page.setContent(html, {
waitUntil: "networkidle0",
});
// 生成PDF
const pdfPath = path.join(outputDir, `${fileName}.pdf`);
let pdfBuffer = await page.pdf({
path: pdfPath,
format: "A4",
margin: { top: "20mm", right: "20mm", bottom: "20mm", left: "20mm" },
printBackground: true,
preferCSSPageSize: true,
scale: 1, // 设置缩放比例为1
});
return pdfBuffer;
} catch (error) {
console.error("生成PDF失败:", error);
throw error;
} finally {
if (browser) {
await browser.close();
}
}
}
module.exports = {
generatePdfFromHtml,
};