03-jietu.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. const express = require('express');
  2. const shell = require('shelljs');
  3. const app = express();
  4. app.use(express.static('cover'));
  5. app.listen(3000, function () {
  6. console.log('Example app listening on port 3000!');
  7. });
  8. const pid = process.pid;
  9. // return
  10. const puppeteer = require('puppeteer');
  11. const utils = require('./utils/base');
  12. const start = async (utils) => {
  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((utils) => {
  20. // 设置标题
  21. const title = document.getElementById('title');
  22. const author = document.getElementById('author');
  23. title.innerText = utils.name;
  24. author.innerText = utils.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. }, utils);
  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(utils);