123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687 |
- const puppeteer = require('puppeteer');
- const fs = require('fs');
- (async function ()
- {
- try
- {
- console.log("StageRack HTML to PDF conversion tool");
- var args = process.argv.slice(2);
- let url = args[0];
- let fileDestination = args[1];
-
- if (url === undefined)
- {
- console.log("Didn't get an URL");
- process.exit(10);
- }
- console.log(" -> URL ", url);
-
- if (fileDestination === undefined)
- {
- console.log("Didn't get a file destination");
- process.exit(11);
- }
- console.log(" -> File ", fileDestination);
-
- if (fs.existsSync(fileDestination))
- {
- console.log("[ERROR] The file \"" + fileDestination + "\" already exists");
- process.exit(12);
- }
-
- const browser = await puppeteer.launch({headless: true, args: ['--no-sandbox']});
- const page = await browser.newPage();
- page.on('requestfailed', function(request)
- {
- console.log("Request failed", request);
- process.exit(13);
- });
- page.on('pageerror', function(request)
- {
- console.log("Page Error", request);
- process.exit(13);
- });
- console.log("Rendering data...");
- let response = await page.goto(url, {waitUntil: 'networkidle0'});
- let httpStatus = response.status();
- console.log(" -> Got HTTP code " + httpStatus);
- if (httpStatus !== 200)
- {
- console.log("Error: got HTTP response " + httpStatus + ". Aborting");
- process.exit(20);
- }
- await page.emulateMediaType('print');
-
-
- console.log("Creating the PDF document...");
- // Documentation for this function: https://pptr.dev/api/puppeteer.page
- await page.pdf(
- {
- path: fileDestination,
- format: 'A4',
- omitBackground: false,
- printBackground: true,
- preferCSSPageSize: true,
- margin:
- {
- left: "1.27cm",
- right: "1.27cm",
- top: "1.27cm",
- bottom: "1.27cm",
- }
- });
- console.log('Conversion complete. PDF file generated successfully.');
-
- await browser.close();
- } catch (error)
- {
- console.log('An error occurred:', error);
- process.exit(1);
- }
- process.exit();
- })();
|