pdf.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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. const {init} = require("../../../js-error/js/web");
  7. // 生成
  8. async function initBrowser () {
  9. logger.log.debug('启动', new Date().toLocaleString())
  10. return await puppeteer.launch({
  11. headless: true,
  12. args: ['--no-sandbox', '--disable-setuid-sandbox']
  13. });
  14. }
  15. let browser = null
  16. function checkCache (fPath) {
  17. try {
  18. const fStat = fs.statSync(fPath)
  19. if (fStat) {
  20. const isFile = fStat.isFile()
  21. if (isFile) {
  22. return fPath
  23. }
  24. }
  25. return false
  26. } catch (err) {
  27. return false
  28. }
  29. }
  30. function wait(ms) {
  31. return new Promise((resolve, reject) => {
  32. setTimeout(() => {
  33. console.log("Done waiting");
  34. resolve(ms)
  35. }, ms)
  36. })
  37. }
  38. async function createPDFOfURL (url, config = {}) {
  39. if (!browser) {
  40. browser = await initBrowser()
  41. }
  42. config = Object.assign( {
  43. filename: '',
  44. dir: '',
  45. nocache: false,
  46. width: '950px',
  47. height: '1360px',
  48. margin: {
  49. top: 0,
  50. bottom: 0
  51. },
  52. }, config)
  53. // 文件路径
  54. const outPath = path.join(PATH_FILES, config.dir)
  55. if (!fs.existsSync(outPath)) {
  56. fs.mkdirSync(outPath);
  57. }
  58. const outConfig = Object.assign({path: `${config.filename}.pdf`, width: config.width, height: config.height,printBackground: true }, config)
  59. outConfig.path = path.join(outPath, outConfig.path)
  60. // 检查缓存
  61. if (!config.nocache) {
  62. const result = checkCache(outConfig.path)
  63. if (result) {
  64. logger.log.debug('命中缓存文件')
  65. return result
  66. }
  67. }
  68. const page = await browser.newPage();
  69. try {
  70. await page.setDefaultNavigationTimeout(0)
  71. await page.goto(url, {waitUntil: 'networkidle2'});
  72. await wait(config.delay || 1000)
  73. logger.log.debug('等待生成', new Date().toLocaleString())
  74. await page.pdf(outConfig);
  75. await page.close();
  76. logger.log.debug('当前时间', new Date().toLocaleString())
  77. return outConfig.path
  78. } catch (e) {
  79. logger.log.debug(e)
  80. await page.close();
  81. }
  82. }
  83. module.exports = createPDFOfURL