实现nodejs基于puppeteer插件生成PDF功能

1、解决方案

  • pdf生成需要对已有的HTML进行PDF的转换生成,可分为两种形式:
    1)基于canvas的客户端生成方案
    2)基于nodejs + puppeteer的服务端生成方案

2、需求描述

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: '<Your BucketName>',
  // region以杭州为例(oss-cn-hangzhou),其他region按实际情况填写。
  region: '<Your Region>',
  // 阿里云主账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维,请登录RAM控制台创建RAM账号。
  accessKeyId: '<Your AccessKeyId>',
  accessKeySecret: '<Your AccessKeySecret>',
})
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容