Angular2 显示 PDF [英] Angular2 Displaying PDF

查看:24
本文介绍了Angular2 显示 PDF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an angular2 project with an ASP.Net Web API. I have code to retrieve a file path from my database which goes to a document on my server. I then want to display this document in the browser in a new tab. Does anybody have any suggestions how to do this?

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

I am happy to retrieve the file in either Angular2 (Typescript) or in my API and stream it down.

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

This is my attempt of retrieving it in my API but i cannot work out how to receive it in Angular2 and display it properly:

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;
    }

任何帮助将不胜感激.

非常感谢!!!

推荐答案

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

First of all, you need to set options for your http request - set responseType to ResponseContentType.Blob, use blob() to read response as blob and set its type to 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:

Then, in order to get the file, you need to subscribe to it and you can create new ObjectURL and use window.open() to open PDF in new tab:

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

这篇关于Angular2 显示 PDF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆