【问题标题】:How to save a PDF from an REST API call如何从 REST API 调用中保存 PDF
【发布时间】:2021-03-17 09:11:24
【问题描述】:

我正在通过 axios 向服务器发送请求。作为回应,我从服务器获取此代码。我认为这是缓冲区类型的东西。对此一无所知。

%PDF-1.3\n' +
'%����\n' +
'1 0 obj\n' +
'<<\n' +
'    /CreationDate (D:20201204055104Z)\n' +
'    /ModDate (D:20201204055104Z)\n' +
'>>\n' +
'endobj\n' +
'2 0 obj\n' +

我想将此回复保存为 pdf 格式。我已经尝试过这段代码,但它只会生成空白的 pdf 文件。 这是我的代码

const url = "https://api-stage-starfleet.delhivery.com/package/DL000246845CN/shipping-label";
// Headers config
const config = {
    headers: {
        'Accept': 'application/pdf',
        'id_token': id_token,
        'Authorization': auth_token,
    }
}
axios.get(url, config)
    .then((response) => {
        fs.writeFile("output.pdf", response.data, function (err) {
            if (err) {
                return console.log(err);
            }
            console.log("The file was saved!");
        });

    })
    .catch((err) => {
        console.log(err);
    })

我也尝试在标头对象中添加编码。但它不起作用,只生成空白 pdf。谁能帮我解决这个问题。

【问题讨论】:

    标签: node.js pdf axios pdf-generation


    【解决方案1】:

    默认情况下,axios 将使用字符串作为其响应类型。为了告诉它使用二进制数据,你传递一个名为responseType的配置:

    const config = {
        headers: {
            'Accept': 'application/pdf',
            'id_token': id_token,
            'Authorization': auth_token,
        },
        responseType: 'buffer'; // <-- Here -----
    }
    

    然后,您的 writeFile 将起作用,但请注意,将来自 axios 的响应通过管道传输到文件要高效得多:

    axios({
        method: "get",
        headers: {
            'Accept': 'application/pdf',
            'id_token': id_token,
            'Authorization': auth_token,
        },
        responseType: "stream"
    }).then(function (response) {
        response.data.pipe(fs.createWriteStream("output.pdf"));
    });
    

    【讨论】:

      猜你喜欢
      • 2021-07-28
      • 2023-03-21
      • 1970-01-01
      • 2017-10-11
      • 2017-04-27
      • 2021-08-24
      • 1970-01-01
      • 2016-11-14
      • 1970-01-01
      相关资源
      最近更新 更多