Question

I am using wkhtmltopdf to generate pdfs in nodejs

Below is my sample code to generate pdf

var  wkhtmltopdf = require('wkhtmltopdf')
    , createWriteStream = require('fs').createWriteStream;

 var r =  wkhtmltopdf('http://www.google.com', { pageSize: 'letter' })
            .pipe(createWriteStream('C:/MYUSERNAME/demo.pdf'));

        r.on('close', function(){
            mycallback();
        });

The above code is generating corrupt pdfs. I could not figure out the issue. Although when I generate pdfs using command prompt it is generating correctly like when I use below code in windows command prompt

wkhtmltopdf http://www.google.com demo.pdf 

I get correct pdf generated,sadly when I try to generate pdf in node environment, it generates corrupt pdfs.

Incase it helps I'm using wkhtmltopdf 0.11.0 rc2

Thanks in advance.

Was it helpful?

Solution

wkhtmltopdf for node has a bug for windows, so you can write a new one.

Like this:

function wkhtmltopdf(input, pageSize) {
    var spawn = require('child_process').spawn;

    var html;

    var isUrl = /^(https?|file):\/\//.test(input);
    if (!isUrl) {
        html = input;
        input = '-';
    }

    var args = ['wkhtmltopdf', '--quiet', '--page-size', pageSize, input, '-']
    if (process.platform === 'win32') {
        var child = spawn(args[0], args.slice(1));
    } else {
        var child = spawn('/bin/sh', ['-c', args.join(' ') + ' | cat']);
    }

    if (!isUrl) {
        child.stdin.end(html);
    }

    return child.stdout;
}

// usage:

createWriteStream = require('fs').createWriteStream;

wkhtmltopdf('http://google.com/', 'letter')
    .pipe(createWriteStream('demo1.pdf'));

wkhtmltopdf('<body>hello world!</body>', 'letter')
    .pipe(createWriteStream('demo2.pdf'));

note: the param is now 'letter' not { pageSize: 'letter' }

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top