问题描述
我使用 express 和 pdfkit 生成了一个 pdf,例如:
router.get("/create_pdf",(req,res) => {
var foo = req.body.foo;
var bar = req.body.bar;
// query Postgres with foo and bar to get some custom values
//create pdf
const doc = new PDFDocument();
doc.pipe(res);
doc.fontSize(25).text("Just a header",100,80);
// build some more stuff depending of Postgres query
doc.end();
})
我使用 vue 的前端收到响应
print: function() {
data = {foo: "foo",bar: "bar"};
this.axios({
method: "get",url: "get_recipe_as_pdf",data: data,})
.then((response) => {
console.log(response);
window.open(response.data);
})
.catch(() => {
//some error
});
},
控制台显示 data: "%PDF-1.3↵%����↵7 0 obj↵<...
我发现了类似的问题,但找不到答案。我可能有一些理解问题,所以我很感激提示。谢谢。
解决方法
在您的 Express 应用中:res.setHeader('Content-Type','application/pdf');
在您的前端,只需像点击锚点一样“手动”打开链接:<a href="{url to pdf}" target="_blank">click me</a>
如果您的浏览器支持,pdf 应该在新选项卡中打开,否则将被下载。
编辑:澄清:window.open
需要一个 url 作为第一个参数,而不是 pdf 的内容。