Pipe pdf to http response with PDFKIT and Strapi (Koa)

  javascript, koa, node.js, pdfkit, strapi

I just want to return a pdf in response to a GET Request at my Strapi endpoint.
Strapi uses Koa, and the Strapi controller atm look as follows:

const PDFDocument = require("pdfkit");
module.exports = {
   async printOne(ctx) {
      const doc = new PDFDocument();
      ctx.set("Content-Type", "application/pdf");
      // HTTP response
      doc.pipe(ctx.res); 
      // add stuff to PDF 
      doc.text("Hello world!");
      doc.info["Title"] = "Test Document";
      doc.info["Author"] = "Devon Govett";
      // finalize the PDF and end the stream
      doc.end();
   },
};

I think the problem is the doc.end() is closing the stream before the document is built.

Source: Ask Javascript Questions

LEAVE A COMMENT