Skip to content

Instantly share code, notes, and snippets.

@augustovicente
Last active April 12, 2024 21:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save augustovicente/6ae979818f06f9739c378f7c05ee2673 to your computer and use it in GitHub Desktop.
Save augustovicente/6ae979818f06f9739c378f7c05ee2673 to your computer and use it in GitHub Desktop.
Adonis.js send pdf from buffer
/*
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