微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

我们如何以角度从外部网址下载 pdf?

如何解决我们如何以角度从外部网址下载 pdf?

我尝试使用文件保护模块,但它在新页面中打开 URL 而不是下载。这是我使用的片段。有人能帮我解决这个问题吗?

this.pdfurl = "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf";
const blob = new Blob([this.pdfurl],{type:'applicaton/pdf'})
fileSaver.saveAs(this.pdfurl,"download.pdf");

解决方法

这对我有用:

rest.service.ts

@Injectable()
export class RestService {

  constructor(private httpClient: HttpClient) {
  }

  public downloadPdf() {
    return this.httpClient.get(`https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf`,{
      responseType: 'arraybuffer',headers: new HttpHeaders().append('Content-Type','application/pdf'),});
  }
}

Service 的使用(例如在组件的 TS 内部):

this.restService.downloadPdf().subscribe((response: ArrayBuffer) => download(response,'application/pdf','download.pdf'))

下载.function.ts

export function download(binaryData: ArrayBuffer,fileType: string,fileName: string): void {
  const file: Blob = new Blob([binaryData],{type: fileType});
  const url: string = window.URL.createObjectURL(file);
  const anchorElement: HTMLAnchorElement = document.createElement('a');
  anchorElement.download = fileName;
  anchorElement.href = url;
  anchorElement.dispatchEvent(new MouseEvent('click',{bubbles: true,cancelable: true,view: window}));
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。