node-html-pdf

This repo isn't maintained anymore as phantomjs got dreprecated a long time...

README

node-html-pdf

HTML to PDF converter that uses phantomjs

image


Changelog


Have a look at the releases page: https://github.com/marcbachmann/node-html-pdf/releases

Installation


Install the html-pdf utility via npm:

  1. ```
  2. $ npm install -g html-pdf
  3. ```

Command-line example


  1. ```
  2. $ html-pdf test/businesscard.html businesscard.pdf
  3. ```

Code example

  1. ``` js
  2. var fs = require('fs');
  3. var pdf = require('html-pdf');
  4. var html = fs.readFileSync('./test/businesscard.html', 'utf8');
  5. var options = { format: 'Letter' };

  6. pdf.create(html, options).toFile('./businesscard.pdf', function(err, res) {
  7.   if (err) return console.log(err);
  8.   console.log(res); // { filename: '/app/businesscard.pdf' }
  9. });
  10. ```

API


  1. ``` js
  2. var pdf = require('html-pdf');
  3. pdf.create(html).toFile([filepath, ]function(err, res){
  4.   console.log(res.filename);
  5. });

  6. pdf.create(html).toStream(function(err, stream){
  7.   stream.pipe(fs.createWriteStream('./foo.pdf'));
  8. });

  9. pdf.create(html).toBuffer(function(err, buffer){
  10.   console.log('This is a buffer:', Buffer.isBuffer(buffer));
  11. });


  12. // for backwards compatibility
  13. // alias to pdf.create(html[, options]).toBuffer(callback)
  14. pdf.create(html [, options], function(err, buffer){});
  15. ```

Footers and Headers


html-pdf can read the header or footer either out of the footer and header config object or out of the html source. You can either set a default header & footer or overwrite that by appending a page number (1 based index) to the id="pageHeader" attribute of a html tag.

You can use any combination of those tags. The library tries to find any element, that contains the pageHeader or pageFooter id prefix.
  1. ``` html
  2. <div id="pageHeader">Default header</div>
  3. <div id="pageHeader-first">Header on first page</div>
  4. <div id="pageHeader-2">Header on second page</div>
  5. <div id="pageHeader-3">Header on third page</div>
  6. <div id="pageHeader-last">Header on last page</div>
  7. ...
  8. <div id="pageFooter">Default footer</div>
  9. <div id="pageFooter-first">Footer on first page</div>
  10. <div id="pageFooter-2">Footer on second page</div>
  11. <div id="pageFooter-last">Footer on last page</div>
  12. ```


Options

  1. ``` js
  2. config = {

  3.   // Export options
  4.   "directory": "/tmp",       // The directory the file gets written into if not using .toFile(filename, callback). default: '/tmp'

  5.   // Papersize Options: http://phantomjs.org/api/webpage/property/paper-size.html
  6.   "height": "10.5in",        // allowed units: mm, cm, in, px
  7.   "width": "8in",            // allowed units: mm, cm, in, px
  8.   - or -
  9.   "format": "Letter",        // allowed units: A3, A4, A5, Legal, Letter, Tabloid
  10.   "orientation": "portrait", // portrait or landscape

  11.   // Page options
  12.   "border": "0",             // default is 0, units: mm, cm, in, px
  13.   - or -
  14.   "border": {
  15.     "top": "2in",            // default is 0, units: mm, cm, in, px
  16.     "right": "1in",
  17.     "bottom": "2in",
  18.     "left": "1.5in"
  19.   },

  20.   paginationOffset: 1,       // Override the initial pagination number
  21.   "header": {
  22.     "height": "45mm",
  23.     "contents": '<div style="text-align: center;">Author: Marc Bachmann</div>'
  24.   },
  25.   "footer": {
  26.     "height": "28mm",
  27.     "contents": {
  28.       first: 'Cover page',
  29.       2: 'Second page', // Any page number is working. 1-based index
  30.       default: '<span style="color: #444;">{{page}}</span>/<span>{{pages}}</span>', // fallback value
  31.       last: 'Last Page'
  32.     }
  33.   },


  34.   // Rendering options
  35.   "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

  36.   // Zooming option, can be used to scale images if `options.type` is not pdf
  37.   "zoomFactor": "1", // default is 1

  38.   // File options
  39.   "type": "pdf",           // allowed file types: png, jpeg, pdf
  40.   "quality": "75",         // only used for types png & jpeg

  41.   // Script options
  42.   "phantomPath": "./node_modules/phantomjs/bin/phantomjs", // PhantomJS binary which should get downloaded automatically
  43.   "phantomArgs": [], // array of strings used as phantomjs args e.g. ["--ignore-ssl-errors=yes"]
  44.   "localUrlAccess": false, // Prevent local file:// access by passing '--local-url-access=false' to phantomjs
  45.                            // For security reasons you should keep the default value if you render arbritary html/js.
  46.   "script": '/url',        // Absolute path to a custom phantomjs script, use the file in lib/scripts as example
  47.   "timeout": 30000,        // Timeout that will cancel phantomjs, in milliseconds

  48.   // Time we should wait after window load
  49.   // accepted values are 'manual', some delay in milliseconds or undefined to wait for a render event
  50.   "renderDelay": 1000,

  51.   // HTTP Headers that are used for requests
  52.   "httpHeaders": {
  53.     // e.g.
  54.     "Authorization": "Bearer ACEFAD8C-4B4D-4042-AB30-6C735F5BAC8B"
  55.   },

  56.   // To run Node application as Windows service
  57.   "childProcessOptions": {
  58.     "detached": true
  59.   }

  60.   // HTTP Cookies that are used for requests
  61.   "httpCookies": [
  62.     // e.g.
  63.     {
  64.       "name": "Valid-Cookie-Name", // required
  65.       "value": "Valid-Cookie-Value", // required
  66.       "domain": "localhost",
  67.       "path": "/foo", // required
  68.       "httponly": true,
  69.       "secure": false,
  70.       "expires": (new Date()).getTime() + (1000 * 60 * 60) // e.g. expires in 1 hour
  71.     }
  72.   ]

  73. }
  74. ```

The full options object gets converted to JSON and will get passed to the phantomjs script as third argument.  
There are more options concerning the paperSize, header & footer options inside the phantomjs script.