03-jietu 1.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. const express = require('express');
  2. const shell = require('shelljs');
  3. const config = require('./utils/config');
  4. const app = express();
  5. app.use(express.static('cover'));
  6. app.listen(3000, function () {
  7. console.log('开始制作封面!');
  8. });
  9. const pid = process.pid;
  10. // return
  11. const puppeteer = require('puppeteer');
  12. const start = async (config) => {
  13. const browser = await puppeteer.launch({
  14. args: ['--no-sandbox', '--disable-setuid-sandbox'], // 沙箱模式下运行
  15. });
  16. const page = await browser.newPage();
  17. await page.goto('http://localhost:3000/');
  18. //调用evaluate 方法返回id 为form元素的位置信息
  19. let clip = await page.evaluate((config) => {
  20. // 设置标题
  21. const title = document.getElementById('title');
  22. const author = document.getElementById('author');
  23. title.innerText = config.name;
  24. author.innerText = config.author;
  25. let {
  26. x,
  27. y,
  28. width,
  29. height
  30. } = document.getElementById('page').getBoundingClientRect();
  31. return {
  32. x,
  33. y,
  34. width,
  35. height
  36. };
  37. }, config);
  38. await page.screenshot({
  39. path: './book/OEBPS/Images/cover.jpg',
  40. clip: clip //设置clip 属性
  41. });
  42. await page.close();
  43. await browser.close();
  44. shell.exec(`kill ${pid}`);
  45. };
  46. start(config);