【问题标题】:Angular2 Displaying PDFAngular2显示PDF
【发布时间】:2017-03-11 01:28:13
【问题描述】:

我有一个带有 ASP.Net Web API 的 angular2 项目。我有代码可以从我的数据库中检索文件路径,该文件路径会转到我服务器上的文档。然后,我想在浏览器中的新选项卡中显示此文档。有人对如何做到这一点有任何建议吗?

我很高兴在 Angular2 (Typescript) 或我的 API 中检索文件并将其流式传输。

这是我在我的 API 中检索它的尝试,但我无法弄清楚如何在 Angular2 中接收它并正确显示它:

public HttpResponseMessage GetSOP(string partnum, string description)
    {
        var sopPath = _uow.EpicorService.GetSOP(partnum, description).Path;
        HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
        var stream = new FileStream(sopPath, FileMode.Open);
        result.Content = new StreamContent(stream);
        result.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
        return result;
    }

任何帮助将不胜感激。

非常感谢!!!

【问题讨论】:

  • 如果你想在另一个标签页中看到它,为什么不打开一个新标签页到 API 的 URL 并让浏览器解释内容呢?您可能需要使用 mime 类型的“application/pdf”而不是“application/octet-stream”。
  • 我在这里写了关于在 Angular 2 的新选项卡中获取和显示 pdf 文件的文章,查看我的答案:stackoverflow.com/questions/37046133/…
  • @StefanSvrkota 可以按原样与我的 API 一起使用吗?还是我需要进行更改才能以正确的格式返回它?
  • 我不确定,试试看。我可以稍后告诉您我的 API 的外观。
  • 好的,我只是在实施它,我会让你知道 :)

标签: pdf angular asp.net-web-api filestream


【解决方案1】:

首先,您需要为您的 http 请求设置选项 - 将 responseType 设置为 ResponseContentType.Blob,使用 blob() 将响应读取为 blob 并将其类型设置为 application/pdf

downloadPDF(): any {
    return this._http.get(url, { responseType: ResponseContentType.Blob }).map(
    (res) => {
            return new Blob([res.blob()], { type: 'application/pdf' })
        }
}

然后,为了获取文件,您需要subscribe 到它,您可以创建新的ObjectURL 并使用window.open() 在新选项卡中打开 PDF:

this.myService.downloadPDF().subscribe(
        (res) => {
        var fileURL = URL.createObjectURL(res);
        window.open(fileURL);
        }
    );

【讨论】:

  • 嗨,Stefan。它显示我无法加载 PDF 文档。请帮助我。我正在使用 Angular4。
  • 我可以下载但无法在新的浏览器标签中显示。
  • return new Blob([res.blob()] 拯救了我的一天,谢谢
  • 如果您使用广告拦截器扩展程序,请小心。默认情况下,广告拦截器会阻止 blob URL。结果,例如在 Chrome 和 Firefox 中,使用 uBlock Origin 扩展程序,它会尝试打开新窗口并自动关闭它。你可以在这里阅读更多信息:stackoverflow.com/questions/51272781/…
  • 另外,如果您也关心在 IE 中的工作,请阅读:stackoverflow.com/questions/24007073/…
【解决方案2】:

Angular v.5.2.1 答案:

*.services.ts

downloadPDF(): any {
    return this._httpClient.get(url, { responseType: 'blob'})
            .map(res => {
            return new Blob([res], { type: 'application/pdf', });
        });
  }

然后在*.component.ts

downloadPDF() {
    let tab = window.open();
    this._getPdfService
      .downloadPDF()
      .subscribe(data => {
        const fileUrl = URL.createObjectURL(data);
        tab.location.href = fileUrl;
      });
  }

在调用服务之前启动并打开一个新标签很重要。然后将此选项卡 url 设置为 fileurl。

【讨论】:

  • 为什么在调用服务之前打开选项卡而不是使用objecturl作为参数打开它很重要(如所选答案所示)?
  • @PauFracés 因为您没有“被允许”以“编程方式”打开选项卡,只允许用户打开选项卡,因此您必须启动一个尽可能接近用户交互的新选项卡当用户单击然后调用downloadPDF() 的按钮时发生。订阅内部离用户交互太远了。
  • 我收到错误无法加载 PDF 文档。
  • @jonas 你能看看这个问题。我有一个类似的问题:stackoverflow.com/questions/55070184/…
【解决方案3】:

角度 5

我遇到了同样的问题,我为此丢了几天。

在这里我的回答可能会帮助其他人,这有助于呈现 pdf。

对我来说,即使我提到 responseType : 'arraybuffer',它也无法接受。

为此,您需要提及 responseType : 'arraybuffer' as 'json'.(Reference)

工作代码

service.ts

downloadPDF(): any {
return this._httpClient.get(url, { responseType: 'blob' as 'json' })
        .map(res => {
        return new Blob([res], { type: 'application/pdf', });
    });

}

component.ts

this.myService.downloadPDF().subscribe(
    (res) => {
    var fileURL = URL.createObjectURL(res);
    window.open(fileURL);
    }
);

参考以下链接

https://github.com/angular/angular/issues/18586

【讨论】:

【解决方案4】:

Angular 2+ 示例 PDF 查看器

页面.html

<div class="container">
<div>
    <label>PDF src</label>
    <input type="text" placeholder="PDF src" [(ngModel)]="pdfSrc">
</div>
<div>
    <label>Page:</label>
    <input type="number" placeholder="Page" [(ngModel)]="page">
</div>
<div class="row">
    <div class="col-md-5">
        <div class="thumbnail" style="width: 150px;height: 200px;" (click)="pdfShow=!pdfShow">
            <p>click me to view PDF in Iframe!</p>
            <pdf-viewer [src]="pdfSrc"
                        [page]="page"
                        [original-size]="false"
                        style="display: block;"
             ></pdf-viewer>
        </div>
        <br>
    </div>
    <div class="col-md-7">
        <div *ngIf="!pdfShow">
            <h4>PDF in Iframe</h4>
            <iframe width="500" height="600" [src]="pageurl" type="application/pdf"></iframe>
        </div>
    </div>
</div>
<br><br>
<h2> PDF in Object Tag</h2>
<object width="500" height="600"  data="https://vadimdez.github.io/ng2-pdf-viewer/pdf-test.pdf" type="application/pdf"></object>

page.ts

import { Component } from '@angular/core';
import { BrowserModule, DomSanitizer, SafeResourceUrl } from '@angular/platform- 
browser'

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
 })
 export class AppComponent {

  pdfSrc = 'https://vadimdez.github.io/ng2-pdf-viewer/pdf-test.pdf';
  page: number = 1;
  pageurl: SafeResourceUrl;

  constructor(private domSanitizer: DomSanitizer) {
     }
      ngOnInit() {
      this.pageurl = this.domSanitizer.bypassSecurityTrustResourceUrl(this.pdfSrc);
     }
     title = 'Mohsen';
     }

app.module.ts

添加

import { FormsModule } from '@angular/forms'; 
import { PdfViewerComponent } from 'ng2-pdf-viewer';
import { HttpModule } from '@angular/http';.
import {HttpClientModule} from '@angular/common/http';
import { BrowserModule } from '@angular/platform-browser';

导入

imports: [
    BrowserModule,
    HttpClientModule,
    HttpModule,
    FormsModule,
    RouterModule.forRoot(appRoutes)
],

【讨论】:

    猜你喜欢
    • 2017-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-04
    • 2016-10-21
    相关资源
    最近更新 更多