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

Microsoft graph api 如何使用Microsoft Graph将Office文件转换为PDF,microsoft-graph-api,onedrive,Microsoft Graph Api,Onedrive,我正在寻找一种将Office文件转换为PDF的方法。 我发现可以使用Microsoft Graph 我正在尝试从OneDrive下载使用Microsoft Graph转换的PDF。 我想把.docx转换成.pdf 但是,当我发送以下请求时,即使等待,也没有收到响应 GET https://graph.microsoft.com/v1.0/users/{id}/drive/root:/test.docx:/content?format=pdf 此外,不会返回错误代码。 如果语法错误,将按预期返回

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

我正在尝试从OneDrive下载使用Microsoft Graph转换的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");
            :

API不会直接返回转换后的内容,而是返回到转换后的文件的链接。从:

返回一个
302 Found
响应,该响应重定向到已转换文件的预验证下载URL

要下载转换后的文件,您的应用程序必须遵循响应中的
位置
标题

预验证的URL仅在短时间(几分钟)内有效,并且不需要授权标头进行访问


您需要捕获
302
并第二次调用
位置
头中的URI,以便下载转换后的文件。

我想通过提供一些示例来详细说明一下

由于默认情况下,
HttpClient
的设置为
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); 
      }
}
如果禁用跟随HTTP重定向,则要下载转换的文件,应用程序必须跟随响应中的位置标头,如下所示:

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

谢谢你的帮助。结果,我的网络环境似乎不好。所以,我把它放在Azure上,它成功了。非常感谢。谢谢你的帮助。结果,我的网络环境似乎不好。所以,我把它放在Azure上,它成功了。我非常感激。