Is there a way for me to directly download the PDF from the API using Angular?

I'm trying to download a PDF from an API using Angular.

Here's the service I've created to make the API call:

 getPDF(id:any) {
    return this.http.get(
       `url?=${id}`,
        { responseType: 'blob' as 'json', observe: 'response' }
    );
 }

Within my component file, I'm using the service to trigger the PDF download.

  onGeneratepdf() {
    this.service
  .getPDF(
    123
  )
  .subscribe((res: any) => {
    let filename = res.header
    ?.get('content-disposition')
    ?.split(';')[1]
    .split('=')[1];
  let blob: Blob = res.body as Blob;
  var a = document.createElement('a');
  a.download = filename;
  a.href = window.URL.createObjectURL(blob);
  a.click();
  });

}

When I click onGeneratePDF, the PDF is downloaded but the issue is that it's saved as undefined.pdf instead of user.pdf. Additionally, the response headers show:

access-control-allow-origin: *
cache-control: no-cache, no-store, max-age=0, must-revalidate
content-disposition: attachment; filename=user.pdf
content-type: application/pdf

Any assistance with resolving these problems would be greatly appreciated.

Thanks in advance.

Answer №1

function generatePDF() {
        this.service.getPDF(123)
            .subscribe((response: any) => {
                let filename = response.headers
                    ?.get('content-disposition')
                    ?.split(';')[1]
                    .split('=')[1];
                let blobData: Blob = response.body as Blob;
                var anchor = document.createElement('a');
                anchor.download = filename;
                anchor.href = window.URL.createObjectURL(blobData);
                anchor.click();
            });

Feel free to try out the code snippet provided above. It appears there was a typo in the code you initially wrote, where 'res.header' should actually be 'res.headers'.

If the code above doesn't work for you, you can also check out this link for additional solutions and insights: Here.

Thank you!

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

"Must not be currently employed" when using window.open in a basic React application

Let me share a simplified version of the webapp I'm currently developing. Whenever I run into an Uncaught Error: Should not already be working. while executing the window.open(...) line in the following code snippet: const sleep = milliseconds => ...

Leverage the power of React in tandem with Express

My web site is being created using the Express framework on NodeJS (hosted on Heroku) and I'm utilizing the React framework to build my components. In my project, I have multiple HTML files containing div elements along with React components that can ...

Creating folders and writing data to text files in Angular 4/5 with TypeScript: A tutorial

Is it feasible to create a folder, text file, and write data into that file in Angular5 using Typescript for the purpose of logging errors? Your expertise on this matter would be greatly appreciated. Thank you in advance! ...

Transfer data from a child component to a parent component in a React application

Currently, I am working on my second React app. This time, I am experimenting with nested components, unlike my previous project which only had a single component. The main focus of this project is a calculator app built using React. To guide my design pro ...

Revise the calculation output when a specific input is missing

As I work on creating a basic web page for computing values based on selected options, I've encountered an issue with the calculation process. The result does not immediately appear; instead, I have to input a value like 0 and then delete it in order ...

Implementing JSON data retrieval in Django through jQuery

i have implemented a jQuery functionality to send json data containing arrays of elements as shown below $('#brand_category').click(function(event){ category = $("input:checkbox[name=category]:checked").map(function() { return t ...

The error "commands.reduce is not a function" is encountered when using the router.navigate function in

When I try to send a string as a link to my router, such as "/blog/pages/3", I encounter the error "commands.reduce is not a function". Surprisingly, despite the error message showing up in the console, the navigation still works. goToPage(link) { this ...

Tips for scrolling an element within its parent container as a fixed element moves past it

I'm a bit stuck on this jQuery/javascript challenge and haven't made much progress yet. I need some guidance to help me navigate in the right direction! The issue I'm facing involves a fixed element on my webpage that moves into different w ...

Searching in React can be done dynamically by referencing an array, similar to how the "LIKE" function works in SQL

Currently, I'm tackling an issue with a dropdown feature. My goal is to have the dropdown results sorted when the user enters something into the input field. The values in the dropdown are sourced from an array. For instance, codeList = [N1, N2, N3, ...

Utilizing HTML and JavaScript to dynamically switch stylesheets based on the width of

When it comes to using stylesheets for mobile and non-mobile devices, there is a need for different approaches. The idea of comparing browser height and width in JavaScript seems like a good one, but the implementation may not always work as expected. ...

Dimensions of HTML Container on Google Website

I'm attempting to incorporate a collapsible table using HTML Box in a Google site. The code for the collapsible table can be found at http://tutorials.seowebpower.com/google-sites-advanced/collapsible-table. Here is the code: <html> <head> ...

The tooltip callback in react-chartjs-2 is failing to function as expected

I've been utilizing the react-chartjs-2 library to create basic charts in my React project. In an attempt to customize the tooltip, I added a title: tooltips: { callbacks: { label: (tooltipItem, data) => { return tooltipItem?.valu ...

Utilize local .json data within a React component

Here is a snippet from my local .json file: { "results": [ { "id": 1, "title": "2 bedroom apartment to rent", "location": "30 South Colonnade London E14 5EZ", "description": "The building offers a communal lifestyle which co ...

Pattern matching to exclude specific characters

To enhance security measures, I am looking to restrict users from inputting the following characters: ~ " # % & * : < > ? / \ { | } . The key requirement is that all other characters should be permitted, while ensuring that only the sp ...

Obtain environment variables within a Strapi plugin

I am currently working on developing a Strapi local plugin, but I am facing an issue with retrieving variables defined in my .env file located at the root of my project. Specifically, I am trying to access this value within my React component (plugins/myPl ...

Creating a Three-Dimensional Bounding Box in THREE.js

After successfully utilizing the OBB.js in three.js examples to fetch the center, halfSize, and rotation values, the next step is to determine how to calculate the 8 corners of the bounding box based on this information. Additionally, we need to understa ...

Utilizing mp3 files in Webpack 5 with Next.js

After hours of struggling with my current project using [email protected] and webpack v5, I found myself stuck on fixing mp3 loading. Despite trying various solutions from Stack Overflow and GitHub, none seemed to work for me. Type error: Cannot find ...

Looking to transform an HTML table into a stylish CSS layout complete with a form submission button?

Recently, I've been delving into the world of CSS and PHP as I work on converting old code entirely into HTML and PHP with a touch of CSS. The visual aspect seems fine, but I've hit a roadblock with the submit form due to an IF statement in PHP. ...

"Stay current with real-time updates in seconds using React technology

Check out this code snippet: const currentTime = new Date().getTime(); const targetTime = new Date('November 15, 2020').getTime(); const difference = currentTime - targetTime; let seconds = Math.floor(difference / 1000) % 60; setInterval(functio ...

Grails array using jQuery autocomplete with findByAll() function

Hello everyone, I appreciate the assistance in advance! I am currently attempting to utilize Grails findByAll() in order to retrieve a list for use in the jQuery autocomplete feature found at this link: https://jqueryui.com/autocomplete/ I believe I am cl ...