Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How display pdf in new tab using blob

I have this method in TypeScript/Angular, that generate my file

 imprimir() {

            this.service.emitirAdvertencia({ parametros: [{ name: 'CODIGO', value: 880 }] })
            .subscribe((response) => {
                console.log(response);             
                var fileURL = window.URL.createObjectURL(response);                        

                //this not display my pdf document in a new tab.
                window.open(fileURL, '_blank');

                //this display my document pdf, but in current tab
                window.location.href = fileURL; 
            }, error => {
                console.log(error);
            });
        }

This is my service

emitirAdvertencia(parametros: Object): any {
        parametros['dbenv'] = ApplicationContext.getInstance().getDbenv();
        parametros['usuario'] = ApplicationContext.getInstance().getUser().codigoUsuario;
        parametros['nome_relatorio'] = 'RelAdvertenciaDB';
        var httpOptions = {

            headers: new HttpHeaders({
                'Authorization': this.localStorage.get('token'),
            }),
            responseType: 'blob' as 'blob',
        };
        return this.http.get(ApplicationContext.URL + '/adiantamento/gerar-relatorio/', httpOptions)
            .map((res) => {
                var report = new Blob([res], { type: 'application/pdf' });
                return report;
            });

Like a commented in code, when i try open in a new tab, not works, only works if i open in current tab

How open this blob pdf file in new tab ?

like image 231
Jeterson Miranda Gomes Avatar asked Mar 16 '18 13:03

Jeterson Miranda Gomes


Video Answer


2 Answers

To open file in new Tab, you need to create anchor Element in Typescript and add your file url in href attribute of this element.

In my example service response is as data._body for file blob, you can arrange it as your output response from your service.

var newTab = true;
var inputData = { parametros: [{ name: 'CODIGO', value: 880 }] };

this.service.emitirAdvertencia(inputData).subscribe(
    (data: any) => {
       var contentType = data.headers._headers.get('content-type')[0];
       var blob = new Blob([data._body], { type: contentType });
       var url = window.URL.createObjectURL(blob, { oneTimeOnly: true });
    
       //window.open(url, '_blank', '');
       var anchor = document.createElement('a');
       anchor.href = url;
       if (newTab) {
           anchor.target = '_blank';
       }
       anchor.click();
   },
   error => {
       //TODO
   },
   () => { 
      //TODO 
   }
);
like image 78
Amol Bhor Avatar answered Sep 28 '22 03:09

Amol Bhor


I could make it works like this:

var fileURL = window.URL.createObjectURL(data);
let tab = window.open();
tab.location.href = fileURL;
like image 45
Waseem Khalid Avatar answered Sep 28 '22 03:09

Waseem Khalid