簡體   English   中英

如何將 pdf 文件從 Node/Express 應用程序發送到瀏覽器

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

在我的 Node/Express 應用程序中,我有以下代碼,假設從文件中讀取 PDF 文檔,並將其發送到瀏覽器:

var file = fs.createReadStream('./public/modules/datacollectors/output.pdf', 'binary');
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');
res.pipe(file, 'binary');
res.end(); 

我沒有收到任何錯誤,但我也沒有在瀏覽器中獲取該文件。 我究竟做錯了什么?

您必須通過管道從 Readable Stream 到 Writable 流,而不是相反:

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);

此外,您以錯誤的方式設置編碼,如果需要,請傳遞帶有編碼的對象。

我想我在使用 node js 在瀏覽器中顯示 PDF 文件的另一篇文章中找到了您的答案。

在 Chrome 中測試您的代碼后,它會立即開始下載 PDF 文件。 但是,如果您想顯示 PDF 文件的內容,您可以嘗試以下操作:

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

這應該直接將 PDF 內容發送到瀏覽器中。

希望這能回答你的問題。

這是最簡單的方法:

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

如果這給你帶來麻煩。 檢查 Express.js 版本或任何可能需要的中間件。

干杯

在 REST API 調用上下載 PDF 的最佳方式。

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");
       }    
});

如果您使用的是 Swagger/OpenAPI,那么您可以查看以下代碼的響應部分。 /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

我想如果你想在瀏覽器中顯示它很簡單將內容配置 header 更改為“內聯”而不是“附件;filename=quote.pdf”內聯直接在瀏覽器中顯示它而不是下載它,它對我來說很好用

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM