如何从api-endpoint在浏览器中显示express/pdfkit生成的PDF



我使用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();
})

我的前端使用value接收响应

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↵<...

window.open(…)打开空白标签页。

我发现了类似的问题,但找不到答案。我可能在理解上有些问题,希望你能给我点提示。谢谢。

在您的快递应用程序:res.setHeader('Content-Type', 'application/pdf');

在你的前端只需要打开链接"手动"如点击锚点:<a href="{url to pdf}" target="_blank">click me</a>

如果你的浏览器支持,pdf应该在一个新的选项卡中打开,否则它将被下载。

编辑:澄清:window.open期望url作为第一个参数,而不是pdf的内容。

最新更新