Node.js pdfkit download issue, file gets downloaded after showing error

35 Views Asked by At
router.get('/generate-profile-doc/:id', async (req, res, next) => {
    try {
        const characterId = parseInt(req.params.id);
        const character = await rickAndMortyService.getCharacter(characterId);
        
        if (!character) {
            return res.status(404).json({ error: 'Character not found' });
        }

        const pdfDirectory = path.join(process.cwd(), 'public/pdfs');

        const doc = new PDFDocument();
        const fileName = `${character.id}_profile.pdf`;

        const filePath = path.join(pdfDirectory, fileName);
        // Pipe the PDF content to a writable stream (in this case, a file)
        doc.pipe(fs.createWriteStream(filePath));

        // Add content to the PDF
        doc.fontSize(14).text('Character Profile', { align: 'center' });
        doc.fontSize(12).text(`Name: ${character.name}`);
        doc.text(`Status: ${character.status}`);
        doc.text(`Species: ${character.species}`);

        // End the PDF document
        doc.end();

        // Set the response headers for the download
        res.setHeader('Content-Type', 'application/pdf');
        res.setHeader('Content-Disposition', `attachment; filename=${character.name}`);

        // Send the PDF file to the client for download
        res.sendFile(filePath);
    } catch (error) {
        next(error);     
    }
});

Above route gets called when clicked on download PDF button. I am getting This site can’t be reached - ERR_INVALID_RESPONSE But soon after showing this error page file gets downloaded.

Can anyone help me on this? I am new to node. What am i doing wrong?

I am using following lib, const PDFDocument = require('pdfkit'); const fs = require('fs'); const path = require('path');

0

There are 0 best solutions below