html2pdf.mjs 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import puppeteer from "puppeteer";
  2. import fs from 'node:fs'
  3. import path from 'node:path'
  4. import {fileURLToPath} from 'node:url';
  5. async function run() {
  6. try {
  7. const browser = await puppeteer.launch({
  8. // executablePath: '/Applications/Google\ Chrome.app/Contents/MacOS/bin',
  9. // ignoreHTTPSErrors: false, // 在导航期间忽略 HTTPS 错误
  10. // headless: false,
  11. defaultViewport: { // 为每个页面设置一个默认视口大小
  12. width: 1920,
  13. height: 1080
  14. }
  15. });
  16. const page = await browser.newPage();
  17. await page.goto('file:///Users/honghaitao/code/node_project/md2pdf/index.html');
  18. let inputElement = await page.$('html');
  19. const offsetHeight = await page.evaluate(() => document.querySelector('body').offsetHeight);
  20. // console.log(offsetHeight);
  21. // console.log(inputElement)
  22. await page.pdf({path: 'index_002.pdf',height: offsetHeight,width: 1920})
  23. await browser.close();
  24. } catch ( e ) {
  25. console.log(e)
  26. }
  27. }
  28. export default run;
  29. // const filePath = path.join(__dirname, "index.html")
  30. // console.log(35, filePath)
  31. // const __filename = fileURLToPath(import.meta.url);
  32. //
  33. // // 👇️ "/home/john/Desktop/javascript"
  34. // const __dirname = process.cwd()
  35. // console.log('directory-name 👉️', __dirname);
  36. //
  37. // console.log('2222', process.execPath)
  38. // console.log('2222', process.cwd())