5

I'm getting below response of axios call:

Click here to download response (PDF)

When I'm trying to generate PDF from above link response PDF generated with blank pages

var fs = require('fs');
fs.writeFileSync("12345678.pdf", response.data, 'binary');

axios call:

const url = 'url-here'

const headers = {
    'headers-here'
  };
const axiosConfig = {
    headers,
  };

axios.get(url, axiosConfig)
    .then((response) => {

     var fs = require('fs');
     fs.writeFileSync("12345678.pdf", response.data, 'binary'); 

     callback(null, response.data);
      })
      .catch((error) => {
        logger.error(error.stack || error.message || error);
        callback(error, null);
});

Can anyone please help me to generate correct PDF?

9
  • It looks like you should be streaming the axios response into a Buffer or writable stream. Alternatively, pipe your response into fs - github.com/axios/axios#axiosconfig Commented Mar 18, 2019 at 10:28
  • @ethane What should I do? Can you please suggest ? Commented Mar 18, 2019 at 10:29
  • Could you please add your axios request code to your question. Commented Mar 18, 2019 at 10:31
  • Sure, give me some time. Commented Mar 18, 2019 at 10:43
  • @ethane I've updated my question with axios request code. Commented Mar 18, 2019 at 12:56

1 Answer 1

11

The correct responseType value in the axios request config needs to be set to stream as well as pipeing the response into a writable stream.

axios({ 
  method:'get', 
  url: 'someUrl', 
  responseType: 'stream' // #1 
}) 
.then(function (response) { 
  response.data.pipe(fs.createWriteStream('12345678.pdf')) // #2
});
Sign up to request clarification or add additional context in comments.

1 Comment

This saved me a lot time. In my case I was getting the stream then sending it to another api for it to be uploaded. I didn't specify the responseType in the request, changed it to stream and it worked.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.