How can I help you?
Save PDF files to Google Cloud Storage
11 Feb 20265 minutes to read
To save a PDF file to Google Cloud Storage, follow the steps below.
Step 1: Create a PDF Viewer sample in Angular
Follow the Syncfusion getting-started instructions for the Angular PDF Viewer: Angular PDF Viewer getting started. This sets up the basic PDF Viewer application structure.
Step 2: Modify the PdfViewerController.cs File in the Web Service Project
-
Create a web service project in .NET Core 3.0 or above. Refer to the Syncfusion knowledge base article on creating a PDF Viewer web service: Create a PDF Viewer web service in .NET Core 3.0 and above.
-
Open the
PdfViewerController.csfile in your web service project. -
Import the required namespaces at the top of the file:
using System.IO;
using Google.Cloud.Storage.V1;
using Google.Apis.Auth.OAuth2;- Add the following private fields and constructor parameters to the
PdfViewerControllerclass. In the constructor, assign the configuration values to the corresponding fields.
// Private readonly object _storageClient
private readonly StorageClient _storageClient;
private IConfiguration _configuration;
public readonly string _bucketName;
public PdfViewerController(IWebHostEnvironment hostingEnvironment, IMemoryCache cache, IConfiguration configuration)
{
_hostingEnvironment = hostingEnvironment;
_cache = cache;
// The key file is used to authenticate with Google Cloud Storage. Replace the path with the actual
// service account key JSON file provided by Google Cloud.
string keyFilePath = "path/to/service-account-key.json";
// Load the service account credentials from the key file.
var credentials = GoogleCredential.FromFile(keyFilePath);
// Create a storage client using the service account credentials.
_storageClient = StorageClient.Create(credentials);
_configuration = configuration;
_bucketName = _configuration.GetValue<string>("BucketName");
}- Modify the
Download()method to save the downloaded PDF file to the Google Cloud Storage bucket.
```csharp
[HttpPost(“Download”)]
[Microsoft.AspNetCore.Cors.EnableCors(“MyPolicy”)]
[Route(“[controller]/Download”)]
//Post action for downloading the PDF documents
public 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);
string bucketName = _bucketName;
string fileName = jsonObject[“documentId”];
// Convert the base64 string back to bytes
string result = Path.GetFileNameWithoutExtension(fileName);
byte[] documentBytes = Convert.FromBase64String(documentBase.Split(“,”)[1]);
// Upload the document to Google Cloud Storage
using (var memoryStream = new MemoryStream(documentBytes))
{
_storageClient.UploadObject(bucketName, result + “_downloaded.pdf”, null, memoryStream);
}
return Content(documentBase);
}
6. Open the `appsettings.json` file in the web service project and add the following entries below the existing `"AllowedHosts"` configuration.
```json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"BucketName": "Your Bucket name from Google Cloud Storage"
}
NOTE
Replace Your Bucket name from Google Cloud Storage with the actual name of the Google Cloud Storage bucket.
NOTE
Replace path/to/service-account-key.json with the actual file path to the service account key JSON file. Provide the correct path and filename.
Step 3: Set the PDF Viewer properties in the 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 Google Cloud Storage. Ensure that you correctly pass the document name from the files available in your bucket 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 the server
public service = 'https://localhost:44396/pdfviewer';
public documentPath = 'PDF_Succinctly.pdf';
}NOTE
Install the
Google.Cloud.Storage.V1NuGet package in the web service application to use the previous code example.