const { PATH_FILES } = require('../config') const logger = require('../log/index') const puppeteer = require('puppeteer'); const fs = require('fs') const path = require('path') function checkCache (fPath) { try { const fStat = fs.statSync(fPath) if (fStat) { const isFile = fStat.isFile() if (isFile) { return fPath } } return false } catch (err) { return false } } function wait(ms) { return new Promise((resolve, reject) => { setTimeout(() => { console.log("Done waiting"); resolve(ms) }, ms) }) } async function createPDFOfURL (url, config = {}) { config = Object.assign( { filename: '', dir: '', cache: true, width: '950px', height: '1360px', margin: { top: 0, bottom: 0 }, }, config) // 文件路径 const outPath = path.join(PATH_FILES, config.dir) if (!fs.existsSync(outPath)) { fs.mkdirSync(outPath); } const outConfig = Object.assign({path: `${config.filename}.pdf`, width: config.width, height: config.height,printBackground: true }, config) outConfig.path = path.join(outPath, outConfig.path) // 检查缓存 if (config.cache) { const result = checkCache(outConfig.path) if (result) { logger.log.debug('命中缓存文件') return result } } // 生成 logger.log.debug('启动', new Date().toLocaleString()) const browser = await puppeteer.launch({ headless: true, args: ['--no-sandbox', '--disable-setuid-sandbox'] }); const page = await browser.newPage(); await page.setDefaultNavigationTimeout(0) await page.goto(url, {waitUntil: 'networkidle2'}); await wait(1000) logger.log.debug('等待生成', new Date().toLocaleString()) await page.pdf(outConfig); await browser.close(); logger.log.debug('当前时间', new Date().toLocaleString()) return outConfig.path } module.exports = createPDFOfURL