Currently facing an issue while attempting to generate a PDF within a Lambda function using the .pipe()
function from PDF Kit. The downloaded PDF appears blank, although I have managed to display content by converting the PDF to a base64 string. However, this method may not be sustainable as the PDF size and number of requests increase.
I aim to utilize .pipe()
as suggested in various guides. Below is the code snippet that produces a blank PDF. I have tried setting both responseType: 'blob'
and responseType: arraybuffer
on my client side, but both result in empty files being opened.
let pdf = new PDFDocument();
pdf.text("hello world", 50, 50);
res.setHeader("Content-Type", "application/pdf");
res.setHeader(
"Content-Disposition",
`attachment; filename=test.pdf`
);
res.status(200);
pdf.pipe(res);
pdf.end();
Although this method successfully downloads a PDF with the text "hello world," it is not practical due to performance and memory constraints.
let chunks = [];
let pdf = new PDFDocument();
pdf.text("hello world", 50, 50);
pdf.on("data", data => {
chunks.push(data);
});
pdf.on("end", () => {
res.setHeader("Content-Type", "application/pdf");
res.setHeader(
"Content-Disposition",
`attachment; filename=test.pdf`
);
res.status(200);
const result = Buffer.concat(chunks);
res.send(
"data:application/pdf;base64," + result.toString("base64")
);
});
pdf.end();
Upon inspecting the contents of both PDF files generated using the above approaches, it was noticed that the actual content differed significantly. This distinction was also observed in the raw response logged in Chrome. While I won't provide the entire file contents here, the following snippets highlight the disparity:
Blank PDF
stream
xe;
0=Żg )-*7na'cpFǦ<yԛ_[d1>zӰ1Cͻa} .dJ,ptU*
endstream
Working PDF
stream
xœeŒ;
€0û=Å»€šÍg£ )-ì„íÄ*ÎÂû7na'ÃcŠÇpFǦ<yÔ›â_[ô‹Œd1„>ŒzÓ°1ØC³Œ’¤Í»œØa––±«d³J,pt§Ué ÝÎ*
endstream
While I am not well-versed in encoding, it is apparent that there are differences in how the two files are encoded, indicating a potential oversight in setting configurations in Express.