Syncfusion AI Assistant

How can I help you?

Open PDF file from Azure Blob Storage

28 Feb 20268 minutes to read

The Vue PDF Viewer supports loading PDF files from Azure Blob Storage using either the standalone or server-backed viewer. The following steps demonstrate both approaches.

Using the standalone PDF Viewer

Follow these steps to load a PDF from Azure Blob Storage in the standalone PDF Viewer.

Step 1: Create a Simple PDF Viewer Sample in Vue

Follow the getting-started guide in this link to create a basic PDF Viewer sample in Vue.

Step 2: Modify the src/App.vue file in the Vue project

  1. Import the required modules at the top of the file:
<script>
  import { BlockBlobClient } from "@azure/storage-blob";
</script>
  1. Use the SASUrl to fetch the PDF file, convert the response to an ArrayBuffer, and then transform it into a Uint8Array. Convert the Uint8Array into a Base64 string and load it into the PDF Viewer.

NOTE

Replace Your SAS Url in Azure with the actual SAS URL for the Azure Blob Storage account.

<script>
  export default {
    methods: {
      loadPdfDocument: async function () {
        var SASUrl = "*Your SAS Url in Azure*";
        const response = await fetch(SASUrl);
        const arrayBuffer = await response.arrayBuffer();
        const uint8Array = new Uint8Array(arrayBuffer);
        const base64String = btoa(
          String.fromCharCode(...uint8Array)
        );
        var viewer = document.getElementById('pdfViewer').ej2_instances[0];
        setTimeout(function() {
          viewer.load("data:application/pdf;base64," + base64String);
        }, 2000);
      },
    }
  }
</script>

NOTE

The npm install @azure/storage-blob package must be installed in the application to use the previous code example.

View sample in GitHub.

Using the server-backed PDF Viewer

Follow these steps to load a PDF from Azure Blob Storage using the server-backed PDF Viewer.

Step 1: Create a Simple PDF Viewer Sample in Vue

Follow the getting-started guide in this link to create a basic PDF Viewer sample in Vue.

Step 2: Modify the PdfViewerController.cs File in the Web Service Project

  1. Create a web service project in .NET Core 3.0 or above. Refer to this link for instructions on how to create a web service project.

  2. Open the PdfViewerController.cs file in the web service project.

  3. Import the required namespaces at the top of the file:

using System.IO;
using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Specialized;
  1. Add the following private fields and constructor parameters to the PdfViewerController class. In the constructor, assign the values from the configuration to the corresponding fields:
private readonly string _storageConnectionString;
private readonly string _storageContainerName;
private readonly ILogger<PdfViewerController> _logger;

public PdfViewerController(IConfiguration configuration, ILogger<PdfViewerController> logger)
{
  _storageConnectionString = configuration.GetValue<string>("connectionString");
  _storageContainerName = configuration.GetValue<string>("containerName");
  _logger = logger;
}
  1. Modify the Load method to load PDF files from Azure Blob Storage.
[HttpPost("Load")]
[Microsoft.AspNetCore.Cors.EnableCors("MyPolicy")]
[Route("[controller]/Load")]
//Post action for Loading the PDF documents 
 
public IActionResult Load([FromBody] Dictionary<string, string> jsonObject)
{
  PdfRenderer pdfviewer = new PdfRenderer(_cache);
  MemoryStream stream = new MemoryStream();
  object jsonResult = new object();

  if (jsonObject != null && jsonObject.ContainsKey("document"))
  {
    if (bool.TryParse(jsonObject["isFileName"], out bool isFileName) && isFileName)
    {
      BlobServiceClient blobServiceClient = new BlobServiceClient(_storageConnectionString);
      string fileName = jsonObject["document"];
      BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient(_storageContainerName);
      BlockBlobClient blockBlobClient = containerClient.GetBlockBlobClient(fileName);
      blockBlobClient.DownloadTo(stream);
    }
    else
    {
      byte[] bytes = Convert.FromBase64String(jsonObject["document"]);
      stream = new MemoryStream(bytes);
    }
  }
  jsonResult = pdfviewer.Load(stream, jsonObject);
  return Content(JsonConvert.SerializeObject(jsonResult));
}
  1. Open the appsettings.json file in the web service project and add the following lines below the existing "AllowedHosts" configuration:
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "connectionString": "*Your Connection string from Azure*",
  "containerName": "*Your container name in Azure*"
}

NOTE

Do not store secrets in source control. Use secure configuration options such as Azure Key Vault, environment variables, or a secrets manager to hold connection strings.

Step 3: Configure the PDF Viewer component

Set the serviceUrl property of the PDF Viewer component to the web service endpoint (replace https://localhost:44396/pdfviewer with the actual URL of the server). Set the documentPath property to the PDF file name to load from Azure Blob Storage. Ensure the document name exists in the Azure container.

<template>
  <div id="app">
    <ejs-pdfviewer id="pdfViewer" :serviceUrl="serviceUrl" :documentPath="documentPath">
    </ejs-pdfviewer>
  </div>
</template>

<script setup>
import { provide } from "vue";

import {
  PdfViewerComponent as EjsPdfviewer, Toolbar, Magnification, Navigation, LinkAnnotation, BookmarkView,
  ThumbnailView, Print, TextSelection, TextSearch, Annotation, FormFields, FormDesigner
} from '@syncfusion/ej2-vue-pdfviewer';

// Replace the "localhost:44396" with the actual URL of the server
const serviceUrl = "https://localhost:44396/pdfviewer";
const documentPath = "PDF_Succinctly.pdf";

provide('PdfViewer', [Toolbar, Magnification, Navigation, LinkAnnotation, BookmarkView, ThumbnailView,
  Print, TextSelection, TextSearch, Annotation, FormFields, FormDesigner]);

</script>
<template>
  <div id="app">
    <ejs-pdfviewer id="pdfViewer" :serviceUrl="serviceUrl" :documentPath="documentPath">
    </ejs-pdfviewer>
  </div>
</template>

<script>
import {
  PdfViewerComponent, Toolbar, Magnification, Navigation, LinkAnnotation, BookmarkView,
  ThumbnailView, Print, TextSelection, TextSearch, Annotation, FormFields, FormDesigner
} from '@syncfusion/ej2-vue-pdfviewer';

export default {
  name: 'app',
  components: {
    'ejs-pdfviewer': PdfViewerComponent
  },
  data() {
    return {
      // Replace the "localhost:44396" with the actual URL of the server
      serviceUrl: "https://localhost:44396/pdfviewer",
      documentPath: "PDF_Succinctly.pdf"
    };
  },
  provide: {
    PdfViewer: [Toolbar, Magnification, Navigation, LinkAnnotation, BookmarkView, ThumbnailView,
      Print, TextSelection, TextSearch, Annotation, FormFields, FormDesigner]
  }
}
</script>

NOTE

The Azure.Storage.Blobs NuGet package must be installed in the application to use the previous code example.

View sample in GitHub.