html2html.mjs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import puppeteer from "puppeteer-core";
  2. import fs from "node:fs";
  3. import path from "node:path";
  4. import { fileURLToPath } from "node:url";
  5. async function run(fileName) {
  6. console.log(7, fileName);
  7. const pdfName = `${fileName}`.replace(".html", ".pdf");
  8. try {
  9. const browser = await puppeteer.launch({
  10. // executablePath: '/Applications/Google\ Chrome.app/Contents/MacOS/bin',
  11. executablePath:
  12. "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
  13. // ignoreHTTPSErrors: false, // 在导航期间忽略 HTTPS 错误
  14. // headless: false,
  15. defaultViewport: {
  16. // 为每个页面设置一个默认视口大小
  17. width: 1240,
  18. height: 1080,
  19. },
  20. });
  21. const page = await browser.newPage();
  22. // await page.goto(`file://${process.env.PWD}/${fileName}`);
  23. await page.goto(`file://${fileName}`);
  24. let inputElement = await page.$("html");
  25. const offsetHeight = await page.evaluate(
  26. () => document.querySelector("body").offsetHeight
  27. );
  28. console.log(offsetHeight, 21);
  29. console.log(inputElement);
  30. try {
  31. fs.unlinkSync(pdfName);
  32. } catch (e) {
  33. console.log(e);
  34. }
  35. await page.pdf({
  36. path: pdfName,
  37. height: offsetHeight + 110,
  38. width: 1240,
  39. margin: { left: 20, top: 20, right: 20, bottom: 20 },
  40. printBackground: true
  41. });
  42. // await page.pdf({path: 'index_002.pdf', format:'A4'})
  43. await browser.close();
  44. } catch (e) {
  45. console.log(e);
  46. }
  47. }
  48. export default run;
  49. // const filePath = path.join(__dirname, "index.html")
  50. // console.log(35, filePath)
  51. // const __filename = fileURLToPath(import.meta.url);
  52. //
  53. // // 👇️ "/home/john/Desktop/javascript"
  54. // const __dirname = process.cwd()
  55. // console.log('directory-name 👉️', __dirname);
  56. //
  57. // console.log('2222', process.execPath)
  58. // console.log('2222', process.cwd())