1、解決方案
- pdf生成需要對已有的HTML進行PDF的轉換生成,可分為兩種形式:
1)基于canvas的客戶端生成方案
2)基于nodejs + puppeteer的服務端生成方案
2、需求描述
3、完整代碼
// 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>',
})