我在ASP.NET MVC应用程序中基于一些代码,从一个下载Excel文件的ASP.NET Web API应用程序生成并下载一些工作代码上的PDF文件。
在工作(Web API / Excel)代码中,当我在页面上创建此html(链接)时:
builder.Append(string.Format("<a href=\"api/deliveryperformance/excel/{0}/{1}/{2}\">{3}</a>", unit, startDateYYYYMMDD, endDateYYYYMMDD, fileBaseName));
...并且用户单击它,此Controller被称为:
[Route("{unit}/{begindate}/{enddate}")]
public HttpResponseMessage Get(string unit, string begindate, string enddate)
{
byte[] excelContents;
string selectStmt = "SELECT BinaryData FROM ReportsGenerated WHERE FileBaseName = @fileBaseName";
string fbn = string.Format("deliveryperformance/{0}/{1}/{2}", unit, begindate, enddate);
using (SqlConnection connection = new SqlConnection(PlatypusWebReportsConstsAndUtils.CPSConnStr))
using (SqlCommand cmdSelect = new SqlCommand(selectStmt, connection))
{
cmdSelect.Parameters.Add("@fileBaseName", SqlDbType.VarChar).Value = fbn;
connection.Open();
excelContents = (byte[])cmdSelect.ExecuteScalar();
connection.Close();
}
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(excelContents)
};
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = string.Format("{0}.xlsx", fbn)
};
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
return result;
}
...成功将Excel文件下载到用户的计算机上。
所以,我在我的MVC应用程序中有尽可能类似的代码来生成和下载这样的PDF文件:
internal static HttpResponseMessage GeneratePDFOfReportFutures()
{
HttpResponseMessage result = null;
futureReports = GetAllFutureReports();
try
{
using (var ms = new MemoryStream())
{
using (var doc = new Document(PageSize.A4.Rotate(), 25, 25, 25, 25))
{
using (PdfWriter.GetInstance(doc, ms))
{
//Open the document for writing
doc.Open();
. . .
doc.Add(titleTable);
. . .
doc.Add(tblHeadings);
. . .
doc.Add(tblRow);
} // foreach
doc.Close();
var bytes = ms.ToArray();
result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(bytes)
};
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = string.Format("{0}.pdf", "test")
};
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
return result;
} // pdfWriter
} // doc
} // memoryStream
} // try
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return result;
} // GeneratePDFOfReportFutures
...我通过Ajax调用从客户端调用:
$("#btnViewList").click(function () {
$.ajax({
type: "GET",
url: '@Url.Action("GeneratePDF", "GenerateScheduledRptsPDF")',
success: function () {
alert('success from btnViewList');
},
error: function () {
alert('error in btnViewList');
}
});
});
在完成详细here的一些问题之后,我已经到了Controller方法运行而没有抛出异常的程度(我看到成功的msg(“来自btnViewList的成功”));但是,没有(PDF)文件下载/写入硬盘。
为什么不呢?