main.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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.log("Didn't get an URL");
  14. process.exit(10);
  15. }
  16. console.log(" -> URL ", url);
  17. if (fileDestination === undefined)
  18. {
  19. console.log("Didn't get a file destination");
  20. process.exit(11);
  21. }
  22. console.log(" -> File ", fileDestination);
  23. if (fs.existsSync(fileDestination))
  24. {
  25. console.log("[ERROR] The file \"" + fileDestination + "\" already exists");
  26. process.exit(12);
  27. }
  28. const browser = await puppeteer.launch({headless: true, args: ['--no-sandbox']});
  29. const page = await browser.newPage();
  30. page.on('requestfailed', function(request)
  31. {
  32. console.log("Request failed", request);
  33. process.exit(13);
  34. });
  35. page.on('pageerror', function(request)
  36. {
  37. console.log("Page Error", request);
  38. process.exit(13);
  39. });
  40. console.log("Rendering data...");
  41. let response = await page.goto(url, {waitUntil: 'networkidle0'});
  42. let httpStatus = response.status();
  43. console.log(" -> Got HTTP code " + httpStatus);
  44. if (httpStatus !== 200)
  45. {
  46. console.log("Error: got HTTP response " + httpStatus + ". Aborting");
  47. process.exit(20);
  48. }
  49. await page.emulateMediaType('print');
  50. console.log("Creating the PDF document...");
  51. // Documentation for this function: https://pptr.dev/api/puppeteer.page
  52. await page.pdf(
  53. {
  54. path: fileDestination,
  55. format: 'A4',
  56. omitBackground: false,
  57. printBackground: true,
  58. preferCSSPageSize: true,
  59. margin:
  60. {
  61. left: "1.27cm",
  62. right: "1.27cm",
  63. top: "1.27cm",
  64. bottom: "1.27cm",
  65. }
  66. });
  67. console.log('Conversion complete. PDF file generated successfully.');
  68. await browser.close();
  69. } catch (error)
  70. {
  71. console.log('An error occurred:', error);
  72. process.exit(1);
  73. }
  74. process.exit();
  75. })();