javascriptnode.jsaxiosmicrosoft-graph-apimicrosoft-graph-files

How to receive a converted file from microsoft graph api


I'm having a problem saving a pdf I am receiving from microsoft graph api. I am making the following call using the configuration I construct:

const convertConfig = {
    headers: {
        Authorization: <my token>
    }
};
convertConfig.headers['Content-Type'] = 'application/pdf';
const convertRes = await axios.get(`https://graph.microsoft.com/v1.0/<myTenantId>/sites/<mySite>/drive/root:/<myPath>:/content?format=pdf`, convertConfig);
{
  status: 200,
  statusText: 'OK',
   
  ... // snipped data 

  data: <pdf data here as a string in the form 
    '%PDF-1.7\r\n' +
    '%����\r\n' +
    '1 0 obj\r\n' +...>
}

However, when manually saving this file or uploading it, the pdf ends up blank but with the proper amount of pages. For instance, I can save it like so:

fs.writeFileSync('some.pdf', convertRes.data);

and the resulting pdf saved is just blank white pages.

Here's my main question, somewhere I am misusing this data or not asking for something properly because when I make the request using postman the response actually has the content!

params headers

Is there something I am not including in the call or something I'm not doing to the data to handle it properly as pdf data?


Solution

  • The response that you get is a stream which you can pipe to the file system. Here is how to do it using Axios.

    const writer = fs.createWriteStream('file.pdf');
    
    axios({
        method: 'get',
        url: 'https://graph.microsoft.com/v1.0/sites/site-id/drive/root:/file.docx:/content?format=pdf',
        responseType: 'stream',
        headers: {
            Authorization: "eyJ0..."
        }
    }).then(response => {
        response.data.pipe(writer);
    });