How to send a pdf file from Node/Express app to the browser

后端 未结 5 2039
悲&欢浪女
悲&欢浪女 2020-12-06 00:06

In my Node/Express app I have the following code, which suppose to read a PDF document from a file, and send it to the browser:

var file = fs.createReadStrea         


        
相关标签:
5条回答
  • 2020-12-06 00:39

    If you are using the Swagger/OpenAPI then you can look in responses section of below code. /api/pdf_from_html: post: tags: - PDF description: Create PDF from html produces: - application/pdf consumes: - application/json parameters: - name: contents description: HTML content to convert to pdf in: body required: true schema: $ref: "#/definitions/pdf" responses: 200: description: Returns a PDF encoded in base64 content: application/pdf: schema: type: string format: base64

    0 讨论(0)
  • 2020-12-06 00:42

    I think I found your answer in another post Display PDF file in a browser using node js.

    After testing your code in Chrome, it immediately starts the download of the PDF file. But if you want to display the content of the PDF file you could try below:

    var data =fs.readFileSync('./public/modules/datacollectors/output.pdf');
    res.contentType("application/pdf");
    res.send(data);
    

    This should directly send PDF content into the browser.

    Hope this answers your question.

    0 讨论(0)
  • 2020-12-06 00:44

    Best way to download a PDF on REST API call.

    var path = require('path');     
    var file = path.join(__dirname, 'file.pdf');    
    res.download(file, function (err) {
           if (err) {
               console.log("Error");
               console.log(err);
           } else {
               console.log("Success");
           }    
    });
    
    0 讨论(0)
  • 2020-12-06 00:54

    Here's the easiest way:

    app.get('/', (req, res) => res.download('./file.pdf'))
    

    If this gives you trouble. Check the Express.js version or any middlewares that might be necessary.

    Cheers

    0 讨论(0)
  • 2020-12-06 00:56

    You have to pipe from Readable Stream to Writable stream not the other way around:

    var file = fs.createReadStream('./public/modules/datacollectors/output.pdf');
    var stat = fs.statSync('./public/modules/datacollectors/output.pdf');
    res.setHeader('Content-Length', stat.size);
    res.setHeader('Content-Type', 'application/pdf');
    res.setHeader('Content-Disposition', 'attachment; filename=quote.pdf');
    file.pipe(res);
    

    Also you are setting encoding in wrong way, pass an object with encoding if needed.

    0 讨论(0)
提交回复
热议问题