pdf.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. const { PATH_FILES } = require('../config')
  2. const logger = require('../log/index')
  3. const puppeteer = require('puppeteer');
  4. const fs = require('fs')
  5. const path = require('path')
  6. function checkCache (fPath) {
  7. try {
  8. const fStat = fs.statSync(fPath)
  9. if (fStat) {
  10. const isFile = fStat.isFile()
  11. if (isFile) {
  12. return fPath
  13. }
  14. }
  15. return false
  16. } catch (err) {
  17. return false
  18. }
  19. }
  20. async function createPDFOfURL (url, config = {}) {
  21. config = Object.assign( {
  22. filename: '',
  23. dir: '',
  24. cache: true,
  25. width: '950px',
  26. height: '1360px'
  27. }, config)
  28. // 文件路径
  29. const outPath = path.join(PATH_FILES, config.dir)
  30. if (!fs.existsSync(outPath)) {
  31. fs.mkdirSync(outPath);
  32. }
  33. const outConfig = Object.assign({path: `${config.filename}.pdf`, width: config.width, height: config.height,printBackground: true }, config)
  34. outConfig.path = path.join(outPath, outConfig.path)
  35. // 检查缓存
  36. if (config.cache) {
  37. const result = checkCache(outConfig.path)
  38. if (result) {
  39. logger.log.debug('命中缓存文件')
  40. return result
  41. }
  42. }
  43. // 生成
  44. logger.log.debug('启动', new Date().toLocaleString())
  45. const browser = await puppeteer.launch({headless:true});
  46. const page = await browser.newPage();
  47. await page.setDefaultNavigationTimeout(0)
  48. await page.goto(url, {waitUntil: 'networkidle2'});
  49. logger.log.debug('等待生成', new Date().toLocaleString())
  50. await page.pdf(outConfig);
  51. await browser.close();
  52. logger.log.debug('当前时间', new Date().toLocaleString())
  53. return outConfig.path
  54. }
  55. module.exports = createPDFOfURL