Utilizing Angular to efficiently download and showcase PDF files

Presently utilizing

https://github.com/stranger82/angular-utf8-base64

as well as

https://github.com/eligrey/FileSaver.js/

for the purpose of decoding a base64 encoded PDF file that I am fetching from a rest API.

It successfully decodes and downloads, however when attempting to view it, it shows up as blank.

I have researched

AngularJS: Display blob (.pdf) in an angular app

and attempted adding

responseType: 'arraybuffer'

to my get request but this results in the response being null with no data returned from the get request.

Other files download and render correctly without issues.

Any assistance would be greatly appreciated!

Code:

          function save() {
            var fileContent = base64.decode(response.File.fileContent);
            var file = new Blob([fileContent], {type: response.File.contentType});
            saveAs(file, response.File.name);
          }

        $http.get(url.join('')).success(function(response) {
            save(response);
        }).error(function(error) {
            console.log('The following error has occurred' + error);
        });

Answer №1

If the API Rest returns an array of bytes, you can easily utilize this JavaScript function:

NOTE: data.payload should be in the form of an array of bytes Call the function: DownloadService.download(data.payload, 'downloadExcel', 'xls'); DownloadService.download(data.payload, 'downloadPDF', 'pdf');

(function() {
    'use strict';

    angular
        .module('fileUtils')
        .service('DownloadService', DownloadService);

    DownloadService.$inject = ['$window'];

    function DownloadService($window) { // jshint ignore:line

        this.download = function (fileBytes, name, type) {
            var fileName = '';
            if (name) {
                 fileName = name + '.' + type;
            } else {
                 fileName = 'download.' + type;
            }

            var byteCharacters = atob(fileBytes);
            var byteNumbers = new Array(byteCharacters.length);
            for (var i = 0; i < byteCharacters.length; i++) {
                byteNumbers[i] = byteCharacters.charCodeAt(i);
            }
            var byteArray = new Uint8Array(byteNumbers);

            var file = new Blob([byteArray], { type: 'application/' + type });

            if (window.navigator && window.navigator.msSaveOrOpenBlob) {
                window.navigator.msSaveOrOpenBlob(file, fileName);
            } else {
                //trick to download and store a file by generating its URL
                var fileURL = URL.createObjectURL(file);
                var a = document.createElement('a');
                a.href = fileURL;
                a.target = '_blank';
                a.download = fileName;
                document.body.appendChild(a);
                a.click();
            }
        };
    }
})();

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

Add a fresh category to a JSON document

Combining Express (Node.js) and Mongoose, I am developing a REST API and attempting to implement JWT token-based login. However, I have encountered an issue. Upon executing the code below: const mongoose = require('mongoose'); const User = mongo ...

Issue with Chart.js V3.20: Struggling to Filter Legend Labels

Building a dynamic line chart using Chart.js with the capability of up to 19 datasets. The issue arises when there are less than 19 datasets, as the legend still displays for these unused datasets. Previously, a function was used in Chart.js 2.6.0 options ...

HTML list with clickable elements for querying the database and displaying the results in a <div> element

Patience please; I am a newcomer to StackOverflow and this is my inaugural question. Struggling with writing an effective algorithm, I wonder if my attempts to "push" it forward are causing me to complicate what should be a straightforward concept, or if i ...

What is the best way to reset the state in React prior to the render being called?

Whenever I click on a copy icon, a popup is displayed. This happens because the state "showPopup" is set to true upon clicking the copy icon, and the render function recognizes this and shows the popup. The popup will close automatically if I click anywher ...

displaying HTML on the web page only, without appearing in the text input field

update1: I have updated the image to provide better clarity https://i.sstatic.net/hYLsI.png I am currently working on implementing chip filters similar to Google Flights. When selecting "sports," it currently displays "sports1" and replaces "sports" with ...

Encountering a Jasmine undefined error while utilizing Jasmine jQuery

Currently, I am working in the Yeoman Angular environment and utilizing Jasmine for testing purposes. In my index.html file, I have included both Jasmine and Jasmine jQuery like so: <script src="bower_components/jasmine/lib/jasmine-core/jasmine.js"> ...

We encountered a ReferenceError stating that 'dc' is not defined, despite having already imported d3, dc, and crossfilter in

In my current angular project, I have included the necessary imports in the component.ts file in the specific order of d3, crossfilter2, dc, and leaflet. Additionally, I have added the cdn for dc-leaflet.js in the index.html file. Despite these steps, wh ...

Navigating through elements in an array in node.js

Within my array, I store the languages that users prefer. Here is an example: let language = [] var Lang = "it" language.push(Lang) This process is repeated with various languages. The array would eventually contain these values: language ...

The react-router-dom seems to be malfunctioning, so let's simply render the "/"

Struggling to render multiple pages in React, I am a newbie and have been exploring various tutorials and pages. My stack includes React, Webpack, Babel, and ESLint with Airbnb configuration. When I render my React app, it appears like this. View of the ...

Is it possible to initiate an animation in a child component using an input variable?

I have a specific animation that I would like to trigger once an *ngFor loop completes ngAfterViewInit(): void { this.items.changes.subscribe(() =>{ Promise.resolve().then(() => { this.everythingLoaded(); }) }) } After the loop fini ...

The issue of the useRef object returning undefined in React/React-Native is causing confusion during

Every time I attempt to access the ref object, I keep receiving an error stating that it is 'undefined'. My goal is to map through an array of images and use useRef to access each individual one. To start off, I initialized the useRef like this: ...

WordPress is failing to reference the standard jQuery file

I am currently attempting to include the jQuery DataTable JS file in my plugin to showcase database query results using DataTable. The JS file is stored locally on the server. Information about versions: WordPress: v4.0.1 jQuery: v1.11.1 DataTable: v1.10 ...

Access external variables in next.js outside of its environment configuration

Currently, I am developing my application using next js as the framework. While my environment variables work smoothly within the context of next js, I am facing a challenge when it comes to utilizing them outside of this scope. An option is to use dotenv ...

Changing a callback function into a promise in Node.js for OpenTok integration

MY FUNCTIONAL CODE (SUCCESSFULLY WORKING!) I have developed a function with callback to generate tokens and create sessions for OpenTok. This function is then exported to the application. The function //Dependencies var opentok = require('./ot&ap ...

Getting rid of the hash in the URL with AngularJS ui-router

I recently started working with AngularJS and ui-router, and I'm having trouble removing the hashtag(#) from my URL. Here's what I've tried so far: Added $locationProvider.html5Mode(true); in my app config Inserted <base href="/" /> w ...

Tips for incorporating images as radio buttons

Can anyone assist me in setting up a straightforward enabled/disabled radio button grouping on my form? My idea is to utilize an image of a check mark for the enabled option and an X for disabled. I would like the unselected element to appear grayed out ...

Is there a way for me to locate a forum using a JWT Token?

I am searching for a way to retrieve forums using JWT Token. If a user has created 3 forums, I want to display them in a list. My Request is structured like this : ### http://localhost:8080/forum/getByOwnerID Authorization: Bearer {{adminToken}} Alternat ...

Ways to eliminate a textbox from an HTML table using jQuery or JavaScript while retaining the textbox values

Currently, I am facing a task where I have a table with a column filled with textboxes. My goal is to eliminate the textboxes using jQuery/JavaScript while retaining the values within them. Here are a couple of methods I have attempted: // removes both t ...

Personalize JSON Reporter to Display Captured Information - WebdriverIO

I'm currently in the process of scraping data from an android app using WDIO and APPIUM. After successfully storing the scraped data in an array, I now aim to automatically output this array data to a .json file, rather than manually copying and pasti ...

The instance cannot be accessed by ES6 class methods

Having trouble accessing the this instance in one of my methods within a class that I created. In my router, I am calling the method like this: import Emails from '../controllers/emails' import router from 'express' .... route.post(&a ...