Last active
April 12, 2024 21:05
-
-
Save augustovicente/6ae979818f06f9739c378f7c05ee2673 to your computer and use it in GitHub Desktop.
Adonis.js send pdf from buffer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
I did create a solution so you can generate a pdf, without saving the file, and send it as response. | |
The problem was that adonis.js does not support pipe the pdf into response and send as an attachment. | |
*/ | |
// you have to download the dependencies | |
import blobStream from 'blob-stream'; | |
import PDFDocument from 'pdfkit'; | |
// put it inside controller function | |
const return_pdf = new Promise((resolve) => | |
{ | |
const doc = new PDFDocument(); | |
const buffers = []; | |
doc.on('data', buffers.push.bind(buffers)); | |
const the_stream = doc.pipe(blobStream()); | |
// create elements | |
doc.text('test'); | |
doc.end(); | |
the_stream.on('finish', () => | |
{ | |
let pdfData = Buffer.concat(buffers); | |
response.header('Content-type', 'application/pdf'); | |
response.header('Content-Length', pdfData.length); | |
response.header( | |
'Content-disposition', | |
'attachment; filename=test.pdf' | |
); | |
response.send(pdfData); | |
resolve(true); | |
}); | |
}); | |
await return_pdf; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment