Save PDF files to Azure Blob Storage in Angular
13 Feb 202612 minutes to read
The Angular PDF Viewer component supports saving PDF files to Azure Blob Storage using either a standalone (browser) configuration or a server-backed configuration. The following steps demonstrate both approaches and include prerequisites and security guidance for production deployments.
Using Standalone PDF Viewer
Follow the steps below to save a PDF file to Azure Blob Storage from an Angular PDF Viewer.
Step 1: Create a Simple PDF Viewer Sample in Angular
Start by following the steps provided in this link to create a simple PDF viewer sample in Angular. This will give you a basic setup of the PDF viewer component.
Step 2: Modify the src/app/app.ts File in the Angular Project
- Import the required namespaces at the top of the file:
import { BlockBlobClient } from "@azure/storage-blob";- Add the following private properties to the
AppComponentclass, and assign the values from the configuration to the corresponding properties
NOTE
Replace Your SAS Url in Azure with the SAS URL generated for the target blob. For production, generate short-lived SAS tokens on the server rather than embedding SAS URLs in client code.
private SASUrl: string = "*Your SAS Url in Azure*";- Configure a custom toolbar item for the download function to save a PDF file in Azure Blob Storage.
@Component({
selector: 'app-root',
template: `<div class="content-wrapper">
<ejs-pdfviewer id="pdfViewer"
[resourceUrl]='resource'
[toolbarSettings]="toolbarSettings"
(toolbarClick)="toolbarClick($event)"
style="height:640px;display:block">
</ejs-pdfviewer>
</div>`,
providers: [ LinkAnnotationService, BookmarkViewService, MagnificationService,
ThumbnailViewService, ToolbarService, NavigationService,
TextSearchService, TextSelectionService, PrintService,
AnnotationService, FormDesignerService, FormFieldsService, PageOrganizerService]
})
export class AppComponent implements OnInit {
public resource: string = "https://cdn.syncfusion.com/ej2/23.1.43/dist/ej2-pdfviewer-lib";
public toolItem1: CustomToolbarItemModel = {
prefixIcon: 'e-icons e-pv-download-document-icon',
id: 'download_pdf',
tooltipText: 'Download file',
align: 'right'
};
public toolbarSettings = {
showTooltip: true,
toolbarItems: ['OpenOption', 'PageNavigationTool', 'MagnificationTool', 'PanTool', 'SelectionTool', 'SearchOption', 'PrintOption', this.toolItem1, 'UndoRedoTool', 'AnnotationEditTool', 'FormDesignerEditTool', 'CommentTool', 'SubmitForm']
};
public toolbarClick(args: any): void {
if (args.item && args.item.id === 'download_pdf') {
this.SavePdfToBlob();
}
}
}- Retrieve the PDF viewer instance and save the current PDF as a Blob. Then, read the Blob as an ArrayBuffer and upload the ArrayBuffer to Azure Blob Storage using ‘BlockBlobClient’.
SavePdfToBlob() {
var proxy = this;
var pdfViewer = (<any>document.getElementById('pdfViewer')).ej2_instances[0];
pdfViewer.saveAsBlob().then(function (value: Blob) {
var reader = new FileReader();
reader.onload = async () => {
// Convert ArrayBuffer to Uint8Array
if (reader.result) {
const arrayBuffer = reader.result as ArrayBuffer;
const blobClient = new BlockBlobClient(proxy.SASUrl);
// Upload data to the blob
const uploadBlobResponse = await blobClient.upload(arrayBuffer, arrayBuffer.byteLength);
console.log(`Upload blob successfully`, uploadBlobResponse.requestId);
}
};
reader.readAsArrayBuffer(value);
});
}NOTE
Install the Azure Storage Blob client package for browser use:
npm install @azure/storage-blob.
Using Server-Backed PDF Viewer
To save a PDF file to Azure Blob Storage, you can follow the steps below
Step 1: Create a PDF Viewer sample in Angular
Follow the instructions provided in this link to create a simple PDF Viewer sample in Angular. This will set up the basic structure of your PDF Viewer application.
Step 2: Modify the PdfViewerController.cs File in the Web Service Project
-
Create a web service project in .NET Core 3.0 or above. You can refer to this link for instructions on how to create a web service project.
-
Open the
PdfViewerController.csfile in your web service project. -
Import the required namespaces at the top of the file:
using System.IO;
using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Specialized;- Add the following private fields and constructor parameters to the
PdfViewerControllerclass, 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;
}- Modify the Download() method to save the downloaded PDF file to the Azure Blob Storage container.
[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 document = jsonObject["documentId"];
BlobServiceClient blobServiceClient = new BlobServiceClient(_storageConnectionString);
BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient(_storageContainerName);
string result = Path.GetFileNameWithoutExtension(document);
// Get a reference to the blob
BlobClient blobClient = containerClient.GetBlobClient(result + "_downloaded.pdf");
// Convert the document base64 string to bytes
byte[] bytes = Convert.FromBase64String(documentBase.Split(",")[1]);
// Upload the document to Azure Blob Storage
using (MemoryStream stream = new MemoryStream(bytes))
{
blobClient.Upload(stream, true);
}
return Content(documentBase);
}- Open the
appsettings.jsonfile in your web service project, 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
Replace the placeholders with the actual Azure Storage connection string and container name. For enhanced security, avoid storing connection strings in source-controlled files; use environment variables, managed identities, or a secret store such as Azure Key Vault.
Step 3: Modify the web service project to save the downloaded document to Azure Blob Storage
Create a web service project in .NET Core (version 3.0 and above) by following the steps in this link. In the controller.cs file of your web service project, add the following code to modify the Download method. This code saves the downloaded PDF document to Azure Blob Storage container.
using System.IO;
using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Specialized;
[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 document = jsonObject["documentId"];
BlobServiceClient blobServiceClient = new BlobServiceClient(_storageConnectionString);
BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient(_storageContainerName);
string result = Path.GetFileNameWithoutExtension(document);
// Get a reference to the blob
BlobClient blobClient = containerClient.GetBlobClient(result + "_download.pdf");
// Convert the document base64 string to bytes
byte[] bytes = Convert.FromBase64String(documentBase.Split(",")[1]);
// Upload the document to Azure Blob Storage
using (MemoryStream stream = new MemoryStream(bytes))
{
blobClient.Upload(stream, true);
}
return Content(documentBase);
}Step 4: Set the PDF Viewer properties in the Angular 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 Azure Blob Storage, and ensure that the document exists in the target container.
import { Component, OnInit } from '@angular/core';
import { LinkAnnotationService, BookmarkViewService, MagnificationService,
ThumbnailViewService, ToolbarService, NavigationService,
TextSearchService, AnnotationService, TextSelectionService,
PrintService, FormDesignerService, FormFieldsService} from '@syncfusion/ej2-angular-pdfviewer';
@Component({
selector: 'app-container',
// specifies the template string for the PDF Viewer component
template: `<div class="content-wrapper">
<ejs-pdfviewer id="pdfViewer"
[serviceUrl]='service'
[documentPath]='documentPath'
style="height:640px;display:block">
</ejs-pdfviewer>
</div>`,
providers: [ LinkAnnotationService, BookmarkViewService, MagnificationService,ThumbnailViewService,
ToolbarService, NavigationService, AnnotationService, TextSearchService,
TextSelectionService, PrintService, FormDesignerService, FormFieldsService]
})
export class AppComponent implements OnInit {
// Replace the "localhost:44396" with the actual URL of your server
public service = 'https://localhost:44396/pdfviewer';
public documentPath = 'PDF_Succinctly.pdf';
}NOTE
Install the
Azure.Storage.BlobsNuGet package in the web service project to use the server example. For security, avoid committing connection strings to source control and prefer environment variables, managed identities, or Azure Key Vault for secret management.