Advertisement
Guest User

Untitled

a guest
Mar 19th, 2019
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. 'use strict';
  2.  
  3. // dependencies
  4. const express = require('express');
  5. const bodyParser = require('body-parser');
  6. const path = require('path');
  7. const fs = require('fs');
  8. const puppeteer = require('puppeteer'); // the package to generate pdf
  9. const EventEmitter = require('events');
  10. const opn = require('opn');
  11.  
  12. const app = express();
  13. const emitter = new EventEmitter();
  14.  
  15. // generates a unique invoice number
  16. let today = new Date();
  17. let dd = today.getDate();
  18. let mm = today.getMonth() + 1;
  19. let invoicenum = '';
  20. let yyyy = today.getFullYear();
  21.  
  22. if (dd < 10) {
  23.     dd = '0' + dd;
  24. }
  25.  
  26. if (mm < 10) {
  27.     mm = '0' + mm;
  28. }
  29.  
  30. today = dd + '.' + mm + '.' + yyyy;
  31. invoicenum = dd + mm + yyyy + Math.floor(Math.random() * 1000) + 1;
  32.  
  33. // events
  34. emitter.on('toPdf', () => {
  35.     opn('http://localhost:3000/generate');
  36. });
  37.  
  38. emitter.on('generatePdf', async () => {
  39.     const url = 'http://localhost:3000/create';
  40.     const browser = await puppeteer.launch();
  41.     const page = await browser.newPage();
  42.     await page.goto(url, {waitUntil: 'networkidle2'});
  43.     await page.pdf({path: `invoice_${invoicenum}.pdf`, format: 'A4'});
  44.  
  45.     await browser.close();
  46.     console.log('The invoice has been generated.');
  47.     await opn(`http://localhost:3000/invoice_${invoicenum}.pdf`);
  48. });
  49.  
  50. app.use(express.static(__dirname));
  51. app.use(bodyParser.urlencoded({ extended: true }));
  52.  
  53. // routing
  54. app.get('/', (req, res) => {
  55.     res.sendFile(path.join(__dirname + '/index.html'));
  56. });
  57.  
  58. app.post('/create', (req, res) => {
  59.     let parsedHtml = req.body.data;
  60.  
  61.     fs.writeFile('invoice.html', parsedHtml, (err) => {
  62.         if (err) {
  63.             console.log('An error occured.');
  64.             return;
  65.         } else {
  66.             console.log('The new HTML file was successfully created.');
  67.         }
  68.     });
  69. });
  70.  
  71. app.get('/create', (req, res) => {
  72.     res.sendFile(path.join(__dirname + '/invoice.html'));
  73.  
  74.     emitter.emit('toPdf');
  75. });
  76.  
  77. app.get('/generate', (req, res) => {
  78.     emitter.emit('generatePdf');
  79. });
  80.  
  81. // listening on port
  82. app.listen(3000, () => {
  83.     console.log('Server is running on port 3000...');
  84. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement