如何使用angular 2+在本地下载PDF?

时间:2018-10-29 12:52:36

标签: angular

当我下载PDF时,它显示在angular 2中下载失败。我只想从我的目录下载pdf。但是此代码不起作用。

<a href="hello.pdf" download> Pdf Download......................... </a>

1 个答案:

答案 0 :(得分:0)

使用HTTP客户端

getImage(parameters: string) {
  return this.httpClient.get(parameters, { responseType: 'blob' });
} 

这应将您的pdf下载到浏览器中。

getImageFromService() {
this.getImage(this.exportUrl).subscribe(
  data => {
    const file = new Blob([data], { type: 'image/png' });
    const filename = 'example.png';
    const e = this.document.createEvent('MouseEvents');
    const a = this.document.createElement('a');

    setTimeout(() => this.loadingExporter = false, 100); // Timeout for better user experiance

    a.download = filename;
    a.href = window.URL.createObjectURL(file);
    a.dataset.downloadurl = ['text/json', a.download, a.href].join(':');
    e.initEvent('click', true, false);
    a.dispatchEvent(e);
  },
  error => {
  });

}