Are you a web developer and want to create a PDF dynamically ? If you, then here I came with the solution, I will show you how to create a PDF from the HTML file/web page.
I assume that you have proper knowledge of Node.js programming and you knows basic commands of npm.
We will need a package named `phantomjs`. Let start with creating a file named `convert.js`.
We shall devide script into steps:
1) Create/Design an HTML file which you want to convert to PDF
/* Do some styling stuff here */
A big title here
A short or can be long paragraph written contains text as well as image of an apple
2) Now in convert.js, read the file using `fs` utility and store the content somewhere.
“`var html = require(‘fs’).readFileSync(‘demo.html’)“`
3) Create an instance of phantom js which can further be useful to create a page
“`var instance = phantom.create();
var page = instance.createPage();“`
4) set content to `page` and let page render the content, the page now will render this content to the file as pdf
Let us combine all the steps and the final file will be look like this.
“`var html = require(‘fs’).readFileSync(‘demo.html’);
var instance = phantom.create();
var page = instance.createPage();
process.exit(0); // finally we are telling Nodejs to exit the script.“`