A Comprehensive Guide to Displaying PDF Blob Data in AngularJS Applications

Nov 23, 2025 · Programming · 11 views · 7.8

Keywords: AngularJS | PDF | Blob | HTTP Request | Embed Display

Abstract: This article provides an in-depth exploration of how to properly handle PDF Blob data retrieved from a server in AngularJS applications and display it within the page using the <embed> tag. It covers key technical aspects, including setting the correct HTTP response type, creating temporary URLs with the Blob API, ensuring URL security with AngularJS's $sce service, and final HTML embedding. Through step-by-step analysis and code examples, it offers a complete and reliable solution for developers.

Introduction

In modern web applications, it is common to dynamically retrieve binary files, such as PDF documents, from a server and display them directly on the client side without downloading. AngularJS, as a popular front-end framework, provides powerful tools to handle such requirements. However, due to security and data format constraints, directly displaying Blob data can pose challenges. This article delves into how to successfully display PDF Blob data in AngularJS applications, drawing on high-scoring answers from Stack Overflow and supplementing with detailed code examples.

Problem Background and Core Challenges

Developers often obtain PDF files from a server via HTTP POST requests, with the server returning data in Blob format. A Blob (Binary Large Object) is a way to represent raw data, commonly used for file handling. In AngularJS, directly using Blob data to display PDFs in HTML encounters two main issues: first, the HTTP response type must be correctly configured to support binary data; second, the generated temporary URL needs to be trusted by AngularJS to avoid security errors. For instance, in the original code, not setting the responseType led to Blob creation failure, and not using the $sce service resulted in embedded content failing to load.

Detailed Solution

To address these issues, three key steps must be followed: configuring the HTTP request, processing the Blob data, and safely embedding it in HTML. Each step is explained in detail below.

Step 1: Set HTTP Response Type to ArrayBuffer

In AngularJS's $http service, the default response type is string, which is unsuitable for binary data like PDFs. The responseType must be set to arraybuffer to ensure data is received as a binary array. This is based on the XMLHttpRequest specification, enabling proper Blob handling. Code example:

$http.post('/postUrlHere', {myParams}, {responseType: 'arraybuffer'})
  .success(function(response) {
    // Process response data
  });

If this parameter is omitted, the response data may be incorrectly parsed as a string, causing subsequent Blob creation to fail. This step is foundational for ensuring correct data format.

Step 2: Create Blob and Temporary URL

After receiving the ArrayBuffer data, use the JavaScript Blob API to convert it into a Blob object. The Blob constructor takes a data array and MIME type parameter, specified here as application/pdf for PDF files. Then, generate a temporary URL using URL.createObjectURL(), which points to the Blob data and can be directly referenced in the browser. Extended code:

var file = new Blob([response], {type: 'application/pdf'});
var fileURL = URL.createObjectURL(file);

The temporary URL is an in-memory reference valid until the page unloads or is explicitly revoked. This avoids saving data to disk, improving application performance.

Step 3: Use $sce Service to Trust the URL

AngularJS's security model (Strict Contextual Escaping, SCE) requires dynamic URLs to be trusted to prevent XSS attacks. Directly using the temporary URL in templates causes errors, so the $sce service must be injected, and the trustAsResourceUrl method called. This marks the URL as a safe resource, allowing use in embedding tags. Code example:

$scope.content = $sce.trustAsResourceUrl(fileURL);

Ensure $sce is injected in the controller, e.g., app.controller('MyCtrl', ['$scope', '$sce', function($scope, $sce) { ... }]);. Omitting this step may lead to AngularJS intercepting the URL and blocking content loading.

Step 4: Embed PDF in HTML

Finally, use the <embed> tag to display the PDF in the template. To ensure proper binding in AngularJS, use the ng-src directive instead of the src attribute to avoid request errors when expressions are unresolved. Set width and height via CSS to control the display area. HTML code:

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

The <embed> tag is part of the HTML5 standard and supports built-in PDF viewers if the browser allows. This method requires no external libraries, enabling lightweight integration.

Complete Code Example and Best Practices

Integrating all steps, here is a complete AngularJS controller example demonstrating the full process from request to display:

angular.module('myApp', [])
  .controller('PdfController', ['$scope', '$http', '$sce', function($scope, $http, $sce) {
    $http.post('/postUrlHere', {myParams}, {responseType: 'arraybuffer'})
      .success(function(response) {
        var file = new Blob([response], {type: 'application/pdf'});
        var fileURL = URL.createObjectURL(file);
        $scope.content = $sce.trustAsResourceUrl(fileURL);
      })
      .error(function() {
        console.error('Failed to load PDF');
      });
  }]);

In the template:

<div ng-controller="PdfController">
  <embed ng-src="{{content}}" style="width: 100%; height: 500px;"></embed>
</div>

Best practices include error handling (e.g., using the .error() callback), resource cleanup (calling URL.revokeObjectURL() when $scope is destroyed to free memory), and responsive design (using percentage-based widths). Additionally, ensure the server sets CORS headers correctly if cross-origin requests are involved.

Common Issues and Extended Discussion

In practice, developers might face other issues, such as browser compatibility (older versions of IE may not support the Blob API), handling large files (consider chunked loading), or alternative embedding methods (e.g., using <iframe>). While this article focuses on <embed>, <iframe> is also viable by setting the URL as src. For more complex needs, libraries like PDF.js can be explored, but as noted in the problem, this solution avoids external dependencies.

In summary, by correctly configuring HTTP requests, leveraging the Blob API, and using AngularJS security services, PDFs can be efficiently embedded in applications. This approach enhances user experience by reducing extra steps. It is recommended to test various scenarios during development to ensure robustness.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.