Home > Enterprise >  How to get the rendered view as a string in express.js?
How to get the rendered view as a string in express.js?

Time:03-15

I want to store the rendered view res.render as string to a variable and use node-html-pdf package to print pdf:

var pdf = require('html-pdf');
var html = res.render('my_view', res.view_data); // not work

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

CodePudding user response:

You'll need the app instance of express application.

var appInstance = express();
appInstance.set('views', path.join(__dirname, 'views')); // Set this relative to your file
appInstance.set('view engine', 'pug'); // Or whatever your view engine is

appInstance.render("my_view", view_data, (err, html) => {

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

});
  • Related