zhangyuhan 3 лет назад
Родитель
Сommit
a67b1203b0
5 измененных файлов с 66 добавлено и 2 удалено
  1. 0 1
      .gitignore
  2. 65 0
      bin/create-pdf/pdf.js
  3. 1 1
      bin/server/router.js
  4. BIN
      web/files/1.pdf
  5. 0 0
      web/logs/log.2021-12-08.log

+ 0 - 1
.gitignore

@@ -2,7 +2,6 @@
 node_modules
 /dist
 /unpackage/
-*.pdf
 
 # local env files
 .env.local

+ 65 - 0
bin/create-pdf/pdf.js

@@ -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
+
+
+
+
+

+ 1 - 1
bin/server/router.js

@@ -2,7 +2,7 @@ const { LISTEN_PORT, PATH_ROOT, DOMAIN } = require('../config')
 const Koa = require('koa')
 const StaticServer = require('koa-static')
 const Router = require('koa-router')
-const createPDFOfURL = require('../pdf/pdf')
+const createPDFOfURL = require('../create-pdf/pdf')
 
 const logger = require('../log/index')
 const miSend = require('./middleware')

BIN
web/files/1.pdf


+ 0 - 0
web/logs/log.2021-12-08.log