Node.js: serving dynamic pdf, coming up empty Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Node.js: serving dynamic pdf, coming up empty without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I have a node service that fetches a pdf from an API and serves that pdf.

When I curl or directly open the API, I do see the correct pdf.

But when I serve it from my Node app, I get an empty pdf.

Here’s the section of my code that does the pdf render.

} else if (options.type === 'pdf') {
  res.writeHead(200, {'content-type' : 'application/pdf', 'content-disposition': 'attachment; filename=invoice.pdf'});

I’ve console.log’ed data.invoice to know it’s the right stuff.

typeof(data.invoice) gives string; but I’ve also tried res.end(new Buffer(data.invoice)); which didn’t work either.

Here’s the section of my code that fetches the data

var http_options = {
  method : options.method
, host :
, path : options.path
, port : Config.API.port
, headers : options.headers

var req = http.request(http_options, function (response) {
  var raw_response = "";

  response.on('data', function (response_data) {
    raw_response += response_data.toString();

  response.on('end', function () {
    if (response.statusCode !== 200) {
    } else {
      cb(false, raw_response);

req.setTimeout(timeout, function () {
  cb("API connection timed out");

req.on('error', function (error) {
  cb("API error while requesting for " + options.path + 'n' + error + 'n' + "http   options: " + JSON.stringify(http_options)



It’s quite likely that the toString() and concatenation when you’re receiving the PDF are corrupting it. Try writing raw_response to a file (you can use writeFileSync() since this is just a one-time test) and doing a byte-for-byte comparison with the same PDF retrieved with curl.

Note that if the process of string conversion has corrupted it, trying to convert it back to a buffer before sending it won’t help. You’ll have to keep the whole thing as a buffer from start to finish.

We are here to answer your question about Node.js: serving dynamic pdf, coming up empty - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji