How can I help you?
Open PDF from Google Drive in Angular
11 Feb 20268 minutes to read
Follow these steps to load a PDF from Google Drive using the server-backed PDF Viewer.
Step 1: Set up Google Drive API
Create a project in the Google Developers Console, enable the Google Drive API, and obtain OAuth 2.0 credentials. See the official guide for details
Step 2: Create a simple PDF Viewer sample in Angular
Start by following the steps in this guide to create a simple PDF Viewer sample in Angular. This establishes a basic PDF Viewer component and its dependencies.
Step 3: Modify the PdfViewerController.cs file in the web service project
-
Create a web service project in .NET Core 3.0 or above. For background on the PDF Viewer web service pattern
-
Open the
PdfViewerController.csfile in your web service project. -
Import the required namespaces at the top of the file:
using System.IO;
using Google.Apis.Drive.v3;
using Google.Apis.Util.Store;- Add the following private fields and constructor parameters to PdfViewerController. In the constructor, assign values from configuration to the corresponding fields.
private IConfiguration _configuration;
public readonly string folderId;
public readonly string applicationName;
public readonly string credentialPath;
private static readonly string[] Scopes = { DriveService.Scope.DriveFile, DriveService.Scope.DriveReadonly};
public PdfViewerController(IWebHostEnvironment hostingEnvironment, IMemoryCache cache, IConfiguration configuration)
{
_hostingEnvironment = hostingEnvironment;
_cache = cache;
_configuration = configuration;
folderId = _configuration.GetValue<string>("FolderId");
credentialPath = _configuration.GetValue<string>("CredentialPath");
applicationName = _configuration.GetValue<string>("ApplicationName");
}- Modify the
Load()method to load the PDF files from Google Drive.
[HttpPost("Load")]
[Microsoft.AspNetCore.Cors.EnableCors("MyPolicy")]
[Route("[controller]/Load")]
//Post action for Loading the PDF documents
public async Task<IActionResult> Load([FromBody] Dictionary<string, string> jsonObject)
{
//Initialize the PDF viewer object with memory cache object
PdfRenderer pdfviewer = new PdfRenderer(_cache);
MemoryStream stream = new MemoryStream();
object jsonResult = new object();
if (jsonObject != null && jsonObject.ContainsKey("document"))
{
if (bool.Parse(jsonObject["isFileName"]))
{
string objectName = jsonObject["document"];
UserCredential credential;
using (var stream1 = new FileStream(credentialPath, FileMode.Open, FileAccess.Read))
{
string credPath = "token.json";
credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream1).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(credPath, true));
}
// Create Google Drive API service.
var service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = applicationName,
});
// List PDF files in Google Drive
listRequest.Q = "mimeType='application/pdf' and '" + folderId + "' in parents and trashed=false";
listRequest.Fields = "files(id, name)";
var files = await listRequest.ExecuteAsync();
string fileIdToDownload = string.Empty;
foreach (var file in files.Files)
{
string fileId = file.Id;
string fileName = file.Name;
if (fileName == objectName)
{
// Save the matching fileId
fileIdToDownload = fileId;
break;
}
}
string fileIds = fileIdToDownload;
var request = service.Files.Get(fileIds);
await request.DownloadAsync(stream);
stream.Position = 0;
}
else
{
byte[] bytes = Convert.FromBase64String(jsonObject["document"]);
stream = new MemoryStream(bytes);
}
}
jsonResult = pdfviewer.Load(stream, jsonObject);
return Content(JsonConvert.SerializeObject(jsonResult));
}- Open the
appsettings.jsonfile in your web service project, Add the following lines below the existing"AllowedHosts"configuration
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"FolderId": "Your Google Drive Folder ID",
"CredentialPath": "Your Path to the OAuth 2.0 Client IDs json file",
"ApplicationName": "Your Application name"
}NOTE
Replace the placeholders with actual values for the Google Drive Folder ID, application name, and the path to the OAuth 2.0 client IDs JSON file.
NOTE
The
FolderIdis the unique identifier for the Drive folder. For example, if the folder URL ishttps://drive.google.com/drive/folders/abc123xyz456, then the folder ID isabc123xyz456.
Step 4: Configure the PDF Viewer component
Set the serviceUrl to your web service endpoint (replace the localhost URL with your server URL). Set documentPath to the PDF file name to load from Google Drive. Ensure the document name exists in your Drive folder.
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
Google.Apis.Drive.v3NuGet package must be installed in the web service project to use the previous code example.