First published on TECHNET on Oct 26, 2018
This post is a contribution from Jing Wang, an engineer with the SharePoint Developer Support team
Many SharePoint Online customers want to convert their word documents or some other documents in SPO to pdf files programmatically.
Within SharePoint Online User Interface, you can convert them one at a time manually, but sometimes, users wish to have the ability to convert multiple documents automatically without having to open each document library, locate the documents and click through the options to do them one at a time.
With new Graph api endpoint listed below, above requirement can be automated with custom code, for example, C#, JavaScript…
Format options
The following values are valid for the format parameter:
Format valueDescriptionSupported source extensions
Converts the item into PDF format. | csv, doc, docx, odp, ods, odt, pot, potm, potx, pps, ppsx, ppsxm, ppt, pptm, pptx, rtf, xls, xlsx |
See details of the endpoint here:
https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/driveitem_get_content_forma...
Sample - Complete solution in C#:
Step I, Create a native app in Azure portal and give permissions, for Graph API.
Step II. Create a Console Application, add two dlls and their references:
DLLs:. These can be added as Nuget packages.
Microsoft.IdentityModel.Clients.ActiveDirectory.dll (Nuget Package Microsoft.SharePointOnline.CSOM)
Newtonsoft.Json.dll (Nuget Package Newtonsoft.Json)
Add the below using statements
Step III, Implement the code, with Graph Api to convert the document and download it locally and upload it back to SPO site:
Note: ADAL library is used for authentication.
Source code:
-------------------------------
Here is the converted file downloaded locally.
The converted pdf is also uploaded to this SPO site:
In the process to generate the url for the Graph API endpoint, I found it kind of tricky to identify the drive ID for specific SPO site, so listing the approach to get the same.
First, Use following url format in Graph Explorer to retrieve the drive id:
https://graph.microsoft.com/v1.0/sites/[spositehostname]:/[sites/pub]:/drive
For example, if the SPO site url is:
https://mycompany.sharepoint.com/sites/testsite
Url to put in Graph Explorer is:
https://graph.microsoft.com/v1.0/sites/mycompany.sharepoint.com:/sites/testsite:/drive
Output has the drive id:
--
I have a file named “Repro.docx” in the root of above drive:
So the file’s conversion endpoint is:
https://graph.microsoft.com/v1.0/drives/b!zMNDej1sNEG0SanRDltXfAVTYcdt1pdIggMBPYZYp9Wgdi3ir9sFQJXof6...
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.