Contact Support
Save PDF file to One Drive
9 Aug 20237 minutes to read
To save a PDF file to One Drive, you can follow the steps below
Step 1 Create the Microsoft graph API.
Need to create a Microsoft Graph API application and obtain the necessary credentials, namely the application ID and tenant ID. Follow the steps provided in the link to create the application and obtain the required IDs.
Step 2: Create a PDF Viewer sample in Angular
Follow the instructions provided in this link to create a simple PDF Viewer sample in Angular. This will set up the basic structure of your PDF Viewer application.
Step 3: Modify the PdfViewerController.cs
File in the Web Service Project
-
Create a web service project in .NET Core 3.0 or above. You can refer to this link for instructions on how to create a web service project.
-
Open the
PdfViewerController.cs
file in your web service project. -
Import the required namespaces at the top of the file:
using System.IO;
using Microsoft.Graph;
using Microsoft.Identity.Client;
using Helpers;
- Add the following private fields and constructor parameters to the
PdfViewerController
class, In the constructor, assign the values from the configuration to the corresponding fields
private IConfiguration _configuration;
public readonly string folderName;
public readonly string applicationId;
public readonly string tenantId;
public PdfViewerController(IWebHostEnvironment hostingEnvironment, IMemoryCache cache, IConfiguration configuration)
{
_hostingEnvironment = hostingEnvironment;
_cache = cache;
_configuration = configuration;
folderName = _configuration.GetValue<string>("FolderName");
tenantId = _configuration.GetValue<string>("TenantId");
applicationId = _configuration.GetValue<string>("ApplicationId");
}
- Modify the
Download()
method to save the downloaded PDF files to One Drive bucket
[HttpPost("Download")]
[Microsoft.AspNetCore.Cors.EnableCors("MyPolicy")]
[Route("[controller]/Download")]
//Post action for downloading the PDF documents
public async Task<IActionResult> Download([FromBody] Dictionary<string, string> jsonObject)
{
//Initialize the PDF Viewer object with memory cache object
PdfRenderer pdfviewer = new PdfRenderer(_cache);
string documentBase = pdfviewer.GetDocumentAsBase64(jsonObject);
byte[] documentBytes = Convert.FromBase64String(documentBase.Split(",")[1]);
// Save the PDF as a stream
Stream stream = new MemoryStream(documentBytes);
string documentId = jsonObject["documentId"];
string result = Path.GetFileNameWithoutExtension(documentId);
string fileName = result + "_downloaded.pdf";
var config = LoadAppSettings();
var client = GetAuthenticatedGraphClient(config);
var request = client.Me.Drive.Root.Children.Request();
string folderId = string.Empty;
var results = await request.GetAsync();
var folder = results.FirstOrDefault(f => f.Name == folderName && f.Folder != null);
if (folder != null)
{
// Save the matching folderId
folderId = folder.Id;
}
var uploadedFile = client.Me.Drive.Items[folderId]
.ItemWithPath(fileName)
.Content
.Request()
.PutAsync<DriveItem>(stream)
.Result;
return Content(documentBase);
}
- Open the
appsettings.json
file in your web service project, Add the following lines below the existing"AllowedHosts"
configuration
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"TenantId": "Your_Tenant_ID",
"applApplicationIdicationId": "Your_Application_ID",
"FolderName": "Your_Folder_Name_To_Access_The_Files_In_Onedrive"
}
NOTE
Replace Your_Tenent_ID, Your_Application_ID, and Your_Folder_Name_To_Access_The_Files_In_Onedrive with your actual tenant ID, application ID, and folder name.
Step 4: Set the PDF Viewer Properties in Angular PDF viewer component
Modify the serviceUrl
property of the PDF viewer component with the accurate URL of your web service project, replacing https://localhost:44396/pdfviewer
with the actual URL of your server. Set the documentPath
property of the PDF viewer component to the desired name of the PDF file you wish to load from One Drive. Ensure that you correctly pass the document name from the files available in your drive folder to the documentPath property.
import { Component, OnInit } from '@angular/core';
import { LinkAnnotationService, BookmarkViewService, MagnificationService,
ThumbnailViewService, ToolbarService, NavigationService,
TextSearchService, AnnotationService, TextSelectionService,
PrintService, FormDesignerService, FormFieldsService} from '@syncfusion/ej2-angular-pdfviewer';
@Component({
selector: 'app-container',
// specifies the template string for the PDF Viewer component
template: `<div class="content-wrapper">
<ejs-pdfviewer id="pdfViewer"
[serviceUrl]='service'
[documentPath]='documentPath'
style="height:640px;display:block">
</ejs-pdfviewer>
</div>`,
providers: [ LinkAnnotationService, BookmarkViewService, MagnificationService,ThumbnailViewService,
ToolbarService, NavigationService, AnnotationService, TextSearchService,
TextSelectionService, PrintService, FormDesignerService, FormFieldsService]
})
export class AppComponent implements OnInit {
// Replace the "localhost:44396" with the actual URL of your server
public service = 'https://localhost:44396/pdfviewer';
public documentPath = 'PDF_Succinctly.pdf';
}
NOTE
The following NuGet packages are required to use the previous code example
- Microsoft.Identity.Client
- Microsoft.Graph
- Microsoft.Extensions.Configuration
- Microsoft.Extensions.Configuration.FileExtensions
- Microsoft.Extensions.Configuration.Json
You can install these packages using the NuGet Package Manager.