【发布时间】:2018-03-18 02:25:07
【问题描述】:
我正在尝试使用节点 js 在服务器端生成 PDF,并在客户端以 Angular 4 下载它(当您按下下载为 PDF 时,就像 Google Drive 所做的那样)。
Node JS 代码如下所示:
var pdf = require('html-pdf');
app.get('/pdf/contacts', function(req, res) {
Contact.find(function(error, response) {
res.render('pdfs/views/contacts', {name: 'Daniel Pacuraru', contacts: response}, function(error, thtml) {
var opts = {
"format": "A4",
"orientation": "portrait",
"border": "0.4in"
};
pdf.create(thtml, opts).toStream(function(err, stream){
res.attachment('pdfname.pdf');
stream.pipe(res);
});
});
});
});
在 4 角边我得到了这样的东西:
import * as FileSaver from 'file-saver';
downloadContacts(): Promise<any> {
return this.http
.get('http://localhost:3000/pdf/contacts')
.toPromise()
.then(response => {
FileSaver.saveAs(response, "testdata.pdf");
});
}
我得到这个错误:Failed to execute 'createObjectURL' on 'URL' 如果我把这条线改成这个
FileSaver.saveAs(response.blob(), "testdata.pdf");
然后我得到这个错误:Error: The request body isn't either a blob or an array buffer
我不知道我在做什么错,顺便说一句,有没有一种方法可以轻松下载此流,而无需任何像文件保护程序这样的插件?因为如果我只是在浏览器上输入和 api 链接,它会自动下载我的 pdf 文件。
提前谢谢你,丹尼尔。
【问题讨论】:
标签: javascript node.js angular pdf