Extracting PDF files using API within Angular services

I have set up a Java-based API on a server, with the URL being "ex.com".

This API has an endpoint that returns a PDF file, with the URL set as "ex.com/pdf".

For this endpoint, a POST request is required with a parameter specifying the requested PDF, like so: params = { location: "report.pdf"}.

My goal is to use Angular's Http.post observable to retrieve the PDF file. However, I keep encountering an HttpErrorResponse with the message "Http failure during parsing for http://ex.com/pdf... Unexpected token % in JSON at position 0 at JSON.parse". Since the response is a PDF, I don't want it to be parsed as JSON.

Here is the code I am currently using:

params = {location: "report.pdf"};
return this.http.post<Response>("http://ex.com/pdf", params)
    .subscribe(
         data => {
            var file = new Blob([data], {type: 'application/pdf'});
            var fileURL = URL.createObjectURL(file);
            window.open(fileURL);
         }
     );

I have confirmed that the endpoint works correctly with Postman, as I am able to successfully use the "Send and Download" option to obtain the PDF file. I just need to figure out how to achieve the same result within Angular. Any help would be greatly appreciated.

Answer №1

Here's a suggestion for your issue.

To start, make sure to install the file-saver node package by running npm install --save file-saver.

Next, you can try something similar to the code snippet below. This is what I used for a similar task:

public downloadPDF(): any {
    var mediaType = 'application/pdf';
    this.http.post(this.myUrl, {location: "report.pdf"}, { responseType: 'blob' }).subscribe(
        (response) => {
            var blob = new Blob([response], { type: mediaType });
            saveAs(blob, 'report.pdf');
        },
        e => { throwError(e); }
    );
}

This solution worked for me in saving the file as needed.

If you give it a try, let me know how it goes!


UPDATE - ANGULAR7 & FILESAVER V.^2.0.1+


I recently updated my Angular app from version 6 and Filesaver version below 2.0.1 (not sure of the exact version).
In the new version, remember to change the import statement from:

import { saveAs } from 'file-saver/FileSaver';

to

import { saveAs } from 'file-saver';

All other aspects should function the same as in the previous version!

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

Securing Your Next.js Web App with Session Authentication

I have encountered a challenge while integrating NextAuth authentication into my React.js web application. To ensure seamless user authentication across the entire app, I am attempting to wrap a SessionProvider around the root component. However, VSCode ...

TS - Custom API hook for making multiple API requests - incompatible type with 'IUseApiHook'

What is my objective? I aim to develop a versatile function capable of handling any type of API request for a frontend application. Essentially, I want to add some flair. Issue at hand? I find myself overwhelmed and in need of a fresh perspective to revi ...

classes_1.Individual is not a callable

I am facing some difficulties with imports and exports in my self-made TypeScript project. Within the "classes" folder, I have individual files for each class that export them. To simplify usage in code, I created an "index.ts" file that imports all class ...

Strategies for efficiently loading 100,000 records into a table using Spring Boot on the server side and Angular on the front end

I am facing an issue with the speed of loading data from the back end to the front end without causing delays on the client side. I am using Spring Boot for the back end and Angular 7 for the front end. The problem arises when I submit a request from the f ...

What factors should I consider when determining whether to include @types/* in the `dependencies` or `devDependencies` section?

Currently using TypeScript 2 in my project, I am looking to incorporate a JavaScript library along with its typings. While I know I can easily install the types using npm install @types/some-library, I am uncertain whether to use --save or --save-dev. The ...

Error in Typescript: Array containing numbers is missing index property `0`

This is the code for my class: class Point{ coordinates: [number, number, number]; constructor(coordinates: [string, string, string]) { this.coordinates = coordinates.map((coordinate) => { return Math.round(parseFloat(coordinate) *100)/ ...

What is the best way to transform an array containing double sets of brackets into a single set of brackets?

Is there a way to change the format of this list [[" ", " ", " ", " ", " ", " ", " ", " ", " ", " "]] to look like [" ", " ", " &qu ...

What are the steps to set up tsline in settings.json file?

Currently utilizing visual studio code Upon searching for the settings.json file, the contents appear as follows: { "liveServer.settings.donotVerifyTags": true, "liveServer.settings.donotShowInfoMsg": true, "javascript ...

Associate a unique identifier string with a randomly generated integer identifier by Agora

For my current web project, I am utilizing a String username as the UID to connect to the channel in an Agora video call. However, I now need to incorporate individual cloud recording by Agora into the project. The challenge lies in the fact that cloud r ...

Why does Material-UI's "withStyles()" not function properly with a specified constructor in Typescript?

Update: Please note that there was an issue with the constructor generated by IntelliJ IDEA, but it has been fixed. You can find more details here: I'm exploring the use of Material-UI in my application, and I've encountered some challenges wit ...

Do Prisma Migrations Require a Default Value?

I'm struggling with Prisma data modeling and have tried almost everything to resolve an error I keep getting. The error states that the table needs a default value even though I have already assigned it an ID. I attempted to remove the relation name, ...

How can I create an input field in MUI that restricts input to letters, numbers, and dashes

Is there a way to configure an MUI input field so that it only accepts letters, numbers, and dashes while excluding spaces and symbols such as (*&^%$#@!,.<>{}[])? Specifically, I want to allow characters that wouldn't disrupt a URL, like . Tha ...

Enhance filtering capabilities in FormGroup with an autocomplete input feature for more options

Seeking to implement a basic autocomplete textbox that allows selection from a filtered list of objects displayed by name. For instance, with an array of Country objects containing properties like countryName, countryCode, and countryId, the goal is to fi ...

It is not possible to install Angular CLI on a Mac computer

My Mac computer is currently running macOS Ventura 13.1 I managed to install node (v18.12.1) & npm (8.19.2) successfully on the system. However, when I attempted to run npm install -g @angular/cli to install Angular CLI, it resulted in the following e ...

Assets failing to duplicate during ng build in production

Currently, I'm developing an application using Angular 4. I recently added a new SVG image to the assets/images folder and made the necessary changes in the angular-cli.json file as well. When I run 'ng build' locally, it successfully copies ...

What is the best way to access the highest level form control within a validator function of a nested form group?

Is there a way to access the complete form within a validator function? I attempted using control.parent.parent, but it resulted in an error. private unitNumberValidator(hasMdu){ return (control: AbstractControl)=>{ let returnVal = null; //I need ...

The CORS policy is causing a blockage for the front-end application due to the Spring Boot backend

Currently working with Spring Boot and Angular. I have included the cross-origin annotation in my code to allow access from my Angular localhost port, but unfortunately, I am still encountering the following error: https://i.sstatic.net/4uDuv.png Here is ...

Developing new Azure AD users through Angular using MSAL.js

Is it feasible, from the perspective of Web Applications, for a user to create an Azure AD account by inputting their email, name, phone number, and other details that can then be forwarded to Azure AD through the web application? I am currently exploring ...

Include a bank account for connecting to Stripe custom accounts

Currently, I am implementing Stripe Connect using Node.js and TypeScript for a platform that facilitates payments for third-party services referred to as "partners." Our decision to utilize Stripe Connect's custom accounts gives us complete control ov ...

What are the compatibility considerations for npm packages with Angular 2? How can I determine which packages will be supported?

When working with Angular 2, do NPM packages need to be modified for compatibility or can any existing package work seamlessly? If there are compatibility issues, how can one determine which packages will work? For instance, let's consider importing ...