1、解决方案
2、需求描述
- 项目中需要生成几十页的pdf文件,故之前写的一篇React实战(7)——Ant Design Pro项目下载多页PDF文件文章不能满足需求
- 实现步骤:前端调nodejs接口—>服务端pdf生成中—>生成完成—>前端显示下载按钮—>下载至电脑
3、完整代码
- nodejs基于koa2代码部分
// route.js
const koaRouter = require('koa-router')
const DownloadPdf = require('../controllers/downloadPdf')
const router = new koaRouter()
// 生成PDF
router.get('/createPdf', DownloadPdf.createPdf)
module.exports = router
// downloadPdf.js
const puppeteer = require('puppeteer')
const moment = require('moment')
const fs = require('fs')
class DownloadPdfModel {
// 启动pupeteer,加载页面
// 启动pupeteer,加载页面
const browser = await puppeteer.launch({
executablePath: '/root/dtea-client/dtea/koa-nodejs-server/node_modules/puppeteer/.local-chromium/linux-782078/chrome-linux/chrome', // 非本地环境配置node_model中chrome路径,本地联调需注释,否则报错
headless: true, // 无头
args: [
'--no-sandbox',
'--disable-dev-shm-usage',
'--disable-setuid-sandbox',
'--no-first-run',
'--no-zygote',
'--single-process'
]
})
const page = await browser.newPage()
await page.setViewport({
width: 1920,
height: 1080
})
// 打开页面
await page.goto(
`http://www.test.com/page/#/user/pdf/download`,
{
waitUntil: 'networkidle0', // 接口数据请求完开始生成pdf
}
)
// 生成pdf
let pdfFileName = `报告_${moment(new Date()).format('YYYYMMDDHHmm') + '.pdf'}`
let pdfFilePath = path.join(__dirname, '../../temp/', pdfFileName);
await page.pdf({
path: pdfFilePath,
format: 'A4',
scale: 1,
printBackground: true,
landscape: false,
displayHeaderFooter: false
});
// 一定要关闭,不然开太多虚拟chrome很消耗服务器内容
browser.close();
// 返回文件路径
ctx.status = 200
ctx.body = {
url: `${ctx.request.protocol}://${ctx.request.host}/temp/${pdfFileName}`
}
}
- 前端通过get访问接口'localhost:3000/createPdf'即可,不再赘述
4、将文件上传至OSS文件服务器
- 将生成在项目制定目录中的PDF文件上传至OSS文件服务器,毕竟每个pdf十几兆,都堆在服务器上也不太好
- 项目中引入OSS并添加配置项,具体配置可参考阿里云-nodejs上传本地文件
const OSS = require('ali-oss')
const client = new OSS({
bucket: '',
// region以杭州为例(oss-cn-hangzhou),其他region按实际情况填写。
region: '',
// 阿里云主账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维,请登录RAM控制台创建RAM账号。
accessKeyId: '',
accessKeySecret: '',
})
最新评论