• Stars
    star
    3,560
  • Rank 12,458 (Top 0.3 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 10 years ago
  • Updated 6 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

This repo isn't maintained anymore as phantomjs got dreprecated a long time ago. Please migrate to headless chrome/puppeteer.

node-html-pdf

HTML to PDF converter that uses phantomjs

image
Example Business Card
-> and its Source file

Example Receipt

Changelog

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

Installation

Install the html-pdf utility via npm:

$ npm install -g html-pdf

Command-line example

$ html-pdf test/businesscard.html businesscard.pdf

Code example

var fs = require('fs');
var pdf = require('html-pdf');
var html = fs.readFileSync('./test/businesscard.html', 'utf8');
var options = { format: 'Letter' };

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

API

var pdf = require('html-pdf');
pdf.create(html).toFile([filepath, ]function(err, res){
  console.log(res.filename);
});

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

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


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

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.

<div id="pageHeader">Default header</div>
<div id="pageHeader-first">Header on first page</div>
<div id="pageHeader-2">Header on second page</div>
<div id="pageHeader-3">Header on third page</div>
<div id="pageHeader-last">Header on last page</div>
...
<div id="pageFooter">Default footer</div>
<div id="pageFooter-first">Footer on first page</div>
<div id="pageFooter-2">Footer on second page</div>
<div id="pageFooter-last">Footer on last page</div>

Options

config = {

  // 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": '<div style="text-align: center;">Author: Marc Bachmann</div>'
  },
  "footer": {
    "height": "28mm",
    "contents": {
      first: 'Cover page',
      2: 'Second page', // Any page number is working. 1-based index
      default: '<span style="color: #444;">{{page}}</span>/<span>{{pages}}</span>', // 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"]
  "localUrlAccess": false, // Prevent local file:// access by passing '--local-url-access=false' to phantomjs
                           // For security reasons you should keep the default value if you render arbritary html/js.
  "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
    }
  ]

}

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.

More Repositories

1

electron-rpc

🔃 A lightweight wrapper around the electron ipc module.
JavaScript
59
star
2

dockerfile-libvips

🌄 All libvips dependencies & libvips built from source
Dockerfile
33
star
3

localized-countries

🌐 Country code to name mappings for several languages
JavaScript
25
star
4

limelight

🔦 An extendable, interactive command launcher. Inspired by spotlight & flashlight.
JavaScript
12
star
5

opentelemetry-node-metrics

JavaScript
11
star
6

dockerfile-kibana4

📈 Kibana 4 Dashboard, Environment variable support, without elasticsearch server
Shell
10
star
7

umzug-cli

JavaScript
10
star
8

rancher-prometheus-config

A prometheus confd setup that automatically extracts all metrics of containers using labels. No configuration needed.
Dockerfile
9
star
9

passport-light

A passport authenticator without all the session handling and monkey patching. This module is archived as we've successfully migrated everything to openid connect. I suggest you do do so too.
JavaScript
7
star
10

eventsourced-object

𝌭 A minimal eventsourcing helper for objects and classes
JavaScript
7
star
11

authorizedkeys-github

A service that fetches public keys from github and writes them into an .ssh/authorized_keys file
JavaScript
7
star
12

github-issue-templates

ARCHIVED. Github has now that built in - A chrome extension to enhance the 'New Issue' button with a dropdown populated from a templates file on github.
JavaScript
7
star
13

colt

An extendable sequencing library with a chainable api
JavaScript
6
star
14

knex-umzug

JavaScript
5
star
15

stripe-create-charge

A microservice to charge a credit card using a stripe token retrieved in a client side checkout process.
JavaScript
5
star
16

simple-text-search

JavaScript
4
star
17

flashlight-emoji

Python
4
star
18

find-in-batches

Batch find and processing method. DEPRECATED: Please use native async iterators
JavaScript
3
star
19

validate-scope

Checks whether a subset is contained in a list of oauth scopes. Uses code generation to reach better performance.
JavaScript
2
star
20

require-suggestion

Monkey patches require to show suggestions for requires that throw an error
JavaScript
2
star
21

npm-module-search

🔍 A module to search for npm modules
JavaScript
2
star
22

muemit

An EventEmitter implementation for the browser that imitates the nodejs EventEmitter api.
JavaScript
2
star
23

assert-node-version

A module to assert the current node version against the one in the .npmrc or package.json file
JavaScript
2
star
24

cached-callback

Resolve all the callbacks registered during an invocation of a function with its value.
JavaScript
2
star
25

require-resolve-cli

JavaScript
1
star
26

boolean-expression

⋀⋁ Create a boolean expression that's safe (you can still harm your app if you don't validate) to eval.
JavaScript
1
star
27

metalman

Composes configurable methods which are based on middlewares.
JavaScript
1
star
28

contacts-app

JavaScript
1
star
29

dockerfile-hhvm-wordpress

A dockerfile with hhvm & nginx for wordpress
Shell
1
star
30

freckle-slackbot

🤖 A slackbot to create time tracking entries on letsfreckle.com
JavaScript
1
star
31

coercion

Node module with query helpers to write a REST API
JavaScript
1
star
32

concat-arrays

Concatenates arrays or array-like objects (arguments)
JavaScript
1
star
33

http-condition

Support conditions for http requests based on a simple dsl.
JavaScript
1
star
34

github-badges

JavaScript
1
star
35

metalman-schema

JavaScript
1
star
36

github-todo-status

Extracts TODOs out of your source code and adds the status report to your pull request
JavaScript
1
star
37

borderless-table

JavaScript
1
star
38

livingdocs-delivery

A sample isomorphic app setup that uses the livingdocs-api.
JavaScript
1
star
39

hrtime-milliseconds

Calculates a diff in milliseconds between invocations.
JavaScript
1
star
40

mocha-context-reporter

JavaScript
1
star