在我的服务器端,我使用的是 ASP.NET MVC Web Api,我在其中使用 Crystal 报表生成 PDF 文件并将其导出为 PDF 格式。代码如下:
[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 代码是:
$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 查看器将其打开。通过 Fiddler 查看 HttpResponseMessage 的内容似乎也是正确的。看图:
最佳答案
这个链接对我们帮助很大。下面的解决方案对我很有帮助。 在我们的案例中,离线存储在数据库中的流中:
//Reading the exising pdf file
byte[] bytes = File.ReadAllBytes(pafTemplate);
//gettting memory stream object and writing in to it
var stream = new MemoryStream();
stream.Write(bytes, 0, bytes.Length);
//For our custom need we are placing the memory stream in one of the column
PdfDataTable.PdfFormDataColum = stream.GetBuffer();
Web-API 代码:
[GET("api/pdf/getPdfRecordData/{pdfId}")] //AttributeRouting
public HttpResponseMessage GetPdfRecordData(int pdfId)
{
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, "value");
MemoryStream ms = GetPdfMemoryStreamFromDataBase(pafId);
response.Content = new ByteArrayContent(ms.ToArray());
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
ms.Close();
return response;
}
AngularJs 代码:
$http.get('api/pdf/getPdfRecordData/10', null, { responseType: 'arraybuffer' })
.success(function (data) {
var file = new Blob([data], { type: 'application/pdf' });
var fileURL = URL.createObjectURL(file);
window.open(fileURL);
});
关于javascript - 如何在通过 Http 消息响应内容发送的 javascript 中显示服务器端生成的 PDF 流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21950828/