Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for multi-source input (Issue #33) #119

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,9 +66,21 @@ wkhtmltopdf('http://apple.com/', {
});
```

`wkhtmltopdf` is just a function, which you call with either a URL or an inline HTML string, and it returns
`wkhtmltopdf` is just a function, which you call with a URL, an inline HTML string or an Array of objects (see [Multi-Source-Input](#multi-source-input)), and it returns
a stream that you can read from or pipe to wherever you like (e.g. a file, or an HTTP response).

### Multi-Source-input

`wkhtmltopdf` supports the ability to construct a PDF from several source documents, and can even generate a table-of-contents based on an outline inferred from the source HTML structure. To combine several documents into a single PDF, pass an Array of objects as the first argument. Each element of the array represents a single source for the resulting PDF, and must be an object conforming to the following structure:

```
{
source: STRING, // URL to source. Omit for type 'toc'.
type: STRING, // 'page', 'toc' or 'cover'. Default: 'page'
options: {...} // Page-specific options using same format as global options. Default: {}
}
```

## Options

There are [many options](http://wkhtmltopdf.org/docs.html) available to
Expand Down
146 changes: 90 additions & 56 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,11 @@ var spawn = require('child_process').spawn;
var slang = require('slang');
var isStream = require('is-stream');

var globalArgs = ['collate', 'noCollate', 'cookieJar', 'copies', 'dpi', 'extendedHelp', 'grayscale', 'help', 'htmldoc', 'imageDpi', 'imageQuality', 'license', 'logLevel', 'lowquality',
'manpage', 'marginBottom', 'marginLeft', 'marginRight', 'marginTop', 'orientation', 'pageHeight', 'pageSize', 'pageWidth', 'noPdfCompression', 'quiet', 'readArgsFromStdin', 'readme',
'title', 'useXserver', 'version'];
var tocArgs = ['disableDottedLines', 'tocHeaderText', 'tocLevelIndentation', 'disableTocLinks', 'tocTextSizeShrink', 'xslStyleSheet'];

function quote(val) {
// escape and quote the value if it is a string and this isn't windows
if (typeof val === 'string' && process.platform !== 'win32') {
Expand All @@ -11,6 +16,37 @@ function quote(val) {
return val;
}

function generateArgument(key, val) {
var args = [];

if (key !== 'toc' && key !== 'cover' && key !== 'page') {
key = key.length === 1 ? '-' + key : '--' + slang.dasherize(key);
}

if (Array.isArray(val)) { // add repeatable args
val.forEach(function(valueStr) {
args.push(key);
if (Array.isArray(valueStr)) { // if repeatable args has key/value pair
valueStr.forEach(function(keyOrValueStr) {
args.push(quote(keyOrValueStr));
});
} else {
args.push(quote(valueStr));
}
});
} else { // add normal args
if (val !== false) {
args.push(key);
}

if (typeof val !== 'boolean') {
args.push(quote(val));
}
}

return args;
}

function wkhtmltopdf(input, options, callback) {
if (!options) {
options = {};
Expand All @@ -22,73 +58,71 @@ function wkhtmltopdf(input, options, callback) {
var output = options.output;
delete options.output;

// make sure the special keys are last
var extraKeys = [];
var keys = Object.keys(options).filter(function(key) {
if (key === 'toc' || key === 'cover' || key === 'page') {
extraKeys.push(key);
return false;
}

return true;
}).concat(extraKeys);

// make sure toc specific args appear after toc arg
if (keys.indexOf('toc') >= 0) {
var tocArgs = ['disableDottedLines', 'tocHeaderText', 'tocLevelIndentation', 'disableTocLinks', 'tocTextSizeShrink', 'xslStyleSheet'];
var myTocArgs = [];
keys = keys.filter(function(key){
if (tocArgs.find(function(tkey){ return tkey === key })) {
myTocArgs.push(key);
return false;
}
return true;
});
var spliceArgs = [keys.indexOf('toc')+1, 0].concat(myTocArgs);
Array.prototype.splice.apply(keys, spliceArgs);
}

var args = [wkhtmltopdf.command];
if (!options.debug) {
args.push('--quiet');
}
var isArray = Array.isArray(input);
// handle multi-page input
if (isArray) {
// add global options
Object.keys(options).forEach(function(key) {
if (globalArgs.indexOf(key) >= 0) {
args = args.concat(generateArgument(key, options[key]));
}
});

keys.forEach(function(key) {
var val = options[key];
if (key === 'ignore' || key === 'debug' || key === 'debugStdOut') { // skip adding the ignore/debug keys
return false;
}

if (key !== 'toc' && key !== 'cover' && key !== 'page') {
key = key.length === 1 ? '-' + key : '--' + slang.dasherize(key);
}

if (Array.isArray(val)) { // add repeatable args
val.forEach(function(valueStr) {
args.push(key);
if (Array.isArray(valueStr)) { // if repeatable args has key/value pair
valueStr.forEach(function(keyOrValueStr) {
args.push(quote(keyOrValueStr));
});
} else {
args.push(quote(valueStr));
// add pages/covers/toc and options
input.forEach(function(page) {
// add input for page
args = args.concat(generateArgument(page.type || 'page', quote(page.source) || true));
// add per-page options
var opts = page.options || {};
Object.keys(opts).forEach(function(key) {
if (globalArgs.indexOf(key) < 0) {
args = args.concat(generateArgument(key, opts[key]));
}
});
} else { // add normal args
if (val !== false) {
args.push(key);
});
} else {
// make sure the special keys are last
var extraKeys = [];
var keys = Object.keys(options).filter(function(key) {
if (key === 'toc' || key === 'cover' || key === 'page') {
extraKeys.push(key);
return false;
}

if (typeof val !== 'boolean') {
args.push(quote(val));
}
return true;
}).concat(extraKeys);

// make sure toc specific args appear after toc arg
if (keys.indexOf('toc') >= 0) {
var myTocArgs = [];
keys = keys.filter(function(key){
if (tocArgs.find(function(tkey){ return tkey === key })) {
myTocArgs.push(key);
return false;
}
return true;
});
var spliceArgs = [keys.indexOf('toc')+1, 0].concat(myTocArgs);
Array.prototype.splice.apply(keys, spliceArgs);
}
});

var isUrl = /^(https?|file):\/\//.test(input);
args.push(isUrl ? quote(input) : '-'); // stdin if HTML given directly
args.push(output ? quote(output) : '-'); // stdout if no output file
keys.forEach(function(key) {
if (key === 'ignore' || key === 'debug' || key === 'debugStdOut') { // skip adding the ignore/debug keys
return false;
}

args = args.concat(generateArgument(key, options[key]));
});

var isUrl = /^(https?|file):\/\//.test(input);
args.push(isUrl ? quote(input) : '-'); // stdin if HTML given directly
}

args.push(output ? quote(output) : '-'); // stdout if no output file
// show the command that is being run if debug opion is passed
if (options.debug && !(options instanceof Function)) {
console.log('[node-wkhtmltopdf] [debug] [command] ' + args.join(' '));
Expand Down Expand Up @@ -185,7 +219,7 @@ function wkhtmltopdf(input, options, callback) {
}

// write input to stdin if it isn't a url
if (!isUrl) {
if (!isUrl && !isArray) {
// Handle errors on the input stream (happens when command cannot run)
child.stdin.on('error', handleError);
if (isStream(input)) {
Expand Down
16 changes: 16 additions & 0 deletions spec/wkhtmltopdf.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -110,4 +110,20 @@ describe('wkhtmltopdf', function() {
});
});

describe('when input is an array', function() {
it('use the list of urls as inputs and concatenate the results into a single pdf', function(done) {
var output = Fs.createWriteStream(resultPath('arraySourceSpec.pdf'));
Wkhtmltopdf([
{source: fixtureFileUri('validFile.html'), options: {defaultHeader: true}},
{source: fixtureFileUri('validFile.html'), type: 'page'},
{source: fixtureFileUri('validFile.html'), type: 'cover'},
{type: 'toc', options: {defaultHeader: true}}
], {orientation: 'Landscape'}).pipe(output);
output.on('finish', function() {
checkResults('arraySourceSpec.pdf', 'validFile.pdf');
done();
})
});
});

});