Rodrigo Moreno
Rodrigo Moreno

Reputation: 629

Create a PDF from HTML and send it to the user from a buffer

I'm trying to generate a PDF from an HTML file from the frontend and the users may download the PDF (never be stored on the server).

For this I am using the module: html5-to-pdf

My code is like this:

var pdf = require('html5-to-pdf');
var fs = require('fs');

router.post('/pdf', function(req, res) {
  var html = req.body.html;

  if (!html) {
    return res.sendStatus(400);
  }

  pdf().from.string(html).to.buffer({
    renderDelay: 1000
  }, function(err, data) {
    if (err) {
      return res.sendStatus(500);
    }

    var file = fs.createWriteStream('myDocument.pdf');
    file.write(data, function(err) {
      if (err) {
        res.sendStatus(500);
      }

      res.download('myDocument');
    });
  });

});

Whenever I download a file size of 0Bytes and also creates the file on the server

Someone could help me?

Upvotes: 0

Views: 1625

Answers (2)

Rodrigo Moreno
Rodrigo Moreno

Reputation: 629

The problem is that html5-to-pdf used phantom to generate the PDF, so it phantom deploys a little server at "localhost" and the port 0, the fact is that OpenShift not recognize "localhost"[1] and if instead of using "localhost" variable is used: process.env.OPENSHIFT_NODEJS_IP the application works correctly.

[1] https://github.com/amir20/phantomjs-node/tree/v1#use-it-in-restricted-enviroments

Upvotes: 0

trquoccuong
trquoccuong

Reputation: 2873

Maybe it send file before write finish

file.on('end',function(){
    res.download('myDocument');
})

Upvotes: 1

Related Questions