Preview Azure Blob Pdf document in AngularJS

Rajnilari2015
Posted by in Azure category on for Beginner level | Points: 250 | Views : 8199 red flag

Azure Blob storage is a service for storing large amounts of unstructured data. In this article we will look how we can preview Blob Pdf from Base64 Encoded string in AngularJS.


 Download source code for Preview Azure Blob Pdf document in AngularJS

Introduction

Azure Blob storage is a service for storing large amounts of unstructured data. In this article we will look how we can preview Blob Pdf from Base64 Encoded string in AngularJS.

Step 1: Create a Source Blob Container in the Azure Portal

Open the Azure portal(https://portal.azure.com), and then choose Storage Account say Containers

Create a source container say sourcecontainer

It will appear as

Step 2: Upload a file in the Source Container

Let us upload a Pdf file in sourcecontainer.

Step 3: Making the WebAPI Controller

Open a WebAPI project is VS studio and add the below Nuget packages

Install-Package WindowsAzure.Storage

Install-Package Microsoft.WindowsAzure.ConfigurationManager

Also install CORS by issuing the command Install-Package Microsoft.AspNet.WebApi.Cors

Enable CORS setting inside the WebApiConfig.cs file as under

using System.Web.Http;
using System.Web.Http.Cors;

namespace WebApplication1
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
            // Web API configuration and services    
            config.EnableCors();
            config.EnableCors(new EnableCorsAttribute("*", "*", "*"));

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}

Now create a folder say Utilities and add a class file say BlobService.cs file with the below content

using Microsoft.Azure;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using System;
using System.IO;

namespace WebApplication1.Utilities
{
    public class BlobService
    { 
  		public string GetBase64BlobPdfData(string blobName)
        {
            string connectionString = CloudConfigurationManager.GetSetting("StorageConnectionString");

            // Retrieve storage account from connection string.
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);

            // Create the blob client.
            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

            // Retrieve reference to the blob container.
            CloudBlobContainer container = blobClient.GetContainerReference("documents");

            // Retrieve reference to a blob
            CloudBlockBlob blobReference = container.GetBlockBlobReference(blobName);

            string base64Data;

            //Convert stream to base64 encoding
            using (var memoryStream = new MemoryStream())
            {
                blobReference.DownloadToStream(memoryStream);
                var bytes = memoryStream.ToArray();
                var b64String = Convert.ToBase64String(bytes);
                base64Data = "data:application/pdf;base64," + b64String;
            }
            return base64Data;            
        }
    }
}

The GetBase64BlobPdfData function accepts the blobname, converts the blob pdf file to base64 encoded data and finally returns the string. Finally open the ValuesController.cs file and add the below code

using System.Web.Http;
using WebApplication1.Utilities;

namespace WebApplication1.Controllers
{
    [RoutePrefix("BlobDocument")]
    public class ValuesController : ApiController
    {      

        [Route("BlobPdfData")]
        [HttpGet]
        public string GetPhotoData()
        {
            BlobService df = new BlobService();
            var blobPdfContent = df.GetBase64BlobPdfData("IDProof.pdf");
            return blobPdfContent;
        }
    }
}

Running the application from PostMan yields

Step 4: Making the Pdf file Preview from AngularJS

Create a index.html page and add the below content to it

<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>

<body>
	<h2>Preview PDF document</h2>
	<div ng-app="myApp" ng-controller="myCtrl">

		<embed ng-src="{{pdfContent}}" style="width:500px;height:500px;"></embed>

	</div>

	<script>
		var app = angular.module('myApp', []);
		app.controller('myCtrl', [ '$scope', '$sce','$http',function($scope,$sce,$http) {

			$http.get("http://localhost:12369/BlobDocument/BlobPdfData")

  			.then(function(response) {

  				console.log(response.data);
      				
      				$scope.pdfContent = $sce.trustAsResourceUrl(response.data);
      			}); }]);
	</script>

</body>
</html>

The code is reading the content from the API exposed and binds the same to an embed tag by setting the ng-src to the URL value returned from the API (http://localhost:12369/BlobDocument/BlobPdfData). The output is as under

Conclusion

In this article we looked into how to preview Blob Pdf from Base64 Encoded string in AngularJS. Hope this will be helpful. Thanks for reading. Zipped file attached.

Page copy protected against web site content infringement by Copyscape

About the Author

Rajnilari2015
Full Name: Niladri Biswas (RNA Team)
Member Level: Platinum
Member Status: Member,Microsoft_MVP,MVP
Member Since: 3/17/2015 2:41:06 AM
Country: India
-- Thanks & Regards, RNA Team


Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)