main.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. console.log("Failure Error Text", request.failure().errorText);
  34. process.exit(13);
  35. });
  36. page.on('pageerror', function(message)
  37. {
  38. console.log("Page Error", message);
  39. process.exit(13);
  40. });
  41. console.log("Rendering data...");
  42. let response = await page.goto(url, {waitUntil: 'networkidle0'});
  43. let httpStatus = response.status();
  44. console.log(" -> Got HTTP code " + httpStatus);
  45. if (httpStatus !== 200)
  46. {
  47. console.log("Error: got HTTP response " + httpStatus + ". Aborting");
  48. process.exit(20);
  49. }
  50. await page.emulateMediaType('print');
  51. console.log("Creating the PDF document...");
  52. // Documentation for this function: https://pptr.dev/api/puppeteer.page
  53. await page.pdf(
  54. {
  55. path: fileDestination,
  56. format: 'A4',
  57. omitBackground: false,
  58. printBackground: true,
  59. preferCSSPageSize: true,
  60. margin:
  61. {
  62. left: "1.27cm",
  63. right: "1.27cm",
  64. top: "1.27cm",
  65. bottom: "1.27cm",
  66. }
  67. });
  68. console.log('Conversion complete. PDF file generated successfully.');
  69. await browser.close();
  70. } catch (error)
  71. {
  72. console.log('An error occurred:', error);
  73. process.exit(1);
  74. }
  75. process.exit();
  76. })();