Retrieve a PDF file using AngularJS's $http.get method

  • When using the $http.get(...) method in SPA to download a PDF, the printed document turns out blank.
  • However, upon debugging, it was found that data is successfully retrieved from the API.

Can anyone assist with this issue?

Here is the API implementation to generate and return the PDF stream:

public Stream GetConsumerInformationReport(Guid id)
 {
   ..........
   var stream = cryRpt.ExportToStream(ExportFormatType.PortableDocFormat);
   return stream;
}

This is how the SPA fetches the data from the API:

var print = function () {
            var downloadPath = apiEndPoint + 'Reports/' + $state.current.data.printPrefix + '.pdf';
            $http.get(downloadPath,httpConfig).
                success(function (data) {
                    var blob = new Blob([data], { type: "application/pdf" });
                    var objectUrl = URL.createObjectURL(blob);
                    $window.open(objectUrl);
            }).
            error(function (data, status, headers, config) {
            // if there's an error you should see it here
            });

        };

Answer №1

Download FileSaver.js by visiting this link

Next, create your own download function following this example. Use it as a guide but don't just copy and paste :) For the original version, you can check out -

//Implement the download() method in your AngularJS controller

$scope.download = () => {
    //Indicate that a download is in progress
    $scope.isDownloading = true;

    return $http.get(downloadPath, httpConfig).$promise.then((data: any) => {
            //using saveAs.js (part of upcoming HTML5 API, currently a polyfill)
            var blob = data.response.blob;

            var fileName: string = data.response.fileName || 'document.pdf';

            //SaveAs can be found at saveAs.js from http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js
            (<any>$window).saveAs(blob, fileName);
        })
        .finally(() => {
            $scope.isDownloading = false;
    });
}

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

Guide to transferring parameters from one function to another in Javascript

For my automation project using Protractor and Cucumber, I have encountered a scenario where I need to use the output of Function A in Function B. While I was able to do this without Cucumber by extending the function with "then", I am facing difficulties ...

"Bootstrap-Wizard: How to troubleshoot the onPrevious function not working when used with an

I have been incorporating a bootstrap wizard into one of my applications, and I have encountered an issue. When attempting to utilize the index position of the tabs to achieve a specific goal, I found that it only works with the next button and not with th ...

Is there a way to use JQuery to determine which button in a table was clicked and retrieve all the data from that specific row?

Below is the HTML code: <table class="table table-stripped table-bordered table-hover centerAll" cellpadding="10"> <thead> <th>Nombre</th> <th>Descripci ...

Using this.forceUpdate to efficiently update state within React-Router-DOM's Link component

I was able to resolve my issue on my own, but I'm still unsure about what exactly is going on and why it's working. The situation involves a Link component that links to the current page for a different product. Essentially, it's the same c ...

Is it possible to conceal a form field until a previous field has been completed?

Looking for a way to hide a form field until another field is properly completed? I have a divided registration form and want the second field to appear only when the first one is valid. Preferably using CSS3, with HTML5 and maybe some JavaScript if necess ...

Determining Field of View (FOV) for a perspective camera in ThreeJS following a browser window resize

After changing the size of the browser window, I'm trying to determine the correct Three.JS camera FOV. I have looked at several related questions, but haven't found a solution yet: How to calculate fov for the Perspective camera in three js? C ...

Looking to adjust the fill pattern dynamically

I previously implemented this code: Is there a way to modify the fill image on my 3 buttons to display in 3 distinct colors instead? ...

Unable to retrieve the desired value

Below is the code snippet using ajax //html <input type="text" name="txtName" id="name_id" /> //test.php $.ajax( { url:"controller.php", data:$('#txtName').val(), success: function(result){ ...

What is the best way to find the vertex positions of a JSON model in

Here is the code I am using to load a 3D model in THREE.js: var noisenormalmap = THREE.ImageUtils.loadTexture( "obj/jgd/noisenormalmap.png" ); noisenormalmap.wrapS = THREE.RepeatWrapping; noisenormalmap.wrapT = THREE.RepeatWrapping; noisenormalmap.repeat. ...

Sending messages to all sockets in socket.io except the one who sent it

I'm currently working on integrating a chat feature into my app using socket.io. The process involves sending an API request to the server each time a user sends a message, which is then stored in the database. Only after this data storage step is com ...

Alter the webpage's background color using setInterval while also implementing automatic scrolling based on active records

I've created a row of blinking div elements with a time interval, ensuring that only one div blinks at any given moment. To see it in action, please view the demo below: var arr = $(".boxes"); var current = 0; function bgChange() { if (a ...

Exploring the dynamic JSON object from D3 in a Rails view

Currently, I am in the process of learning D3 and my initial attempt involves showcasing a graph where I manually hard-code the json data. To demonstrate this, I have put together a JSFiddle which you can view here: http://jsfiddle.net/Nu95q/1/ The JSFid ...

Building NodeJS Applications with Object Oriented Design

After spending a considerable amount of time working with NodeJS, I am still struggling to grasp the concept of object-oriented design within the language. The closest I have come is creating a class like this: var SomeClass = function(){ var self = t ...

Steps to create two jQuery dropdown filters for multiple identifiers:

Is it possible to create two dropdown menus that can be used to filter a gallery of images? I am currently facing an issue where the filtering functionality is not working after adding a name attribute to the image IDs. When I select an option from the s ...

Get the data from the files in the request using request.files in Node.js

Is there a way to read the content of a file (either a txt or CSV file) that a user uploads without saving it to local storage? I know I can save the file in an upload directory and then read it from storage. However, I'm wondering if there is a way ...

Utilizing ImagesLoaded and Masonry during the subsequent AJAX request

After successfully loading the page content with an ajax call and initializing the masonry gallery using the code below, everything seems to be working fine: $(".masonry-wrapper").imagesLoaded( container, function() { setTimeout(function () { ...

Is my implementation of async await the most efficient method to handle asynchronous operations in my code?

Struggling to implement and grasp async await functions in my login example, I'm uncertain if my code is the most optimal, elegant, and clean. I especially have doubts regarding error handling, and how to best utilize const and functional programming ...

Get a jQuery object from an array

I have a challenge where I am storing jQuery elements in an array and need to retrieve them. My current approach is as follows: var arr = []; arr.push( $(someElement) ); When attempting to retrieve the element, I use: arr.indexOf($(someElement)); Unf ...

Tips for altering the appearance of a dropped item using JQueryUI sortable

I have a straightforward website where I need to implement the ability to drag and drop styled DIV elements between two containers. Utilizing JQueryUI's sortable function, this behavior was successfully achieved with the following code: $("#active-co ...

Maximizing Intellisense for custom Javascript services in VS Code using Typescript definitions

While developing a backend server with SailsJS, I encountered an issue where my model helper services and own services were not showing Intellisense. To address this, I set up typings, installed type definitions for lodash and node globally, and created js ...