Angular – Open PDF file in new tab

angularangular6typescript

Open PDF file in new tab using Angular 6. I tried this:

Rest controller:

@RestController
@RequestMapping("/downloads")
public class DownloadsController {

    private static final String EXTERNAL_FILE_PATH = "/Users/test/Documents/blacklist_api.pdf";

    @GetMapping("export")
    public ResponseEntity<InputStreamResource> export() throws IOException {
        ClassPathResource pdfFile = new ClassPathResource(EXTERNAL_FILE_PATH);

        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");

        return ResponseEntity.ok().headers(headers).contentLength(pdfFile.contentLength())
                .contentType(MediaType.parseMediaType("application/pdf"))
                .body(new InputStreamResource(pdfFile.getInputStream()));
    }
}

Service:

@Injectable({
  providedIn: 'root'
})
export class DownloadService {

  constructor(private http: HttpClient) {
  }

  exportPdf() {
    return this.http.get(environment.api.urls.downloads.getPdf,  { responseType: 'blob' });
  }
}

Component:

@Component({
  selector: 'app-download',
  templateUrl: './download.component.html',
  styleUrls: ['./download.component.scss']
})
export class DownloadComponent implements OnInit {

  constructor(private downloadService: DownloadService,
              private router: Router,
              private route: ActivatedRoute) {
  }

  ngOnInit() {

  }

  export() {     
     window.open(this.downloadService.exportPdf());
  }
}

HTML code:

<h1 class="title">Export</h1>

<div class="content grid-wrapper">

  <div class="export">
      <button class="btn btn-secondary" (click)="export()">Export</button>
    </div>

</div>

What is the proper wya to implement the Angular service and component in order to open the PDF document into new tab when I click the button?

Can you advice?

Best Answer

you can try

export() {
    this.downloadService.exportPdf();
}

...

exportPdf(){
     window.open(environment.api.urls.downloads.getPdf);
}
Related Topic