Save PDF files to Google Drive
21 Oct 20255 minutes to read
To save a PDF file to Google Drive using the ASP.NET MVC PDF Viewer, follow the steps below. This approach uses a server-backed web service.
Step 1: Set up the Google Drive API
Create a project in the Google Cloud Console and enable the Google Drive API. Obtain the necessary credentials to access the API. For more information, see the official guide
Step 2: Create an ASP.NET MVC PDF Viewer sample
Follow the instructions in this Getting Started guide to create a simple PDF Viewer sample in ASP.NET MVC.
Step 3: Modify the HomeController.cs file in the project
- Import the required namespaces at the top of the file:
using System.IO;
using Google.Apis.Drive.v3;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using Google.Apis.Util.Store;- Modify the
Download()method to save the downloaded PDF files to the Google Drive folder.
// Specify the path to the credentials file
private string credentialsPath = "Your Path to the OAuth 2.0 Client IDs json file";
// Specify the folder ID where you want to upload the PDF on Google Drive
private readonly string folderId = "Your Google Drive Folder ID";
private readonly string ApplicationName = "Your Application Name";
private readonly string tokenjson = "Path to create token.json file";
public async Task<ActionResult> Download(jsonObjects jsonObject)
{
PdfRenderer pdfviewer = new PdfRenderer();
var jsonData = JsonConverter(jsonObject);
string[] Scopes = { DriveService.Scope.DriveFile };
// Download the PDF document
string documentBase = pdfviewer.GetDocumentAsBase64(jsonData);
byte[] documentBytes = Convert.FromBase64String(documentBase.Split(',')[1]);
string documentId = jsonData["documentId"];
string result = Path.GetFileNameWithoutExtension(documentId);
string fileName = result + "_downloaded.pdf";
UserCredential credential;
using (var streammen = new FileStream(credentialsPath, FileMode.Open, FileAccess.Read))
{
// The file token.json stores the user's access and refresh tokens and is created
// automatically when the authorization flow completes for the first time.
string tokenPath = tokenjson;
credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(streammen).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(tokenPath, true));
}
// Create the Drive API service
var service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
// Create file metadata
var fileMetadata = new Google.Apis.Drive.v3.Data.File()
{
Name = fileName,
Parents = new List<string> { folderId }
};
FilesResource.CreateMediaUpload request;
// Upload the file to Google Drive
using (var stream = new MemoryStream(documentBytes))
{
request = service.Files.Create(fileMetadata, stream, "application/pdf");
request.Fields = "id";
var uploadedFile = await request.UploadAsync();
}
return Content(documentBase);
}NOTE
Replace the placeholders with the actual Google Drive folder ID, application name, and the path to the OAuth 2.0 Client IDs JSON file. The folder ID is the unique identifier in the folder URL. For example, in
https://drive.google.com/drive/folders/abc123xyz456, the ID isabc123xyz456.
Step 4: Set the PDF Viewer properties in the ASP.NET MVC PDF Viewer component
Set the documentPath property of the PDF Viewer component to the desired PDF file name that you wish to load from Google Drive. Ensure that the document exists in the target folder.
@{
ViewBag.Title = "Home Page";
}
<div>
<div style="height:500px;width:100%;">
@Html.EJS().PdfViewer("pdfviewer").ServiceUrl(VirtualPathUtility.ToAbsolute("~/Home/")).DocumentPath("PDF_Succinctly.pdf").Render()
</div>
</div>NOTE
Install the Google.Apis.Drive.v3 NuGet package in the application to use the previous code example.