如何使用Microsoft Graph将Office文件转换为PDF

时间:2018-10-03 05:50:02

标签: microsoft-graph onedrive

我正在寻找一种将Office文件转换为PDF的方法。 我发现可以使用Microsoft Graph。

我正在尝试使用Microsoft Graph从OneDrive下载转换后的PDF。 我想将.docx转换为.pdf。

但是,当我发送以下请求时,即使等待也没有收到回复。

GET https://graph.microsoft.com/v1.0/users/{id}/drive/root:/test.docx:/content?format=pdf

此外,不会返回错误代码。 如果语法错误,将按预期返回错误代码。 它只会在正确时才返回。

此外,如果不进行转换,我可以下载文件。

GET https://graph.microsoft.com/v1.0/users/{id}/drive/root:/test.docx:/content

我的方法是否错误或是否需要条件? 如果可能的话,请给我您可以实际使用的示例代码。

 using (HttpClient client = new HttpClient())
        {
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken);
            client.BaseAddress = new Uri(graphUrl);

            var result = await client.GetAsync("/v1.0/users/xxxxxxxxxxxxxxxxxxxxxxxxx/drive/root:/test.docx:/content?format=pdf");
            :

2 个答案:

答案 0 :(得分:1)

API不会直接返回转换后的内容,而是会返回指向转换后文件的链接。来自documentation

  

返回302 Found响应,重定向到已转换文件的预先认证的下载URL。

     

要下载转换后的文件,您的应用必须遵循响应中的Location标头。

     

预先认证的URL仅在短时间内(几分钟)有效,不需要访问Authorization标头。

您需要捕获302并在Location标头中对URI进行第二次调用才能下载转换后的文件。

答案 1 :(得分:1)

我想通过提供Marc's answer的一些示例来详细说明HttpClient

由于HttpClient HttpClientHandler.AllowAutoRedirect property的默认 设置为True,因此无需显式遵循HTTP重定向标头,并且可以像这样下载内容:

using (HttpClient client = new HttpClient())
{
     client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
     client.BaseAddress = new Uri("https://graph.microsoft.com");

     var response = await client.GetAsync($"/v1.0/drives/{driveId}/root:/{filePath}:/content?format=pdf");

      //save content into file 
      using (var file = System.IO.File.Create(fileName))
      { 
           var stream = await response.Content.ReadAsStreamAsync(); 
           await stream.CopyToAsync(file); 
      }
}

如果禁用了 ,则要下载转换后的文件,您的应用必须遵循响应中的Location标头,如下所示:

var handler = new HttpClientHandler()
{
    AllowAutoRedirect = false
};

using (HttpClient client = new HttpClient(handler))
{
     client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
     client.BaseAddress = new Uri("https://graph.microsoft.com");

     var response = await client.GetAsync($"/v1.0/drives/{driveId}/root:/{filePath}:/content?format=pdf");
     if(response.StatusCode == HttpStatusCode.Redirect)
     {
           response = await client.GetAsync(response.Headers.Location); //get the actual content
     }

      //save content into file 
      using (var file = System.IO.File.Create(fileName))
      { 
           var stream = await response.Content.ReadAsStreamAsync(); 
           await stream.CopyToAsync(file); 
      }
}
相关问题