Open PDF from Google Drive in Vue
28 Feb 20269 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 Vue
Start by following the steps in this guide to create a simple PDF Viewer sample in Vue. 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 the 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 appsettings.json in the web service project and add the following keys 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 the web service endpoint (replace the localhost URL with the server URL). Set documentPath to the PDF file name to load from Google Drive. Ensure the document name exists in the Drive folder.
<template>
<div id="app">
<ejs-pdfviewer id="pdfViewer" :serviceUrl="serviceUrl" :documentPath="documentPath">
</ejs-pdfviewer>
</div>
</template>
<script setup>
import { provide } from "vue";
import {
PdfViewerComponent as EjsPdfviewer, Toolbar, Magnification, Navigation, LinkAnnotation, BookmarkView,
ThumbnailView, Print, TextSelection, TextSearch, Annotation, FormFields, FormDesigner
} from '@syncfusion/ej2-vue-pdfviewer';
// Replace the "localhost:44396" with the actual URL of the server
const serviceUrl = "https://localhost:44396/pdfviewer";
const documentPath = "PDF_Succinctly.pdf";
provide('PdfViewer', [Toolbar, Magnification, Navigation, LinkAnnotation, BookmarkView, ThumbnailView,
Print, TextSelection, TextSearch, Annotation, FormFields, FormDesigner]);
</script><template>
<div id="app">
<ejs-pdfviewer id="pdfViewer" :serviceUrl="serviceUrl" :documentPath="documentPath">
</ejs-pdfviewer>
</div>
</template>
<script>
import {
PdfViewerComponent, Toolbar, Magnification, Navigation, LinkAnnotation, BookmarkView,
ThumbnailView, Print, TextSelection, TextSearch, Annotation, FormFields, FormDesigner
} from '@syncfusion/ej2-vue-pdfviewer';
export default {
name: 'app',
components: {
'ejs-pdfviewer': PdfViewerComponent
},
data() {
return {
// Replace the "localhost:44396" with the actual URL of the server
serviceUrl: "https://localhost:44396/pdfviewer",
documentPath: "PDF_Succinctly.pdf"
};
},
provide: {
PdfViewer: [Toolbar, Magnification, Navigation, LinkAnnotation, BookmarkView, ThumbnailView,
Print, TextSelection, TextSearch, Annotation, FormFields, FormDesigner]
}
}
</script>NOTE
The
Google.Apis.Drive.v3NuGet package must be installed in the web service project to use the previous code example.