12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697 |
- const { PATH_FILES } = require('../config')
- const logger = require('../log/index')
- const puppeteer = require('puppeteer');
- const fs = require('fs')
- const path = require('path')
- // 生成
- async function initBrowser () {
- logger.log.debug('启动', new Date().toLocaleString())
- return await puppeteer.launch({
- headless: true,
- args: ['--no-sandbox', '--disable-setuid-sandbox']
- });
- }
- let browser = null
- 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 = {}) {
- if (!browser) {
- browser = await initBrowser()
- }
- config = Object.assign( {
- filename: '',
- dir: '',
- nocache: false,
- 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.nocache) {
- const result = checkCache(outConfig.path)
- if (result) {
- logger.log.debug('命中缓存文件')
- return result
- }
- }
- const page = await browser.newPage();
- try {
- await page.setDefaultNavigationTimeout(0)
- await page.goto(url, {waitUntil: 'networkidle2'});
- await wait(config.delay || 1000)
- logger.log.debug('等待生成', new Date().toLocaleString())
- await page.pdf(outConfig);
- await page.close();
- logger.log.debug('当前时间', new Date().toLocaleString())
- return outConfig.path
- } catch (e) {
- logger.log.debug(e)
- await page.close();
- }
- }
- module.exports = createPDFOfURL
|