Displaying PDF (created in python) on the WEB with nodejs

Asked

Viewed 19 times

1

I have a python script that generates a PDF file according to the information provided. I created an application in nodejs so that with each POST request, the script runs generating a new PDF file. The file is saved inside the "public" folder and as a response, the request returns this PDF file. This file is displayed on an HTML page where it is possible to provide the necessary information for PDF generation.

NODE JS

router.post('/', (req, res) => {
    var data = req.body;
    console.log(data)
    const python = spawn('python3', ['public/python/pdf.py', data.nSchool, data.nSubject, data.nProf, data.nQue]);

    python.on('close', (code) => {
         console.log(`${code}`);

        var file = fs.createReadStream("./public/pdf/gab.pdf");
        res.contentType('application/pdf')
        file.pipe(res);
    });
});

JAVASCRIPT

document.querySelector('#submit').onclick = function(){
    fetch('/makepdf', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            nSchool: document.querySelector('#nSchool').value,
            nSubject: document.querySelector('#nSubject').value,
            nProf: document.querySelector('#nProf').value,
            nQue: document.querySelector('#nQue').value
        })
    }).then(function(res) {
        res.blob().then(function(resq){
            var fileURL = URL.createObjectURL(resq)
            document.querySelector('#img').src = fileURL
        });
    });
}

The application works perfectly while running locally, but when it is hosted, the PDF file is not displayed.

Where’s the problem? In file generation? (maybe the server isn’t running the python script correctly) Or in file saving? (Being a static folder is not possible to solve the problem in the way I imagined?)

What would be the most efficient way to create such an application?

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.