Open PDF from Google Cloud Storage in SfPdfViewer

17 Jul 20263 minutes to read

This article shows how to load a PDF stored in Google Cloud Storage into the Blazor SfPdfViewer component.

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 minimal SfPdfViewer sample

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: Add required namespaces

  1. 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: Download an object and load into the viewer

The example below loads a PDF object from a GCS bucket into memory, converts it to a Base64 data URI, and assigns it to DocumentPath.

@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 the service account credentials.
        _storageClient = StorageClient.Create(credentials);
        _storageClient.DownloadObject(bucketName, fileName, stream);
        stream.Position = 0;
        DocumentPath = "data:application/pdf;base64," + Convert.ToBase64String(stream.ToArray());
        await stream.DisposeAsync();
    }
}

NOTE

  • Replace YourBucketName with the actual Google Cloud Storage bucket name and FileName.pdf with the object name to load in the SfPdfViewer.
  • Replace path/to/service-account-key.json with a path the application can read at runtime to the service account key JSON file.
  • Install the Google.Cloud.Storage.V1 NuGet package in the application to use the preceding code. Ensure the Blazor packages are installed and a valid license key is registered.

View the sample on GitHub

See also