Search code examples
node.jsstreamnode-pdfkit

PDFToolKit is sending weird data


I have installed PDFKit for node.js. When i call my method to download a PDF file, i get this kind of characers on my browser:

xœU»nÜ0ìùüËûâ’Œ+8Ò¹.H‘œOn|Eà¿ï!ï>  AÔ’”†ÃåÌŠ#áºa4Χð+ðÕ؇ýe£ªMfç)av

This is my code:

var doc = new PDFDocument({ layout: 'landscape' });
doc.pipe(res);
doc.moveDown(1);
doc.text(reportName, { align: "center" });
doc.text(bNames.join(','), { align: "center" });
doc.text(dateFrom + " - " + dateTo, { align: "center" });
doc.moveDown(2);
const table0 = {
   headers: allNames,
   rows: allData
};
doc.table(table0, {
   prepareHeader: () => doc.font('Helvetica-Bold').fontSize(10),
   prepareRow: (row, i) => doc.font('Helvetica').fontSize(10)
});
doc.end();

Is there something else i have to tell PDFKit to work right?

EDIT1:

I am running this code on my backend and sending it to my frontend so i can download it there


Solution

  • If you want a PDF response straight to the browser, you need to add the header so it understands the binary data.

    Set this before the response is piped.

    res.setHeader('Content-type', 'application/pdf')