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

Testing the React context value with React testing library- accessing the context value before the render() function is executed

In my code, there is a ModalProvider that contains an internal state managed by useState to control the visibility of the modal. I'm facing a dilemma as I prefer not to pass a value directly into the provider. While the functionality works as expecte ...

The Material Angular components fail to load

Just started a brand new project using Angular and Material design UPDATE : Check out the live editor on StackBlitz: here Working on implementing the toolbar example, but here's what I have so far: Tried inserting the sample code into the app.compo ...

Encounter the "Error: Source 'cloudsTileLayer-RasterSource' not found" message while trying to integrate a weather tile layer into Azure Maps

I have been working on a React application that utilizes the React-Azure-Maps npm package. My current challenge involves creating a weather layer, which I believe shares similarities with the sample code provided for layers. The code snippet responsible f ...

Is there a way to transform time into a percentage with the help of the moment

I am looking to convert a specific time range into a percentage, but I'm unsure if moment.js is capable of handling this task. For example: let start = 08:00:00 // until let end = 09:00:00 In theory, this equates to 100%, however, my frontend data ...

Testing a callback function within a method in Angular

I am currently working with Angular 11 using TypeScript and I am unsure how to properly test scenarios where an exception is raised within my method. myMethod() { this.myService.callBackend(id).subscribe(() => { // do something when success ...

Identifying Gmail line breaks in the clipboard using Angular

I'm currently working on a feature that allows users to paste content from Gmail into a field and detect line breaks. The field doesn't have to be a text area, I just need to identify the line breaks. However, there seems to be an issue with det ...

Navigating the complexities of applying CSS exclusively to child grids within Kendo Angular may seem challenging at first

This image illustrates the grid layout I have created an angular UI using kendo that features a nested grid. I am trying to apply CSS specifically to the child grid without affecting the parent grid. However, no matter what CSS I write, it ends up being a ...

Execute tap() function without subscribing

Can the tap() pipe function be executed without subscribing to it? observer$:BehaviorSubject<number[]> = new BehaviorSubject<number[]>([1]) getData(page:number):void{ of(page).pipe( tap({ next: (data) => this.observe ...

Display the content of an md-dialog with a scroll bar

I am experiencing a problem with printing a long report created using md-list displayed in a md-dialog. When I attempt to print it, only the section that is currently visible on the screen gets printed instead of the entire length of the md-list. I have at ...

Developing an Angular 11 Web API Controller with a POST Method

I am in need of creating or reusing an object within my web API controller class to send these 4 variables via a POST request: int Date, int TemperatureC, int TemperatureF, string Summary Currently, I am utilizing the default weather forecast controller t ...

Choosing the default drop-down option in Angular based on a falsy value

Within this template, the "Select Military Status" choice will be selected if the underlying model.militaryStatus property is null. <select [(ngModel)]="model.militaryStatus"> <option [ngValue]="null">Select Military Status</option> ...

Creating a universal wrapper function to serve as a logging tool?

Currently, I am working on a generic JS function that can wrap any other function. The purpose of this wrapper is to execute the wrapped function, log the input and output events, and then return the output for "transparent" logging. However, as I attempt ...

Navigating through a React application with several workspaces - the ultimate guide

Currently, I am working on implementing a monorepo setup inspired by this reference: https://github.com/GeekyAnts/nativebase-templates/tree/master/solito-universal-app-template-nativebase-typescript In this repository, there are 4 distinct locations wher ...

Having trouble with VueJS ref not preventing the default form action on submit?

Within my <script> tag, I currently have the following code: render(createElement) { return createElement("form", {ref: "formEl" , on: {submit: this.handleSubmit} }, [ <insert create form inputs here> ]); } handleSubmit(e) { ...

Is it possible to include a component in an HTML file when the constructor of the component needs a parameter?

Recently delving into the world of AngularJs has been a captivating experience for me. I am aiming to develop a component with a constructor that accepts a parameter of type string. However, when I try to declare the selector on the HTML file, the componen ...

Add one string to an existing array

I have a component named ContactUpdater that appears in a dialog window. This component is responsible for displaying the injected object and executing a PUT operation on that injected object. The code for the component is shown below: HTML <form [for ...

Ways to delete a class in typescript

There's a menu on my website with li tags containing an a element for navigation. Everything is working fine, but I'm facing an issue where I need to remove all elements with the class seleccionado and only add it to the clicked li. I tried using ...

What could be causing my Angular2 component to not properly use my template?

I have two components that I am working with. The first component is: import {Component} from 'angular2/angular2'; import {Navbar} from './navbar'; @Component({ selector: 'app' template: `<div class="col-md-12"> ...

Enhancing keyboard accessibility with the spacebar for radio buttons and check boxes in Angular 2

I am currently working on a form in Angular 2 that includes radio buttons and checkboxes. When tabbing through the fields, they are highlighted properly. However, I am facing an issue with the radio buttons - I want them to be selected when I hit the space ...

Is it possible to ensure that all values from a specific type are represented in an enum collection?

I have a Prisma enum that I've defined (not in TypeScript), and I'm curious if it's possible to synchronize a TypeScript String enum with the generated Type from the Prisma Client. Here are the key details: export const GroupInvitationSta ...