html2pdf.mjs 1.6 KB

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