Node js, piping pdfkit to a memory stream

后端 未结 5 1571
谎友^
谎友^ 2021-02-07 21:07

I am using pdfkit (https://github.com/devongovett/pdfkit) on my node server, typically creating pdf files, and then uploading them to s3. The problem is that pdfkit examples pip

5条回答
  •  遇见更好的自我
    2021-02-07 21:58

    An updated answer for 2020. There is no need to introduce a new memory stream because "PDFDocument instances are readable Node streams".

    You can use the get-stream package to make it easy to wait for the document to finish before passing the result back to your caller. https://www.npmjs.com/package/get-stream

    const PDFDocument = require('pdfkit')
    const getStream = require('get-stream')
    
    const pdf = () => {
      const doc = new PDFDocument()
      doc.text('Hello, World!')
      doc.end()
      return await getStream.buffer(doc)
    }
    
    
    // Caller could do this:
    const pdfBuffer = await pdf()
    const pdfBase64string = pdfBuffer.toString('base64')
    

    You don't have to return a buffer if your needs are different. The get-stream readme offers other examples.

提交回复
热议问题