如何使用NodeJS下载pdf并发送给客户端?

我正尝试使用NodeJS下载PDF文件,然后将其数据发送到客户端以embedded到页面中。 下面是我如何下载PDF文件:

exports.sendPdf = function(req, responce) { var donneRecu = req.body; var url = 'http://www.ieee.org/documents/ieeecopyrightform.pdf'//pdf link http.get(url, function(res) { var data = ''; res.on('data', function(chunk) { console.log('downloading'); data += chunk; }); res.on("end", function() { console.log('downloaded'); responce.header("Access-Control-Allow-Origin", "*"); responce.header("Access-Control-Allow-Headers", "X-Requested-With"); responce.header(200, {'content-type' : 'application/pdf'}); responce.send(data); }); }).on("error", function() { callback(null); }); } 

如何将从NodeJS收到的数据发送到客户端?

编辑我发现解决scheme:

 exports.sendPdf = function(req, res) { var donneRecu = req.body; console.log(donneRecu['lien']); var url = donneRecu['lien']; //pdf link http.get(url, function(response) { var chunks = []; response.on('data', function(chunk) { console.log('downloading'); chunks.push(chunk); }); response.on("end", function() { console.log('downloaded'); var jsfile = new Buffer.concat(chunks).toString('base64'); console.log('converted to base64'); res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "X-Requested-With"); res.header('content-type', 'application/pdf'); res.send(jsfile); }); }).on("error", function() { callback(null); }); } 

接下来在我的angular度控制器:

 var pdf = $scope.base64ToUint8Array(data); PDFJS.getDocument(pdf).then(functiongetPdfHelloWorld(_pdfDoc) { $scope.pdfDoc = _pdfDoc;$scope.renderPage($scope.pageNum); }); 

       

网上收集的解决方案 "如何使用NodeJS下载pdf并发送给客户端?"

我find了解决办法:

 exports.sendPdf = function(req, res) { var donneRecu = req.body; console.log(donneRecu['lien']); var url = donneRecu['lien']; //pdf link http.get(url, function(response) { var chunks = []; response.on('data', function(chunk) { console.log('downloading'); chunks.push(chunk); }); response.on("end", function() { console.log('downloaded'); var jsfile = new Buffer.concat(chunks).toString('base64'); console.log('converted to base64'); res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "X-Requested-With"); res.header('content-type', 'application/pdf'); res.send(jsfile); }); }).on("error", function() { callback(null); }); } 

接下来在我的angular度控制器:

 var pdf = $scope.base64ToUint8Array(data); PDFJS.getDocument(pdf).then(functiongetPdfHelloWorld(_pdfDoc) { $scope.pdfDoc = _pdfDoc;$scope.renderPage($scope.pageNum); }); 

我也面临同样的情况,下面的代码帮助了我。

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

希望能帮助到你。