Generate PDF in NodeJS and open in React with react-pdf

Viewed 1003

I'm generating a PDF file using html-pdf-node in my NodeJS backend.

exports.generatePDF = async (req, res, next) => {
    const data = req.body || req.body.data;
    const content = data.html;
    let options = { 
        format: 'letter',
        margin: {
            right: '40px',
            left: '40px'
        } 
    };
    let file = { content };
    html_to_pdf.generatePdf(file, options).then(pdfBuffer => {
        res.setHeader('Content-Length', pdfBuffer.length);
        res.setHeader('Content-Type', 'application/pdf');
        return res.end(pdfBuffer);
    });
}

Then, I'm trying to open the generated PDF in React using react-pdf.

import React, { useState, useEffect } from 'react';
import { Document } from 'react-pdf';
import * as helperAPI from '../../api/Helper'; // This is just a helper for the axios request to NodeJS

const PDFViewer = (props) => {
    //const html = props.html;
    const html = "<html><body><div><p>This is a Test</p></div></body></html>";

    const [ pdfLink, setPDFLink ] = useState(null);

    useEffect(() => {
        async function fetchData() {
            const res = await helperAPI.generatePDF({html});
            const file = new Blob(
                [res], 
                {type: 'application/pdf'}
            );
            const fileURL = URL.createObjectURL(file);
            setPDFLink(fileURL);
        }
        fetchData();
    }, [html]);

    const onDocumentLoadSuccess = () => {
        console.log('onLoad');
        console.log(pdfLink);
    }
        console.log('Link: ' + pdfLink);
    return (
        <div>
            <Document
                file={{
                    url: pdfLink,
                }}
                onLoadSuccess={onDocumentLoadSuccess}
            /> 
        </div>
    );
}

export default PDFViewer;

The axios request inside the helperAPI:

import axios from 'axios';
import * as url from '../Constants/Custom';

export const generatePDF = async (data) => {
    let output = "";
    await axios.post(`${url.REQ_URL}/helper/generatePDF`, data)
        .then((res) => {
            output = res.data;
        });
    return output;
};

When I run the code, the browser returns: Failed to load PDF file. How can I load a blob generated file from NodeJS in react-pdf?

0 Answers
Related