Skip to content

Commit

Permalink
Add toBuffer, toStream & toFile methods
Browse files Browse the repository at this point in the history
  • Loading branch information
marcbachmann committed Jan 21, 2015
1 parent c1dc25f commit 3ea3cc3
Show file tree
Hide file tree
Showing 9 changed files with 243 additions and 91 deletions.
36 changes: 21 additions & 15 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,18 @@

```javascript
var fs = require('fs');
var pdf = require('./lib');
var pdf = require('html-pdf');
var html = fs.readFileSync('./test/businesscard.html', 'utf8')
pdf.create(html, { width: '50mm', height: '90mm'}, function(err, buffer) {
var options = { filename: './businesscard.pdf', format: 'Letter' };

This comment has been minimized.

Copy link
@marcbachmann

marcbachmann Jun 30, 2015

Author Owner

filename: './businesscard.pdf' as option is deprecated. Please use the following code:

pdf.create(html, options).toFile('./businesscard.pdf', function(err, res) {
    if (err) return console.log(err);
    console.log(res); // { filename: './businesscard.pdf' }
}); 
pdf(html, options).exec(function(err, res) {
if (err) return console.log(err);
fs.writeFile('businesscard.pdf', buffer);
console.log(res);
/*
{
filename: './businesscard.pdf',
pages: 1
}
*/
});
```

Expand All @@ -32,16 +39,19 @@ pdf.create(html [, options], callback)

```javascript
var pdf = require('html-pdf');
var callback = function(err, buffer){}
pdf.create(htmlString, options, callback)
pdf.create(htmlString, options, function(err, res){
console.log(res); // { "filename": "/tmp/path" }
})
```


## Options
```javascript
config = {
// Script options
script: '/url' // Absolute path to a custom phantomjs script, use the file in lib/scripts as example
timeout: 10000 // Timeout that will cancel phantomjs, in milliseconds

// Export options
"filename": "/tmp/html-pdf-123-123.pdf" // The file path of the file that will be written. If you want to save the file permanently, you have to pass this option.
"directory": "/tmp" // The directory the file gets written into if no filename is defined. default: '/tmp'

// Papersize Options: http://phantomjs.org/api/webpage/property/paper-size.html
"height": "", // allowed units: mm, cm, in, px
Expand All @@ -50,7 +60,6 @@ config = {
"format": "A4", // 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
"header": {
Expand All @@ -61,18 +70,15 @@ config = {
"height": "28mm",
"contents": '<span style="color: #444;">{{page}}</span>/<span>{{pages}}</span>'
},


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

// Script options
script: '/url' // Absolute path to a custom phantomjs script, use the file in lib/scripts as example
timeout: 10000 // Timeout that will cancel phantomjs, in milliseconds

// Export options
"buffer": true, // only supported on certain systems
- or -
"filename": "/tmp/html-pdf-123-123.pdf" // The file path of the file that will be written. If you want to save the file permanently, you have to pass this option.
"directory": "/tmp" // The directory the file gets written into if no filename is defined. default: '/tmp'
}
```

Expand Down
6 changes: 1 addition & 5 deletions lib/index.coffee
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
PDF = require('./pdf')

module.exports = (html, options, callback) ->
exports.create = (html, options, callback) ->
if arguments.length == 1
return new PDF(html)

Expand All @@ -17,7 +17,3 @@ module.exports = (html, options, callback) ->
return callback(err)

pdf.exec(callback)


module.exports.create = ->
module.exports.apply(undefined, arguments)
6 changes: 1 addition & 5 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ var PDF;

PDF = require('./pdf');

module.exports = function(html, options, callback) {
exports.create = function(html, options, callback) {
var err, pdf;
if (arguments.length === 1) {
return new PDF(html);
Expand All @@ -22,7 +22,3 @@ module.exports = function(html, options, callback) {
}
return pdf.exec(callback);
};

module.exports.create = function() {
return module.exports.apply(void 0, arguments);
};
11 changes: 11 additions & 0 deletions lib/pdf.coffee
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,17 @@ module.exports = class PDF
stream


toFile: (filename, callback) ->
assert(arguments.length == 2, 'html-pdf: The method pdf.toFile([filename, ]callback) requires two arguments.')
if arguments.length == 1
callback = filename
filename = undefined
else
@options.filename = filename
@exec(callback)
stream


exec: (callback) ->
child = childprocess.spawn(phantomjs.path, [@script])
stdout = []
Expand Down
12 changes: 12 additions & 0 deletions lib/pdf.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,18 @@ module.exports = PDF = (function() {
return stream;
};

PDF.prototype.toFile = function(filename, callback) {
assert(arguments.length === 2, 'html-pdf: The method pdf.toFile([filename, ]callback) requires two arguments.');
if (arguments.length === 1) {
callback = filename;
filename = void 0;
} else {
this.options.filename = filename;
}
this.exec(callback);
return stream;
};

PDF.prototype.exec = function(callback) {
var child, stderr, stdout, timeout;
child = childprocess.spawn(phantomjs.path, [this.script]);
Expand Down
2 changes: 2 additions & 0 deletions lib/scripts/pdf_a4_portrait.coffee
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ exit('Did not receive any html') if !json.html?.trim()
options = json.options
page = webpage.create()
page.content = json.html
page.viewportSize = vp if vp = options.viewportSize
totalPages = 0


# Set up content
Expand Down
124 changes: 124 additions & 0 deletions lib/scripts/pdf_a4_portrait.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
var content, exit, json, options, page, paper, setContent, system, totalPages, type, vp, webpage, _i, _len, _ref, _ref1, _ref2, _ref3;

system = require('system');

webpage = require('webpage');

exit = function(error) {
var message;
if (typeof error === 'string') {
message = error;
}
if (error) {
system.stderr.write("html-pdf: " + (message || ("Unknown Error " + error)) + "\n");
}
return phantom.exit(error ? 1 : 0);
};

setTimeout(function() {
return exit('Force timeout');
}, 120000);

json = JSON.parse(system.stdin.readLine());

if (!((_ref = json.html) != null ? _ref.trim() : void 0)) {
exit('Did not receive any html');
}

options = json.options;

page = webpage.create();

page.content = json.html;

if (vp = options.viewportSize) {
page.viewportSize = vp;
}

totalPages = 0;

content = page.evaluate(function() {
var $body, $footer, $header, body, footer, header, styles, _ref1;
styles = ((_ref1 = document.querySelector('head style')) != null ? _ref1.outerHTML : void 0) || '';
if ($header = document.getElementById('pageHeader')) {
header = $header.outerHTML;
$header.parentNode.removeChild($header);
}
if ($footer = document.getElementById('pageFooter')) {
footer = $footer.outerHTML;
$footer.parentNode.removeChild($footer);
}
if ($body = document.getElementById('pageContent')) {
body = $body.outerHTML;
} else {
body = document.body.outerHTML;
}
return {
styles: styles,
header: header,
body: body,
footer: footer
};
});

paper = {
border: options.border || '0'
};

if (options.height && options.width) {
paper.width = options.width;
paper.height = options.height;
} else {
paper.format = options.format || 'A4';
paper.orientation = options.orientation || 'portrait';
}

setContent = function(type) {
var _ref1;
return paper[type] = {
height: (_ref1 = options[type]) != null ? _ref1.height : void 0,
contents: phantom.callback(function(pageNum, numPages) {
var _ref2;
return (((_ref2 = options[type]) != null ? _ref2.contents : void 0) || content[type] || '').replace('{{page}}', pageNum).replace('{{pages}}', numPages) + content.styles;
})
};
};

_ref1 = ['header', 'footer'];
for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
type = _ref1[_i];
if (options[type] || content[type]) {
setContent(type);
}
}

if ((_ref2 = paper.header) != null) {
if (_ref2.height == null) {
_ref2.height = '45mm';
}
}

if ((_ref3 = paper.footer) != null) {
if (_ref3.height == null) {
_ref3.height = '28mm';
}
}

page.paperSize = paper;

page.onLoadFinished = function(status) {
var fileOptions, filename;
fileOptions = {
type: options.type || 'pdf',
quality: options.quality || 75
};
if (!options.buffer) {
filename = options.filename || ("" + (options.directory || '/tmp') + "/html-pdf-" + system.pid + "." + fileOptions.type);
page.render(filename, fileOptions);
system.stdout.write(filename);
} else {
system.stderr.write('html-pdf: options.buffer is deprecated. Because of compatibility issues this method is longer supported.\n');
page.render('/dev/stdout', fileOptions);
}
return exit(null);
};
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "html-pdf",
"version": "0.3.0",
"version": "0.4.0",
"description": "HTML to PDF converter that uses phantomjs",
"main": "lib/index.js",
"directories": {
Expand Down
Loading

0 comments on commit 3ea3cc3

Please sign in to comment.