How to convert the RTF to PDF using Microsoft Graph API

Mohan M A 11 Reputation points
2023-11-08T19:06:40.88+00:00

Hi there,

I am trying to convert a RTF document to PDF file using Microsoft Graph API.

I followed the steps in below documentation. I couldn't be able to convert the document to PDF.

https://techcommunity.microsoft.com/t5/microsoft-sharepoint-blog/using-microsoft-graph-api-to-convert-the-format-of-your/ba-p/510110

As per above documentation I registered an App in Azure and created OneDrive account.

And I upload one sample file to OneDrive.

Then from code part, I am able to generate the Access_Token using Azure AD Client Id and Client Secret.

In this I am not able to identity what is "driveItem". The POC code I tried in Console Application added here.

Now I want to know what exactly to do to convert a rtf document to pdf?

private static string TENANT_NAME = "mycompany.onmicrosoft.com";
private static string resource = "https://graph.microsoft.com";
private static string loginname = "*******-fa34-****-b**4-********10";
private static string loginpassword = "*****~d~********Gpd*********";
private static string AzureTenantID = "{TenantID}";
private static string spositeUrl = "https://mytest-my.sharepoint.com/personal/user1/";
private static string destinationDocumentLibrary = "dl1";

 static async Task Main(string[] args)
{
    var values = new List<KeyValuePair<string, string>>
    {
        new KeyValuePair<string, string>("client_id", loginname),
        new KeyValuePair<string, string>("client_secret", loginpassword),
        new KeyValuePair<string, string>("scope", "Files.ReadWrite.All"),
        new KeyValuePair<string, string>("grant_type", "client_credentials"),
        new KeyValuePair<string, string>("resource", resource)
    };

    var client = new HttpClient();
    var requestUrl = $"https://login.microsoftonline.com/{TenantID}/oauth2/token";
    var requestContent = new FormUrlEncodedContent(values);
    var response = await client.PostAsync(requestUrl, requestContent);
    var responseBody = await response.Content.ReadAsStringAsync();
    dynamic tokenResponse = JsonConvert.DeserializeObject(responseBody);
    string token1 = tokenResponse?.access_token;

    //USER TOKEN - THIS WORKS!!!!!!!!!!!!

    //UserPasswordCredential userPasswordCredential = new UserPasswordCredential(loginname, loginpassword);
    //var graphauthority = "https://login.microsoftonline.com/" + AzureTenantID;
    //AuthenticationContext authContext = new AuthenticationContext(graphauthority);
    //var token = authContext.AcquireTokenAsync(resource, ""*******-fa34-****-b**4-********10", userPasswordCredential).Result.AccessToken;
    // Create a new HttpWebRequest Object to the mentioned URL.

    HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create("https://graph.microsoft.com/v1.0/drive/************:/content?format=pdf");
    //HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create("https://graph.microsoft.com/v1.0/drives/b!zMNDej1sNEG0SanRDltXfAVTYcdt1pdIggMBPYZYp9Wgdi3ir9sFQJXof6...");

    myHttpWebRequest.AllowAutoRedirect = false;
    myHttpWebRequest.Headers.Set("Authorization", ("Bearer " + token1));
    HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
    string downloadPath = myHttpWebResponse.GetResponseHeader("Location");
    Console.WriteLine("Download PDF file from here:\n " + downloadPath);

    //Get the file Stream with Location Url

    HttpWebRequest HttpWebRequest_download = (HttpWebRequest)WebRequest.Create(downloadPath);
    HttpWebRequest_download.Accept = "blob";
    var response1 = (HttpWebResponse)HttpWebRequest_download.GetResponse() ;

    Stream myStream = response1.GetResponseStream();
    FileStream targetFile = new FileStream(@"D:\Test\GraphAPI\converted_localcopy.pdf", FileMode.Create);
    myStream.CopyTo(targetFile);
    myStream.Close();    

    //You can continue to use Graph API to upload document back to OneDrive or other SPO site

    //since we used loginname/password above already, we will use simple CSOM to upload file to another SPO site as quick demo

    using (var clientContext = new ClientContext(spositeUrl))
    {

        SecureString passWord = new SecureString();
        foreach (char c in loginpassword.ToCharArray()) passWord.AppendChar(c);
        clientContext.Credentials = new SharePointOnlineCredentials(loginname, passWord);
		var web = clientContext.Web;
        clientContext.Load(web);
        clientContext.ExecuteQuery();
        List dl = web.Lists.GetByTitle(destinationDocumentLibrary);
        clientContext.Load(dl);
        clientContext.ExecuteQuery();
        //Upload the converted file to SPO site
        targetFile.Position = 0;
        var fci = new FileCreationInformation
        {

            Url = "orange_converted_spocopy.pdf",
            ContentStream = targetFile,
            Overwrite = true
        };

        Folder folder = dl.RootFolder;
        FileCollection files = folder.Files;
        Microsoft.SharePoint.Client.File file = files.Add(fci);
        clientContext.Load(files);
        clientContext.Load(file);
        clientContext.ExecuteQuery();
        targetFile.Close();
        response1.Close();
        Console.WriteLine("Converted file is uploaded to SPO site - orange_converted_spocopy.pdf");
        Console.ReadKey();

    }

}
Microsoft Graph
Microsoft Graph
A Microsoft programmability model that exposes REST APIs and client libraries to access data on Microsoft 365 services.
12,291 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,026 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Q&A Assist
    2023-11-08T19:06:40.9466667+00:00
    AI generated content. This question contains an answer created with AI from Q&A Assist. Learn more

    To convert an RTF document to a PDF file using Microsoft Graph API, you can use the OneDrive API and Microsoft Graph API. You will need to upload the RTF document to OneDrive, then use the Microsoft Graph API to convert it to a PDF file. Here are the high-level steps to follow:

    1. Register your application with Microsoft to get a client ID and a client secret.
    2. Sign in to OneDrive with the specified scopes using the token flow or code flow.
    3. Upload the RTF document to OneDrive.
    4. Use the Microsoft Graph API to convert the RTF document to a PDF file.

    For detailed steps on how to register your application and upload the RTF document to OneDrive, see the "OneDrive Service" and "Quickstart: Acquire a token and call Microsoft Graph API from a desktop application" references respectively.

    To convert the RTF document to a PDF file, you can use the POST /drives/{drive-id}/items/{item-id}/content endpoint of the Microsoft Graph API. Set the format query parameter to pdf and include the Content-Type header set to application/pdf. For more information on making requests to the Microsoft Graph endpoint for OneDrive resources, see the "Getting started with OneDrive API" reference.


    References:

    0 comments No comments

  2. Bruce (SqlWork.com) 66,866 Reputation points
    2023-11-09T02:52:31.6866667+00:00

    Every file (driveitem) as a unique item-id. You can also it’s unique path

    https://learn.microsoft.com/en-us/onedrive/developer/rest-api/resources/driveitem?view=odsp-graph-online


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.