Search code examples
node.jspdfaxiospdf-generation

How to save a PDF from an REST API call


I am sending a request to a server via axios. In response I get this code from server. I think it is buffer type thing. Dont't know anything about it.

%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' +

I want to save this response in pdf format. I have tried this code but it will only generate blank pdf file. Here is my code

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);
    })

I have also tried by adding encoding in header object. But it is not working and only generating blank pdf. Can anyone help me on this.


Solution

  • By default, axios will use strings for its response types. In order to tell it to use binary data instead you pass a configuration called responseType:

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

    Then, your writeFile would work, though note it's far more efficient to just pipe the response from axios to the file:

    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"));
    });