@@ -4,6 +4,10 @@ const path = require('path');
44const fs = require ( 'fs' ) ;
55const crypto = require ( 'crypto' ) ;
66const app = express ( ) ;
7+ const bodyParser = require ( 'body-parser' ) ;
8+
9+ app . use ( bodyParser . json ( ) ) ; // support json encoded bodies
10+ app . use ( bodyParser . urlencoded ( { extended : true } ) ) ; // support encoded bodies
711
812let port = 3000 ;
913let calls = {
@@ -20,7 +24,25 @@ app.get('/health', (req, res) => {
2024 deliverJson ( res , { isReady, calls} , isReady ? 200 : 503 ) ;
2125} ) ;
2226
23- app . get ( '/from-html' , async ( req , res ) => {
27+ app . post ( '/from-html' , async ( req , res ) => {
28+ const html = req . body . html ;
29+ const htmlFile = md5 ( html . substr ( 0 , 100 ) ) + '.html' ;
30+ const fullHtmlPath = path . join ( __dirname , storagePath , htmlFile ) ;
31+
32+ fs . writeFileSync ( fullHtmlPath , html ) ;
33+
34+ let pdfFilePath ;
35+ try {
36+ pdfFilePath = await generatePdf ( `file://${ fullHtmlPath } ` ) ;
37+ } catch ( err ) {
38+ console . log ( '/from-html: error generating PDF' , e ) ;
39+ let msg = 'failure generating PDF' ;
40+ deliverJson ( res , { msg, err} , 500 ) ;
41+ return ;
42+ }
43+
44+ deliverPdfFile ( res , pdfFilePath ) ;
45+ fs . unlinkSync ( fullHtmlPath ) ;
2446} ) ;
2547
2648app . get ( '/from-url' , async ( req , res ) => {
@@ -75,7 +97,7 @@ async function generatePdf(url) {
7597 waitUntil : 'networkidle2' ,
7698 } ) ;
7799
78- let filename = crypto . createHash ( ' md5' ) . update ( url ) . digest ( 'hex' ) + '.pdf' ;
100+ let filename = md5 ( url ) + '.pdf' ;
79101 const pdfFolder = path . join ( __dirname , storagePath ) ;
80102 if ( ! fs . existsSync ( pdfFolder ) ) {
81103 fs . mkdirSync ( pdfFolder ) ;
@@ -95,6 +117,10 @@ async function generatePdf(url) {
95117 return pdfFilePath ;
96118}
97119
120+ function md5 ( seed ) {
121+ return crypto . createHash ( 'md5' ) . update ( seed ) . digest ( 'hex' ) ;
122+ }
123+
98124app . listen ( port , ( ) => {
99125 console . log ( `Kool PDF service running at port ${ port } ` ) ;
100126 console . log ( `Going to start puppeter` ) ;
0 commit comments