Search code examples
node.jsqr-codeexceljs

Read QR code as a buffer and save it in Excel


I am using below code to generate a QR code and save it in an Excel file. I am using using qrcode and exceljs libraries. The excel file is generated but doesn't have the expected QR code.

app.use('/api/qr/:content', async (req, res) => {
        try {
            const workbook = new ExcelJS.Workbook();
            const sheet = workbook.addWorksheet('Sheet 1');

            const content = req.params.content;
            const bufferImage = await QRCode.toDataURL(content, {
                type: 'image/png',
                width: 200,
            });
            const imageId2 = workbook.addImage({
                buffer: Buffer.from(bufferImage),
                extension: 'png'
            });

            sheet.addImage(imageId2, {
                tl: { col: 0, row: 0 },
                ext: { width: 200, height: 200 }
            });

            await workbook.xlsx.writeFile('ExcelFile.xlsx');
            return res.send({ data: 'ok' });
        } catch (err) {
            console.error('Failed to return content', err);
        }
    });

So the idea is to generate the QR code in buffer and add it in excel file as an image.


Solution

  • Solved it. Had to change the QR reading method from DataURL to toBuffer.

    const content = req.params.content;
                const bufferImage = await QRCode.toBuffer(content, {
                    type: 'png',
                    errorCorrectionLevel: 'H',
                });
    
                const imageId2 = workbook.addImage({
                    buffer: bufferImage,
                    extension: 'png'
                });