简体   繁体   中英

SailsJs - Export html view to PDF

I need to export a HTML view to a PDF. I already have my view working and I want to create another link to generate a PDF version from this view. I'm trying to use http.get to download the HTML file but it's not working. Here's the code:

var http = require('http');
var fs = require('fs');
var file = fs.createWriteStream("files/" + filename);

var fullUrl = req.protocol + '://' + req.get('host') + 'PATH/TO/MY/VIEW?id=' + id;

var request = http.get(fullUrl, function(response){
    response.pipe(file);    
});

The written file just outputs:

Found. Redirecting to /<default_pattern>

Instead of downloading you could use a html to pdf converter like wkhtmltopdf . Converting a view to pdf is simple as:

res.render('ticket/pdf', {
    'title': 'Ticket #1',
}, function(err, html) {
    if (err) {
        return res.negotiate(err);
    }
    res.setHeader('Content-disposition', 'attachment; filename=myFile.pdf';
    return require('wkhtmltopdf')(html).pipe(res);
});

The converter has to be installed on your system, refer to http://wkhtmltopdf.org/

If you still like to download a view, do the following:

wkhtmltopdf('http://google.com/', { pageSize: 'letter' })
  .pipe(fs.createWriteStream('out.pdf'));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM