title: API Gateway Response Download File using Node, PDFMake, Serverless
body: <p>I am in the process of migrating my NodeJS project to API Gateway and I cannot figure out how to download a file from Lambda.</p>
  
  <p>Here is a snippet of the response code on my local Node project.</p>
  
  <pre><code>app.get('/downloadPDF', function (req, res) {
    res.setHeader('Content-disposition', 'attachment; filename=test.pdf');
    res.setHeader('Content-type', 'application/pdf');
    var PdfPrinter = require('pdfmake');
    var printer = new PdfPrinter(fonts);
  
    var pdfDoc = printer.createPdfKitDocument(dd);
    pdfDoc.pipe(res);
    pdfDoc.end();
  });
  </code></pre>
  
  <p>Piping to the response I was able to get back a PDF.</p>
  
  <p>Here is a snippet of my lambda function using serverless.</p>
  
  <pre><code>module.exports.createPDF = (event, context) =&gt; {
    var PdfPrinter = require('pdfmake');
    var printer = new PdfPrinter(fonts);
  
    var pdfDoc = printer.createPdfKitDocument(dd);
    pdfDoc.pipe(res);
    pdfDoc.end();
  }
  </code></pre>
  
  <p>Here is the endpoint in my serverless.yml</p>
  
  <pre><code>createPDF:
  handler: functions.myFunction
  events:
    - http:
        path: services/getPDF
        method: get
        response:
          headers:
            Content-Type: "'application/pdf'"
            Content-disposition: "'attachment; filename=test.pdf'"
  </code></pre>
  
  <p>I don't know how to get reference to the response object in Lambda to pipe to. Is that possible? Is there another way?</p>
  
  <hr>
  
  <p><strong>Update</strong></p>
  
  <p>I ended up solving this issue by returning the base64 encoded PDF binary in a JSON response and decoding on the client.
  Note: using the base64 decoding in the response mapping template did not work.</p>
  
  <p>Sample code:</p>
  
  <pre><code>    var buffers = [];
  pdfDoc.on('data', buffers.push.bind(buffers));
  
  pdfDoc.on('end', function () {
      var bufCat = Buffer.concat(buffers);
  
      var pdfBase64 = bufCat.toString('base64');
  
  return cb(null, 
      {"statusCode": 200,
      "headers": {"Content-Type": "application/json"},
      "body": pdfBase64});
  });
  </code></pre>