pdf.js 1.9 KB

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