Create a PDF from Web Page

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`.

“`touch 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

“`‘content’, html);
page.render(‘demo.pdf’, {
format: ‘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();‘content’, html);
page.render(‘demo.pdf’, {
format: ‘pdf’

process.exit(0); // finally we are telling Nodejs to exit the script.“`

So guys, this is how we can generate PDFs with knowledge of HTML, CSS and javascript. Thank you for reading !

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.