ÖzgürKon 2021
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

113 lines
2.8 KiB

5 years ago
const puppeteer = require('puppeteer');
const {Logger, LogLevel} = require('plop-logger');
const {colorEmojiConfig} = require('plop-logger/lib/extra/colorEmojiConfig');
5 years ago
const handler = require('serve-handler');
const http = require('http');
5 years ago
Logger.config = colorEmojiConfig;
Logger.config.defaultLevel = LogLevel.Debug;
const logger = Logger.getLogger('pdf');
5 years ago
// Configuration
const output = 'static/schedule/schedule.pdf';
5 years ago
const serverConf = {
port: 8765,
options: {
"public": "./public"
}
};
const browserConf = {
5 years ago
headless: true,
args: ['--no-sandbox', '--disable-setuid-sandbox'],
5 years ago
defaultViewport: {width: 1280, height: 1700},
margin: {
top: "0cm",
right: "0cm",
bottom: "0cm",
left: "0cm"
},
devtools: false
};
async function startServer({port, options}) {
return new Promise((resolve, reject) => {
const server = http.createServer((request, response) =>
handler(request, response, options));
server.listen(port, err => {
if (err) {
logger.error('Fail to start server', err);
reject(err);
} else {
logger.info('Server started', () => `http://localhost:${port}`);
resolve(server);
}
});
});
}
async function stopServer(server) {
return new Promise((resolve, reject) => {
logger.info('Stopping server...');
server.close(err => {
if (err) {
logger.error('Fail to stop server', err);
reject(err);
} else {
logger.info('Server stopped');
resolve();
}
});
});
}
async function cleanupBeforePrint(page) {
const toHide = [
'body > header',
'body > footer',
'main .hero',
];
await page.$$eval(toHide.join(','), elts =>
elts.forEach(elt =>
elt.parentNode.removeChild(elt)));
await page.addStyleTag({
content: '@page { size: auto; }',
});
}
5 years ago
(async () => {
5 years ago
const server = await startServer(serverConf);
5 years ago
logger.info("launch puppeteer browser");
5 years ago
const browser = await puppeteer.launch(browserConf);
5 years ago
try {
logger.info("open new page");
const page = await browser.newPage();
logger.debug("opened new page");
const file = 'fr/schedule/index.html';
5 years ago
const url = `http://localhost:${serverConf.port}/${file}`;
5 years ago
logger.info("go to", url);
const pageResponse = await page.goto(url, {waitUntil: 'networkidle2'});
5 years ago
logger.debug("done", pageResponse.statusText());
5 years ago
5 years ago
await cleanupBeforePrint(page);
logger.info('export pdf', output);
5 years ago
const format = 'A3';
const scale = .4;
const printBackground = true;
await page.pdf({path:output, format, scale, printBackground});
5 years ago
logger.debug("pdf done");
} catch (e) {
console.error(e);
logger.error('Oops!', e);
} finally {
logger.info('close puppeteer browser');
await browser.close();
5 years ago
await stopServer(server);
5 years ago
}
})();