Carlos Palacios
Carlos Palacios

Reputation: 25

Render PDF in React and sending it to Laravel API

So my problem here is that I'm rendering PDF inside a react component using html2canvas and pdfmake.js. After rendering it I decide if it will be downloaded or open in a new tab or sending it via email (using static email). If the user wants to use the third option I need to send the pdf to the email he desires.

The idea is that when the user clicks on the button send by email an axios instance will tell my Laravel API to use the pdf and send it to de desired person. My problem is that I can't seem to pass the generated pdf or the html (lack of css) to the Laravel API for sending it.

This is the function that is binded to the button event click.

createPDF = action => {
    html2canvas(document.getElementById('exportthis'),
    {
        width: 816, 
        height: 956, 
        logging: false
    })
    .then(async canvas => {
        const docDefinition = {
            content: [
                { image: canvas.toDataURL() , fit: [700, 700] },
            ],
            pageSize: 'A4',
            pageMargins: [10, 10, 10, 10]
        };

        switch(action) {
            case 'download':
                pdfMake.createPdf(docDefinition).download(`folio_${this.props.sale ? this.props.sale.document.series.folio : ''}`);
                break;
            case 'print':
                pdfMake.createPdf(docDefinition).print();
                break;
            default:
                // create axios for sending dataURL
                const res = await axios.post('/email-invoice', {
                    data: canvas.toDataURL(),
                    name: `folio_${this.props.sale ? this.props.sale.document.series.folio : ''}`,
                    user: '[email protected]'
                }, {
                    headers: {
                        'Authorization': `Bearer ${this.props.token}`
                    }
                });

                console.log(res);
        }
    });
 }

So for my question, do I need to change the logic and create a PDF in Laravel and send it back to my React frontend or is there a way to pass the pdf generated in React to Laravel and then sending it to the person.

Upvotes: 1

Views: 1662

Answers (1)

Leonardo Lobato
Leonardo Lobato

Reputation: 1097

The usual approach is create the pdf in Laravel and then send it.

You have to take in consideration that some operations can be very demanding for a mobile phone for example if you let this logic on the client.

So I advise you to put this logic on the server side. It's easier, faster and more secure.

Upvotes: 3

Related Questions