I have an ajax endpoint where I generate a pdf based off the user's GET
request, then send them back the pdf through a Buffer.
When I try to send them the buffer directly, the resulting downloaded pdf is corrupted, however, when I send them a base64 version then decode it on the client side it works properly.
AJAX endpoint:
module.exports = function(req, res) {
pdf.create('<h1>Title</h1>').toBuffer(function(err, buffer) {
res.setHeader('Content-Type', 'application/pdf');
res.send(buffer.toString('base64'));
});
};
Client:
$.get('/createPDF', (data) => {
var len = binary.length;
var buffer = new ArrayBuffer(len);
var view = new Uint8Array(buffer);
for (var i = 0; i < len; i++) {
view[i] = binary.charCodeAt(i);
}
const blob = new Blob([view], {type: "application/pdf"});
const url = window.URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'file.pdf');
document.body.appendChild(link);
link.click();
});
If I skip the toString('base64')
on the server and the part above the Blob
creation on the client it doesn't work, but if I include that it does. Does anyone know why this might be the case? Note I'm asking for this specific use-case of jquery's ajax.