One of the perks our project, Maître, offers is that you can see and download restaurant’s menus, so you can access them anytime. To do so, we had to find the tool that allowed us to transform JSON’s information to PDF. So we took the JSON that API’s query return, with information from the database, and access the data in it and then design a standard menu for every restaurant with HTML, downloadable in PDF.
After considering several options like PDFKit or PDFMake, we chose html-pdf.
This tool would allow us to do this:
Let’s see how to install it:
First, we install html-pdf with npm:
During the installation PhantomJS will be downloaded automatically
Now let’s try the package with a simple code:
var codigo = `
<h1>Probando html-pdf</h1>
<p>Creamos nuestro PDF a partir de código HTML</p>
`;
pdf.create(codigo).toFile(‘./salida.pdf’, function(err, res) {
if (err){
console.log(err);
} else {
console.log(res);
}
});
What we have in the code is:
- html-pdf require
- A variable in which we are going to include our html code
- The create() method that receives the content we want to make, and it can also receive other configuration options, which we will see later
- The path where we want the file to be saved
- A callback
We run the file from the console with:
And it will create a PDF in the same folder that looks like this:
Having this code you can twist it as you like, even use CSS to make it look more atractive and use formats like JSON to obtain data and use it. Iss what we did in our case, using the JSON we create with the API, HTML and CSS to create the menus.
To do so, in addition to what we have seen so far we have also configured the package. PhantomJS offers multiple configuration options, which we can change with a JSON like this, that we include in our code and, as we said earlier, also as the second parameter of the create() method.
// Export options
“directory”: “/tmp”, // The directory the file gets written into if not using .toFile(filename, callback). default: ‘/tmp’
// Papersize Options: http://phantomjs.org/api/webpage/property/paper-size.html
“height”: “10.5in”, // allowed units: mm, cm, in, px
“width”: “8in”, // allowed units: mm, cm, in, px
– or –
“format”: “Letter”, // allowed units: A3, A4, A5, Legal, Letter, Tabloid
“orientation”: “portrait”, // portrait or landscape
// Page options
“border”: “0”, // default is 0, units: mm, cm, in, px
– or –
“border”: {
“top”: “2in”, // default is 0, units: mm, cm, in, px
“right”: “1in”,
“bottom”: “2in”,
“left”: “1.5in”
},
paginationOffset: 1, // Override the initial pagination number
“header”: {
“height”: “45mm”,
“contents”: ‘
‘
},
“footer”: {
“height”: “28mm”,
“contents”: {
first: ‘Cover page’,
2: ‘Second page’, // Any page number is working. 1-based index
default: ‘{{page}}/{{pages}}‘, // fallback value
last: ‘Last Page’
}
},
// Rendering options
“base”: “file:///home/www/your-asset-path”, // Base path that’s used to load files (images, css, js) when they aren’t referenced using a host
// Zooming option, can be used to scale images if `options.type` is not pdf
“zoomFactor”: “1”, // default is 1
// File options
“type”: “pdf”, // allowed file types: png, jpeg, pdf
“quality”: “75”, // only used for types png & jpeg
// Script options
“phantomPath”: “./node_modules/phantomjs/bin/phantomjs”, // PhantomJS binary which should get downloaded automatically
“phantomArgs”: [], // array of strings used as phantomjs args e.g. [“–ignore-ssl-errors=yes”]
“script”: ‘/url’, // Absolute path to a custom phantomjs script, use the file in lib/scripts as example
“timeout”: 30000, // Timeout that will cancel phantomjs, in milliseconds
// Time we should wait after window load
// accepted values are ‘manual’, some delay in milliseconds or undefined to wait for a render event
“renderDelay”: 1000,
// HTTP Headers that are used for requests
“httpHeaders”: {
// e.g.
“Authorization”: “Bearer ACEFAD8C-4B4D-4042-AB30-6C735F5BAC8B”
},
// To run Node application as Windows service
“childProcessOptions”: {
“detached”: true
}
// HTTP Cookies that are used for requests
“httpCookies”: [
// e.g.
{
“name”: “Valid-Cookie-Name”, // required
“value”: “Valid-Cookie-Value”, // required
“domain”: “localhost”,
“path”: “/foo”, // required
“httponly”: true,
“secure”: false,
“expires”: (new Date()).getTime() + (1000 * 60 * 60) // e.g. expires in 1 hour
}
]
}
And the create() method from before should look like this:
if (err){
console.log(err);
} else {
console.log(res);
}
});
And after following these steps we will have our PDF generated with the aspect that we choose.
Leave a Reply