How can I help you?
Save PDF files to Google Cloud Storage
25 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 React
Follow the Syncfusion getting-started instructions for the React PDF Viewer: React 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.
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.
[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);
}- Open the
appsettings.jsonfile in the web service project and add the following entries below the existing"AllowedHosts"configuration.
{
"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 React PDF Viewer component
Modify the serviceUrl property of the PDF Viewer component with the accurate URL of the web service, replacing https://localhost:44396/pdfviewer with the actual server URL. Set the documentPath property to the desired PDF file name to load from Google Cloud Storage, and ensure that the document exists in the target bucket.
import * as ReactDOM from 'react-dom';
import * as React from 'react';
import { PdfViewerComponent, Toolbar, Magnification, Navigation, LinkAnnotation, BookmarkView, ThumbnailView,
Print, TextSelection, Annotation, TextSearch, Inject, FormDesigner, FormFields} from '@syncfusion/ej2-react-pdfviewer';
function App() {
return (<div>
<div className='control-section'>
{/* Render the PDF Viewer */}
<PdfViewerComponent
id="container"
documentPath="PDF_Succinctly.pdf"
// Replace the "localhost:44396" with the actual URL of the server
serviceUrl="https://localhost:44396/pdfviewer"
style={{ 'height': '640px' }}>
<Inject services={[ Toolbar, Magnification, Navigation, Annotation, LinkAnnotation, BookmarkView,
ThumbnailView, Print, TextSelection, TextSearch, FormDesigner, FormFields ]} />
</PdfViewerComponent>
</div>
</div>);
}
const root = ReactDOM.createRoot(document.getElementById('sample'));
root.render(<App />);NOTE
Install the
Google.Cloud.Storage.V1NuGet package in the web service application to use the previous code example.