Obtain a document from an Angular 2+ software program

In the process of developing a web application using Angular 9, there is a requirement from the client that a PDF should be downloaded upon submitting a form on a particular page.

The backend (server-side) is able to generate the PDF file successfully and return it as a stream. The response from the Web API developed can be viewed at the following link:

https://pastebin.com/xJScx7A4

Various methods were attempted in the Angular app to either open the PDF in the browser or download it as a file. However, the result obtained was similar to what is shown in the screenshot below:

https://i.sstatic.net/YKGMF.png

The first method involved:

loadReport(){

this.spinner.show();

//////// /////////////// /////////////////////

this.api.loadReport(this.filterVM)
.subscribe(res => {
  console.log(res);
  this.spinner.hide();

  ////// //////////////////////////
  const blob = new Blob([res], { type: 'application/pdf' });
  const url= window.URL.createObjectURL(blob);
  window.open(url);
  ////////// /////////////////////

}, err => {
  console.log(err);
  this.spinner.hide();
});
///// ///////////// //////////////////////////

}

The second approach utilized:

  loadReport(){

    this.spinner.show();

    //////// /////////////// /////////////////////    
    this.api.loadReport(this.filterVM)
    .subscribe(res => {
      console.log(res);
      this.spinner.hide();

      ////// //////////////////////////
      this.saveByteArray("Sample Report.pdf", res);
      ////////// /////////////////////

    }, err => {
      console.log(err);
      this.spinner.hide();
    });
    ///// ///////////// //////////////////////////

  }

 saveByteArray(reportName, byte) {
  var blob = new Blob([byte], {type: "application/pdf"});
  var link = document.createElement('a');
  link.href = window.URL.createObjectURL(blob);
  var fileName = reportName;
  link.download = fileName;
  link.click();
};

The outcome of the second methodology is depicted in the provided screenshot:

https://i.sstatic.net/edluj.png

Upon attempting to download the file, it was noticed that the actual size of the file is significantly lesser than the size indicated in the HTTP response (9 bytes vs ~16 KB).

The headers sent in the Web API HTTP response include:

Content-Type: application/pdf
Content-Length: 16187
Content-Disposition: attachment; filename=Report.pdf; filename*=UTF-8''Report.pdf

Several blogs and sites have been referenced for potential solutions, however, none have yielded success yet.

Download File from Bytes in JavaScript

Typescript blob filename without link

https://dev.to/nombrekeff/download-file-from-blob-21ho

How do I download a file with Angular2 or greater

Answer №1

The problem has finally been resolved! Big thanks to Ambroise Rabier for providing a solution to a similar issue on Angular 2 how to display .pdf file. His post led me to https://medium.com/techinpieces/blobs-with-http-post-and-angular-5-a-short-story-993084811af4 as well.

Changes implemented:

In my service.ts file (which was not included in the initial question), you can find it here: https://pastebin.com/vhucnvAX.

Only change made: I added a single line

responseType: 'blob' as 'json'

This line was added to the configureOptions() function of my service class, which is called from the constructor of my service.

You can also view my component.ts file here: https://pastebin.com/d1gB4V8x

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

Prohibit using any as an argument in a function if a generic type is

I have attempted to implement this particular solution to prevent the calling of a generic function with the second type being equal to any. The following code snippet works fine as long as the first generic parameter is explicitly specified: declare fu ...

Sharing the label element as a prop in React component

I encountered the following code snippet: <div className="input-field"> <label htmlFor="timeObjective">Time Objective</label> <FrequencySet label='label'/> //HERE </div> My goal is to tra ...

Incorporating Angular 4 with Angular CLI and ASP.Net MVC5 for seamless integration

Creating a hybrid application with Angular 4 and MVC 5 is my current project. I've set up the Angular 4 structure using angular-cli, but most of the information online only covers either: Manually integrating the two technologies, or Integrating MVC ...

Dealing with mouseover and mouseout events for ul li elements in Angular 9: An easy guide

Having trouble showing and hiding the span tag using mouseover and mouseout events. The ul and li elements are generating dynamically, so I attempted to toggle the display between block and none but it is not working as expected. Does anyone have a solutio ...

Retrieve the text content of the <ul> <li> elements following a click on them

Currently, I am able to pass the .innerTXT of any item I click in my list of items. However, when I click on a nested item like statistics -> tests, I want to display the entire path and not just 'tests'. Can someone assist me in resolving thi ...

The ReferenceError occurs exclusively during the execution of tests

I keep encountering a dull stacktrace after executing my test. I've experimented with solutions like using fakeTimers, require('iconv-lite')..., etc, based on these queries: Encoding not recognized in jest.js ReferenceError: You are trying ...

Why isn't tslint:disable working? What could be causing this issue?

Despite setting tslint:disable, I am still receiving tslint warnings. The specific warnings that are appearing include: [ts] Argument of type 'string' is not assignable to parameter of type 'RequestInit | undefined'. (parameter) optio ...

Expansive Carousel Feature with Ng Bootstrap

In my Angular 5 application, I am utilizing the Carousel component from "@ng-bootstrap/ng-bootstrap": "^1.1.2". I am trying to display pictures in full screen but when I press F11, the image appears like this. I am unsure of which CSS properties to apply ...

Delete a Leaflet polyline connecting two markers using Angular

When utilizing the interval to update JSON data coordinates, a connection path appears between the last and first points on the original data path. https://i.sstatic.net/Sdavp.png Is there a way to eliminate this "connection path" that connects the last ...

Issue encountered while connecting ipcRenderer with ipcMain in an electron application

I recently set up Angular CLI in Electron, and I have a link that triggers a function which communicates between ipcRenderer and ipcMain: Here is the HTML code: <a (click)="check()"> click </a> This is the component code: constructor(privat ...

Is it possible for component tags that are generated to be altered?

I am tasked with converting HTML/CSS documents to be compatible with Angular/cli. The CSS file uses single selectors like "section > section > div", but the generated HTML contains non-standard "component tags" that break these selectors. Instead o ...

Are there any other ways to write code in a Functional style within Angular?

From what I understand, there are several types of Angular v17 code that can be implemented in a Functional way: Functional HTTP Interceptors Functional Route Guards Functional Validator (Reactive forms) I'm interested to know if there are any addit ...

The onChange() function should only consider the last character typed, rather than evaluating the entire line each time

Explanation: I am utilizing the onChange function to detect when someone types the symbol @. Issue: While typing, the code currently checks the entire line each time a character is added, causing a lag in typing speed. I am looking to update the code so i ...

Why aren't the validations being set when creating Angular forms using formControl.values?

I had to structure the form in a specific way in my app.ts file -> courseNameControl = new FormControl("", [Validators.required,Validators.minLength(2)]); contentControl = new FormControl("", Validators.required); form = { cours ...

When using TypeScript and React with Babel, an error may occur: "ReferenceError: The variable 'regeneratorRuntime'

I've been delving into learning typescript, react, and babel, and here is the code I've come up with: export default function App(): JSX.Element { console.log('+++++ came inside App +++++++ '); const {state, dispatch} = useCont ...

Graphics fail to load on cordova-built mobile applications

My angular application functions correctly, but when I convert it to a mobile application using Apache Cordova, the images do not load due to a path not found error. My file structure looks like this: angular.json package.json config.xml s ...

increase the selected date in an Angular datepicker by 10 days

I have a datepicker value in the following format: `Fri Mar 01 2021 00:00:00 GMT+0530 (India Standard Time)` My goal is to add 60 days to this date. After performing the addition, the updated value appears as: `Fri Apr 29 2021 00:00:00 GMT+0530 (India St ...

I require adding a new line of information into the database table

I am looking for help with adding data into a table without any user inputs. Specifically, I want to add data by passing them into an array and then be able to call them at the "Add Site" button so that the row is added into the table. Can someone assist m ...

Centralized MUI design for varying screen dimensions

I am struggling to perfectly center my modal box in the middle of the screen. The problem arises when the screen size changes, causing the box to be misaligned. I attempted using top:50% and left: 50%, but this did not effectively center the box. center ...

When making a GET request using Angular HttpClient, an error message stating "No overload matches this call" may

One issue I am facing is with a GET method in my backend. When sending a request body as input, I receive a list of results in return. However, the problem arises in my frontend: search(cat: Cat): Observable<Cat[]> { return this.httpClient.ge ...