How to display a PDF in Angular 6 using a byte array retrieved from a WebAPI

Having trouble opening a PDF from byte array sent by WebAPI.

This is my Service:

fetchPdfDocument(): Observable<any> {
        return this.httpClient
            .get(this.configuration.serverUrl + this.configuration.getPdfDoc, {
                responseType: "arraybuffer" //tried with 'blob'
            });
}

And here's what I have in my component:

this.service.fetchPdfDocument()
        .subscribe(data => {
            var file = new Blob([data], { type: 'application/pdf' });   
            this.pdfContent = URL.createObjectURL(file);
            window.open(this.pdfContent);
        })

However, when I run it, the PDF document fails to load. I've enabled pop-ups but still no luck...

Link to Image

Answer №1

Check out the following code snippet:

service:

getPdfDocument(): Observable<any> {
    let headers = new HttpHeaders({ 'Content-Type': 'application/JSON' });
    return this.httpClient
               .get(this.configuration.serverUrl + this.configuration.getPdfDoc,
                    { headers: headers, responseType: 'blob', observe: 'response' }
                });
        }

request:

this.service.getPdfDocument()
        .subscribe(
                (data) => {
                    this.openFileForPrint(data);
                });

openFileForPrint(data: HttpResponse<any>) {
        let fileUrl = window.URL.createObjectURL(data);
        window.open(fileUrl, '_blank', 'location=yes,height=600,width=800,scrollbars=yes,status=yes');
    }

Server side

[HttpGet]
public HttpResponseMessage getpdf(DateTime datum, int idlokacija)
{
    var r = _printService.getdata(datum, idlokacija);
    if (r == null)
    {
        return new HttpResponseMessage(HttpStatusCode.NotFound);
    }
    return SendPdfFile(r);
}

public static HttpResponseMessage SendPdfFile(string filePath, bool brisanje = true)
{
    var stream = new FileStream(filePath, FileMode.Open);
    HttpResponseMessage response = new FileHttpResponseMessage(filePath, brisanje)
    {
        StatusCode = HttpStatusCode.OK,
        Content = new StreamContent(stream)
    };
    response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
    return response;
}

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

Alter the language settings of the Datepicker feature in Material Angular 4

Need help changing the language of Datepicker in Material Angular. Struggling to locate this information in the Angular material 2 documentation. Check out this plunkr https://plnkr.co/edit/unzlijtsHf3CPW4oL7bl?p=preview <md-input-container> < ...

Navigating using Javascript library in Angular 2 framework

I am currently utilizing Parse, an external JS library, within Angular JS 2. Nevertheless, I am encountering issues when attempting to call the function gotoMain() from within a callback function of Parse. It appears that certain elements are not being l ...

What is the best way to display a Nested JSON structure without an object key?

Need help with extracting data from two different JSON structures. The first one is straightforward, but the second is nested in multiple arrays. How can I access the content? See below for the code snippets: // First JSON { "allSuSa": [ { ...

Visual Studio 2015 is struggling to locate a specific module, yet the command line interface for

Recently, I delved into the world of TypeScript in VS2015 and so far, it has been a smooth journey. I managed to establish a structure that compiled and performed as anticipated. However, things took a turn when I attempted to incorporate npm-installed mo ...

Encapsulate the module function and modify its output

I am currently utilizing the node-i18n-iso-countries package and I need to customize the getNames function in order to accommodate a new country name that I wish to include. At the moment, I am achieving this by using an if-else statement like so: let cou ...

Utilizing WebDriver for creating distinct driver profiles for Chrome and Internet Explorer browsers

When working on my project, I need specific cookies to access the application. Currently, for Firefox Driver, I am using a Firefox profile that I also use for manual testing as it contains all the necessary cookies. However, I am unsure how to achieve th ...

Can we incorporate 'this' in the super() constructor?

While reviewing someone else's code, I came across the following snippet: class foo extends bar { constructor() { super(param1, param2, new certainObject(this, otherParams)); } } The issue with this code is that it generates an error ...

Auto-complete feature not populating the input field in Google Chrome

Within my register form, I have various INPUT tags present. One of these INPUTs has the name email. <input type=text name=email id=email> When filling out this form in Chrome, I encounter a peculiar behavior. Upon clicking on the email input field ...

Utilizing two DTOs for a single controller in NestJS

I'm having trouble retrieving and transforming different types of dtos from the body. My goal is to extract and transform firstDto if it's incoming, or convert secondDto if that's what's being received. However, my current code isn&apos ...

TypeORM: When generating a migration, a SyntaxError is thrown stating that an import statement cannot be used outside a

While configuring TypeORM in my NextJS TypeScript project, I encountered an issue where I received the error message: SyntaxError: Cannot use import statement outside a module when attempting to create migrations for my entities. ...

What are the steps for incorporating a Zoom & Pan feature into an anyChart SeatMap?

In our IONIC application, we are utilizing the anyChart SeatMap to display SVG-based seatmaps. However, some of the seatmaps are quite large and we require support for zooming and panning functionalities. Despite researching the 'Move & Zoom' opt ...

The error message indicates a change in the binding value within the template, resulting in an

This is the structure of my component A : <nb-tab tabTitle="Photos" [badgeText]="centerPictures?.pictures?.length" badgePosition="top right" badgeStatus="info"> <app-center-pictures #centerPictures [center]="center"> ...

ModalComponent dependency not provided

I am new to working with Angular, so please bear with me if this question seems basic. In our application, all forms are displayed in a popup. Within the header section, we have multiple tabs and I need the component to load when a tab is clicked. Can you ...

Is it possible to generate a Date object from a predetermined string in typescript?

I have a string with values separated by commas, and I'm trying to create a Date object from it. It seems like this is not doable -- can someone verify this and provide a solution if possible? This code snippet doesn't work : let dateString=&a ...

The module '@/assets/icons/pay/pay-success.png' cannot be located, along with its corresponding type declarations.ts

Recently, I encountered an issue while trying to import a png image in my Typescript code. Here is the snippet of code that caused the error: import paySuccessIcon from "@/assets/icons/pay/pay-success.png"; When I tried to import the image, Visual Studio ...

The issue of the Angular service being consistently undefined arises when it is invoked within an

I have already researched numerous other SO questions, but none of the solutions worked for me. My goal is to implement an async validator that checks if a entered username already exists. However, every time I type a letter into the input field, I encoun ...

The one-tap login popup from Google always appears, even when the user is already logged in

Blocking Google's One Tap Login Popup in Angular 16 Is there a way to prevent Google's one tap login popup from appearing when the user is already logged in? Every time I refresh the page or save changes in the code (auto reload), the login popu ...

Unable to transfer data through Ionic popover

I've encountered an issue when trying to pass data to my popover component, as the data doesn't seem to be sent successfully. Code HTML <div class="message" id="conversation" *ngFor="let message of messages.notes"> <ion-row class= ...

Looking for recommendations on the best tools to use for starting an Angular 2 project?

After successfully creating an Angular 2 web app on my computer, I encountered a problem when trying to build it for production. Instead of using my project files, angular-cli generated a "Hello World" app. The confusion arose because I was initially using ...

What is the best way to incorporate cors modules in TypeScript?

I am encountering some difficulties while attempting to import the cors module in a TypeScript project using Express. When I use the following code: import cors from "cors"; I receive the following error message: "Cannot find module &apos ...