How can I help you?
Open PDF file from Google Cloud Storage in Blazor SfPdfViewer
1 Oct 20253 minutes to read
To load a PDF file from Google Cloud Storage in a SfPdfViewer, follow the steps below.
Step 1: Create a service account.
Open the Google Cloud Console and navigate to IAM & Admin > Service accounts. Select Create service account, provide a name, assign the required role (for example, Storage Object Admin), and create a JSON key. Download the key file securely. Use this key file for authenticating your application to access the Google Cloud Storage bucket. For more information, refer to the official Google Cloud documentation..
Step 2: Create a simple SfPdfViewer sample in Blazor.
Follow the getting started guide to create a basic Blazor application with the SfPdfViewer component. This provides the required project setup and a working viewer instance.
Step 3: Include the following namespaces in the Index.razor file.
- Import the required namespaces at the top of the file:
@using Google.Cloud.Storage.V1;
@using Google.Apis.Auth.OAuth2;
@using Syncfusion.Blazor.SfPdfViewer;Step 4: Add the following code example.
@page "/"
<SfPdfViewer2 DocumentPath="@DocumentPath"
@ref="@viewer"
Height="100%"
Width="100%">
</SfPdfViewer2>
@code {
private string DocumentPath { get; set; }
private SfPdfViewer2 viewer;
private readonly string keyFilePath = @"path/to/service-account-key.json";
private readonly string bucketName = "YourBucketName";
private readonly string fileName = "FileName.pdf";
private StorageClient _storageClient;
protected override async Task OnInitializedAsync()
{
MemoryStream stream = new MemoryStream();
// Load the service account credentials from the key file.
var credentials = GoogleCredential.FromFile(keyFilePath);
// Create a storage client with Application Default Credentials
_storageClient = StorageClient.Create(credentials);
_storageClient.DownloadObject(bucketName, fileName, stream);
stream.Position = 0;
DocumentPath = "data:application/pdf;base64," + Convert.ToBase64String(stream.ToArray());
}
}NOTE
Replace Your Bucket name from Google Cloud Storage with the actual Google Cloud Storage bucket name and File Name to be Loaded into Syncfusion® SfPdfViewer with the object name to load in the Syncfusion SfPdfViewer.
NOTE
Replace path/to/service-account-key.json with the absolute or application-accessible path to the service account key JSON file.
NOTE
Install the Google.Cloud.Storage.V1 NuGet package in the application to use the preceding code. Ensure the Syncfusion Blazor packages are installed and a valid license key is registered.