|
@@ -0,0 +1,65 @@
|
|
|
+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
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+async function createPDFOfURL (url, config = {}) {
|
|
|
+ config = Object.assign( {
|
|
|
+ filename: '',
|
|
|
+ dir: '',
|
|
|
+ cache: true,
|
|
|
+ width: '950px',
|
|
|
+ height: '1360px'
|
|
|
+ }, 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});
|
|
|
+ const page = await browser.newPage();
|
|
|
+ await page.setDefaultNavigationTimeout(0)
|
|
|
+ await page.goto(url, {waitUntil: 'networkidle2'});
|
|
|
+ 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
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+
|