main.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. const puppeteer = require('puppeteer');
  2. const fs = require('fs');
  3. (async function ()
  4. {
  5. try
  6. {
  7. console.log("StageRack HTML to PDF conversion tool");
  8. var args = process.argv.slice(2);
  9. let url = args[0];
  10. let fileDestination = args[1];
  11. if (url === undefined)
  12. {
  13. console.error("Didn't get an URL");
  14. process.exit(10);
  15. }
  16. console.log(" -> URL ", url);
  17. if (fileDestination === undefined)
  18. {
  19. console.error("Didn't get a file destination");
  20. process.exit(11);
  21. }
  22. console.log(" -> File ", fileDestination);
  23. if (fs.existsSync(fileDestination))
  24. {
  25. console.error("[ERROR] The file \"" + fileDestination + "\" already exists");
  26. process.exit(12);
  27. }
  28. const browser = await puppeteer.launch();
  29. const page = await browser.newPage();
  30. console.log("Rendering data...")
  31. await page.goto(url, {waitUntil: 'networkidle0'});
  32. await page.emulateMediaType('screen'); // To use normal CSS instead of only print styles
  33. console.log("Creating the PDF document...");
  34. // Documentation for this function: https://pptr.dev/api/puppeteer.page
  35. await page.pdf(
  36. {
  37. path: fileDestination,
  38. format: 'A4',
  39. omitBackground: false,
  40. printBackground: true,
  41. preferCSSPageSize: true,
  42. margin:
  43. {
  44. left: "1.27cm",
  45. right: "1.27cm",
  46. top: "1.27cm",
  47. bottom: "1.27cm",
  48. },
  49. });
  50. console.log('Conversion complete. PDF file generated successfully.');
  51. await browser.close();
  52. } catch (error)
  53. {
  54. console.error('An error occurred:', error);
  55. }
  56. process.exit();
  57. })();