How can I help you?
Save PDF files to Google Drive
12 Feb 20266 minutes to read
This article describes how to save a PDF file to Google Drive from the Syncfusion JavaScript PDF Viewer using a server-side web service. Follow the steps below.
Step 1: Set up the Google Drive API
Create a Google Cloud project, enable the Google Drive API, and obtain OAuth 2.0 credentials. For details, see the Google Drive API enable guide.
Step 2: Create a PDF Viewer sample in JavaScript
Create a simple PDF Viewer sample in JavaScript by following the Syncfusion PDF Viewer for JavaScript getting started guide. This establishes the basic application structure required for the integration.
Step 3: Modify the PdfViewerController.cs file in the web service project
-
Create a web service project targeting .NET Core 3.0 or later. For guidance, see the Syncfusion knowledge base article on creating a PDF Viewer web service in .NET Core.
-
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 the
PdfViewerControllerclass. In the constructor, assign configuration values 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
Download()method to save the downloaded PDF file to the configured Google Drive folder.
[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]);
string documentId = jsonObject["documentId"];
string result = Path.GetFileNameWithoutExtension(documentId);
string fileName = result + "_downloaded.pdf";
UserCredential credential;
using (var memStream = new FileStream(credentialPath, FileMode.Open, FileAccess.Read))
{
string credPath = "token.json";
credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(memStream).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(credPath, true));
}
// Create the Drive API service.
var service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = applicationName,
});
var fileMetadata = new Google.Apis.Drive.v3.Data.File()
{
Name = fileName,
Parents = new List<string> { folderId }
};
FilesResource.CreateMediaUpload request;
using (var stream = new MemoryStream(documentBytes))
{
request = service.Files.Create(fileMetadata, stream, "application/pdf");
request.Fields = "id";
object value = await request.UploadAsync();
}
return Content(documentBase);
}eturn Content(documentBase);
}- Open the
appsettings.jsonfile in the web service project and add the following settings 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 the actual Google Drive folder ID, application name, and the path to the OAuth 2.0 Client IDs JSON file.
NOTE
The folder ID is the unique identifier in the folder URL. For example, in
https://drive.google.com/drive/folders/abc123xyz456, the ID isabc123xyz456.
NOTE
Use a valid
client_idfrom the JSON file to authenticate with the Google Drive API and save files securely.
Step 4: Set the PDF Viewer properties in the JavaScript PDF Viewer component
Update the serviceUrl property of the PDF Viewer component to the web service URL, replacing https://localhost:44396/pdfviewer with the actual server endpoint. Set the documentPath property to the PDF file name that exists in the configured Google Drive folder.
// Inject required modules
ej.pdfviewer.PdfViewer.Inject(
ej.pdfviewer.Toolbar,
ej.pdfviewer.Magnification,
ej.pdfviewer.Navigation,
ej.pdfviewer.LinkAnnotation,
ej.pdfviewer.ThumbnailView,
ej.pdfviewer.BookmarkView,
ej.pdfviewer.TextSelection,
ej.pdfviewer.Annotation,
ej.pdfviewer.FormFields,
ej.pdfviewer.FormDesigner
);
var viewer = new ej.pdfviewer.PdfViewer();
// Replace the "localhost:44396" with the actual URL of your server
viewer.serviceUrl = 'https://localhost:44396/pdfviewer';
viewer.appendTo('#pdfViewer');
viewer.load('PDF_Succinctly.pdf', null);NOTE
Install the
Google.Apis.Drive.v3NuGet package in the web service application to use the previous code example.