pdf.js 2.1 KB

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