'nodejs cant open pdf file after download

I am using nest js, I have converted html file and saved to pdf on my localhost when opening the pdf file from the save location it is fine, but when I am downloading I'm unable to open the file.

My api controller answers that the file is download successfully.

async exportPDF(@Res({ passthrough: true }) res: Response, @Body() dto: ExportReadingsPDFDto) {
    const stream = await this.metersService.exportPDF(dto);
    const filename = stream.replace(/^.*[\\\/]/, "");
    const fileReadStream = fs.createReadStream(stream, { encoding: "base64" });
    const stat = fs.statSync(stream);
    res.set({
        "Content-Type": "application/pdf",
        "Content-Length": stat.size,
        "Content-Disposition": 'attachment; filename="' + filename + '"'
    });

    fileReadStream.pipe(res);
}

Please help, I couldn't find any other example for creating pdf files and sending them to the user



Solution 1:[1]

You can simply create the PDF file within server, then using this piece of code you can download it as a response for the user.

const filename = '123.pdf';
res.setHeader('Content-disposition', 'attachment; filename=' + filename);
const filestream = createReadStream('files/' + filename);
filestream.pipe(res);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Yuval Moshe