如何在AngularJS中处理来自Web API的PDF文件?

dhr*_*hrm 8 asp.net-web-api angularjs

我有这个Web APIpost方法来生成PDF:

[HttpPost]
[Route("api/pdf")]
public HttpResponseMessage Post(CustomType type)
{
    StreamContent pdfContent = PdfGenerator.GeneratePdf();

    HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
    response.Content = pdfContent;
    response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
    response.Content.Headers.ContentDisposition.FileName = "PDFName.pdf"

    return response;
}
Run Code Online (Sandbox Code Playgroud)

在AngularJS中我想得到这样的PDF文件:

$http.post("api/pdf", object).then(function (results) {
    var data = results.data;

    //TODO: got PDF, how to handle?

}, function (results) {
    console.log(results);
});
Run Code Online (Sandbox Code Playgroud)

但是我应该如何处理AngularJS中的PDF数据?在iPad上,我希望PDF能够打开,但如果文件被下载或只是在桌面上打开并不重要.

EDIT1:

使用SaveAS JS库我可以在桌面上创建一个可行的解决方案:

$http.post("api/pdf", object).then(function (results) {
    var data = results.data;

    var file = new Blob([data], { type: 'application/pdf' });
    saveAs(file, "test.pdf");

}, function (results) {
    console.log(results);
});
Run Code Online (Sandbox Code Playgroud)

该文件正在直接下载到我的桌​​面,但由于某些原因,此解决方案无法在iOS中运行.什么都没发生.看到这个JSFiddle.

有没有其他方法可以在我的iPad上显示PDF而无需将文件嵌入我的网站?

Man*_*ube 3

您很可能知道,iOS 设备不会让您像在台式机/笔记本电脑上那样下载文件并将其存储到内存/磁盘中。

Downloaded items must be opened by an app

As you are already working on an website, the browser seems a natural candidate.


As I surmise you do not wish to embed the pdf file inside your website, an alternative would be to open the pdf in a new browser tab.

If such a solution is acceptable for you, please check this SO post:

window.open() in an iPad

The provided solution does work, but only when Safari is configured so as not to block popups.


I am afraid this may well be the only viable option for you. Having the iPad store the pdf into apps like iBooks will not work, according to this post. It cannot be automated with javaScript.


To my knowledge, there is no perfect solution in this case, just a most acceptable solution: open the pdf in a new tab in the browser, if ios has been detected.

If you are interested in this compromise, and run into issues implementing it with window.open(), I'll be happy to help.