如何在nodejs + express中下载pdf?

时间:2019-05-03 13:27:35

标签: javascript node.js express

我正在尝试填充pdf,并且该pdf需要下载。但是我无法下载该pdf 我正在使用这个包裹

https://www.npmjs.com/package/node-pdftk

我从客户那里请求

获取请求

http://localhost:3000/api/joining-form/navasd.sharma@asda.com

export const sendGetRequest = (url, config = {}) => {
    return axios.get(url, config);
}

enter image description here

const buf = await pdftk
                .input('templates/joining-form.pdf')
                .fillForm(data)
                .flatten()
                .output()
            res.send(buf);

enter image description here

当前获得此输出

%PDF-1.6
%âãÏÓ
1 0 obj 
<<
/FormType 1
/Subtype /Form
/Resources 
<<
/Font 
<<
/Helv 2 0 R
>>
/ProcSet [/PDF /Text /ImageB /ImageC /ImageI]
>>
/Type /XObject
/BBox [0 0 362.4 28.8]
/Filter /FlateDecode
/Length 87
/Matrix [1 0 0 1 0 0]
>>
stream

1 个答案:

答案 0 :(得分:0)

在客户端,您可以基于请求响应创建可下载的链接,

尝试一下:

sendGetRequest(
  "http://localhost:3000/api/joining-form/navasd.sharma@asda.com",
  {
    responseType: "blob" // important
  }
).then(response => {
  const url = window.URL.createObjectURL(new Blob([response.data]));
  const link = document.createElement("a");
  link.href = url;
  link.setAttribute("download", "file.pdf");
  document.body.appendChild(link);
  link.click();
});