Angular2显示PDF [英] Angular2 Displaying PDF

查看:171
本文介绍了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()将响应读取为,并将其类型设置为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天全站免登陆