How to open a blank PDF in a new window using AngularJS

When attempting to generate a PDF with AngularJS, the file ends up empty.

Here is the scenario:

I have a REST API where the response payload from a GET request looks like this:

JVBERi0xLjQKJeLjz9MKMyAwIG9iago8PC9GaWx0ZXIvRmxhdGVEZWNvZGUvTGVuG3RoIDE4NT4+c3RyZWFtCnicpY4xD4JADIX3+xVvxEV7PeDAUYXBSZNzMg4EkGgCRIiD/144B41RNCF9aZO2r18vYmGE8hGQD5OJyIitYKz7rgR10efAZZhSzGIJSTBH4UzMud99rhDS8tXkMbTmqf9mJDtuCuEkbdYpexSr/iah+HB3f+hqZv/6TmQVQqtBZFVXt7K+trs2b0bSQhc+0wAsbk5Y5Smoc9DcCsvIgEnqkWylf7A3SQMeCXG1Bw4HIPIvwB0h835eCmVuZHN0cmVhbQplbmRvoKMSAwIG9iago8PC9UYWJzLviRYlBBdSGVNMSkgNSAwIFIvTWVkaWAwaWs/cBF60Icb333hlJKFLFKSSANKnfb9ou2ZPabdabYpneMd; // and so on

The response headers are:

Response Headers Image

The PDF generated from this data is fine, with all the content intact.

The issue arises when I make an HTTP GET call from Angular as shown below:

$scope.confirmPayment = function(){
    $http.get(apiUrl).then(function(response) {
        console.log(response.data);
        var data = new Blob([response.data], { type: "application/pdf" });
        var fileURL = URL.createObjectURL(data);
        window.open(fileURL);
    });
};

The resulting PDF turns out to be empty. So, why does this happen and what can be done to resolve it? It's worth noting that the response payload in both requests remains consistent.

The response headers for the second call are:

Second Call Response Headers Image

The console log outputs the following:

%PDF-1.4
%
3 0 obj
<</Filter/GMG Read More Length 178>>stream 
// continued log content...
controller.home.js:7:7

Answer №1

For the full blog post on this topic, check out: Learn How to Download Files in an Angular Js2 Application

I have a solution that is working well for me. You can give it a try. One important point you missed is using

RequestOptions({responseType: ResponseContentType.Blob})
and another critical step is: <Blob>response.blob()

   ngOnInit(): void {
    this.getFile("http://localhost:1800/api/demo/GetTestFile")
    .subscribe(fileData => 
      {
      let b:any = new Blob([fileData], { type: 'application/zip' });
      var url= window.URL.createObjectURL(b);
        window.open(url);
      }
    );
  }

   public getFile(path: string):Observable<any>{
    let options = new RequestOptions({responseType: ResponseContentType.Blob});
    return this.http.get(path, options)
        .map((response: Response) => <Blob>response.blob())  ;
  }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What methods are most effective when utilizing imports to bring in components?

Efficiency in Component Imports --Today, let's delve into the topic of efficiency when importing components. Let's compare 2 methods of importing components: Method 1: import { Accordion, Button, Modal } from 'react-bootstrap'; Meth ...

Use Jquery to add unique styles to specific words within a paragraph

I am looking to specifically style a particular word within a dynamic div for example, <div id="info">{$info}</div> prints <p>here you can get info about somnething. if you want more info about something then click here....</p> ...

Sending the same element to a personalized filter repeatedly

Is there a better way to convert a string to a JavaScript date object before using the Angular date filter? The custom filter, stringToDate(), has been implemented and integrated into the code snippet below. <div ng-repeat="blogPost in blogPosts" class ...

Error: jQuery JSONP syntax error due to missing semicolon before statement

Currently, I have implemented the following code to access a rest service that is hosted on a different domain: $.ajax({ type: 'GET', url: url, async: false, jsonpCallback: 'jsonCallback' ...

The require statement in Vue.js is failing to function dynamically

Having trouble dynamically requiring an image in Vue.js and it's not functioning as expected <div class="card" :style="{ background: 'url(' + require(image) + ')',}"> export default { data() { return { ...

Compatibility of Typescript with local storage

Can Typescript interact with local storage in any way? I have been setting items using the following code: localStorage.setItem('someString', JSON.stringify(MyTypescriptObject)); This method stores the object as a plain string. For example: ...

The bootstrap datepicker does not display the date range on the calendar

I tried to incorporate a bootstrap datepicker date-range in the code snippet below, but I am encountering an issue where the selected date range is not displaying on the calendar. <!DOCTYPE html> <html> <head> <link rel="stylesheet" ...

What is the most effective approach for managing nested callbacks in Node.js/Expressjs?

My server side coding is done using Node.js and Expressjs, with MongoDB as the backend. Although I am new to these technologies, I need to perform a list of actions based on requests. For example, in user management: Check if the user is already registe ...

What are some ways to access my AsyncStorage data from any location?

I am utilizing the saga library and storing tokens in AsyncStorage. My goal is to be able to freely access the token retrieved from AsyncStorage in both the loadUserPosts function and the loadPosts function. Where should I add async and how can I correct ...

AngularJS - Utilizing Nested ng-repeats

I'm attempting to iterate through a given JSONObject that contains JSONArray and display it in an HTML format. Here's a sample of what I have: jsonData: { "category1": [ { "name": "Some title", "desc": "And i ...

display picture upon modification

Is there a way for me to display the image I choose in AngularJS, similar to uploading an image on StackOverflow where the selected picture appears before uploading? I'm very new to this, so please be patient with me. Controller $scope.uploadFile = ...

Understanding Multiple Type Scenarios in React with Typescript

Code Demonstration: type PropsType = {top: number} | {bottom: number} // The function that moves something in one direction by a specific distance. function move(props: PropsType) { ... } Expected Usage: move({top: 100}) or move({bottom: 100}) Avoid us ...

The link appears to be broken when trying to access the notFound component in Next.js version 13

In my Next.js 13.4 app directory, I added a not-found.tsx component that functions correctly when entering the wrong route: import Link from 'next/link' function NotFound() { return ( <section> 404, page not found ...

What is the best way to send my webform data to a web API controller as a model class using JQuery AJAX?

This is the AJAX code I have written to pass two values to my API: function submitData() { var username = $("#username").val(); var password = $("#password").val(); $.ajax({ type: 'POST', ...

Mastering the Correct Way to Import Flatbuffers using TypeScript

When working with typescript, I have been incorporating flatbuffers in the following manner: import {flatbuffers} from 'flatbuffers'; const builder = new flatbuffers.Builder(1); Subsequently, I convert to js for integration with react-native: ...

Retrieving AJAX data in a Node.js environment

In my HTML application, I am utilizing AJAX to showcase the output on the same page after the submit button is clicked. Before submitting, I am able to retrieve the values passed in the HTML form using: app.use(express.bodyParser()); var reqBody = r ...

Creating a bar chart by using d3.layout.stack() and parsing data from a CSV file

Mike Bostock's Stacked-to-Grouped example showcases a data generation method that I find intriguing. However, since I have my own data stored in a CSV file, my main focus is on deciphering his approach and adapting it to work with my data instead. // ...

Breaking down an array into alphabetical sections using React and Typescript

I have a large array of strings containing over 100 words. I have already sorted the array in alphabetical order, but now I need to group or split the array into a hash array called hashMap<String(Alphabet), List<String>>. This will allow me to ...

Break free from the confines of a single quote in jQuery within

I'm currently facing a challenge with my ajax function that calls a PHP class to retrieve code stored in the variable $var. The issue arises from having single quotes within the $var string, causing JavaScript to throw an error. Is there a more effic ...

Implementing dynamic component rendering in Vue JS based on dropdown selection

I'm a beginner with Vue JS and I have a specific task in mind. Task Description : I need to create a dropdown with the following values. https://i.sstatic.net/Nllw7.png Upon selecting each value, a specific dropdown component should be added to th ...