node.jspdfkitfastify

Piping a pdfkit PDF to Fastify


From what I've read, his should work. But it just downloads an empty document. So I must be handling the pipe incorrectly.

It works fine if I pipe it to fs.createWriteStream instead...

import PDFDocument from 'pdfkit'

const downloadPdfRoute = async (app) => {
    app.get('/download/:filename', async (req, reply) => {

        const doc = new PDFDocument()

        reply.type('application/pdf')
        reply.header(
            'content-disposition',
            `attachment; filename="${req.params.filename}"`
        )

        doc.pipe(reply.raw)

        doc.text('Hello, this is your PDF content.')

        doc.end()
    })
}

export default downloadPdfRoute

What am I doing wrong?


Solution

  • Update: After further investigation by OP, it turned out that the return keyword was required for this to work, hence I updated my answer to include that.


    Fastify also supports sending a stream like this:

    return reply.send(doc);
    

    So you should try doing that instead of doc.pipe(reply.raw); which is not recommended because of the .raw usage:

    [...] the use of Reply.raw functions is at your own risk as you are skipping all the Fastify logic of handling the HTTP response.

    Your original code works for me just fine BTW, so maybe you should try extracting your code in a fresh environment to see if you can reproduce this.