如何在JavaScript中显示服务器端生成的PDF流,通过HttpMessageResponse发送内容 [英] How to display a server side generated PDF stream in javascript sent via HttpMessageResponse Content
问题描述
在我的服务器端我使用ASP.NET MVC Web Api,其中我生成PDF文件与水晶报表,并将其导出为PDF格式。代码如下:
On my server side I am using ASP.NET MVC Web Api, where I am generating the PDF file with Crystal report and exporting it to PDF format. The code goes as follows:
[HttpPost]
public HttpResponseMessage SetReport(string name, [FromBody]List<KontoDto> konta)
{
var response = Request.CreateResponse(HttpStatusCode.OK);
var strReportName = "KontoReport.rpt";
var rd = new ReportDocument();
string strPath = HttpContext.Current.Server.MapPath("~/") + "Reports//" + strReportName;
rd.Load(strPath);
rd.SetDataSource(konta);
var tip = ExportFormatType.PortableDocFormat;
var pdf = rd.ExportToStream(tip);
response.Headers.Clear();
response.Content = new StreamContent(pdf);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
return response;
}
我的Javascript代码是:
My Javascript code is:
$scope.xxprint = function () {
console.log($scope.konta);
$http.post('/api/konto/setReport/pdf', $scope.konta, { responseType: 'arraybuffer' })
.success(function (data) {
var file = new Blob([data], { type: 'application/pdf' });
var fileURL = URL.createObjectURL(file);
window.open(fileURL);
});
};
这根本不起作用。我不知道这个代码有什么问题。我得到浏览器打开pdf查看器,但它是空的。此外,创建的pdf正确创建,因为我可以将其保存到磁盘,然后使用Adobe Acrobat查看器打开它。 HttpResponseMessage的内容似乎也通过Fiddler正确查看。查看图片:
This simply does not work. I don't know what's wrong with this code. I get the browser to open the pdf viewer, but it is empty. Also, the created pdf is correctly created as I can save it to disk and open it then with Adobe Acrobat viewer. The content of the HttpResponseMessage seems also correct viewed via Fiddler. See image:
推荐答案
似乎我做的一切正常。问题是我的angularjs版本(v1.08)。当升级到v1.2一切工作确定。在v1.08中, responseType:'arraybuffer'
paramater(这对我的工作至关重要)被angularjs忽略了。它似乎是从v.1.1实现。请参阅此SO问题:如何在AngularJS中读取二进制数据在ArrayBuffer中?
Seems I did it correctly all the time. The problem was with my angularjs version (v1.08). When upgrading to v1.2 everything worked ok. In v1.08 the responseType: 'arraybuffer'
paramater (which is crucial to what I was doing) was simply ignored by angularjs. It seems to be implemented as of v.1.1. See this SO question: How to read binary data in AngularJS in an ArrayBuffer?
这篇关于如何在JavaScript中显示服务器端生成的PDF流,通过HttpMessageResponse发送内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!