【发布时间】:2016-07-19 02:49:31
【问题描述】:
我正在尝试在服务器上创建 PDF,然后在单击按钮时在浏览器的新选项卡中打开它。 PDF 生成良好,但我无法让浏览器在不下载的情况下打开它。在 IE 中它无法识别该文件,而在 Chrome 中它会提示用户下载。任何帮助表示赞赏。我的代码如下:
C# 控制器
public string CreateCustomReport()
{
var doc = new Document();
MemoryStream m = new MemoryStream();
try
{
string query = "";
PdfWriter.GetInstance(doc, m).CloseStream = false;
SqlConnection conn = new SqlConnection(conn);
conn.Open();
SqlCommand cmd = new SqlCommand(query, conn);
cmd.CommandType = CommandType.Text;
SqlDataReader sqdr = cmd.ExecuteReader();
doc.Open();
PdfPTable table = new PdfPTable(4);
PdfPCell cell = new PdfPCell(new Phrase(customTitle));
cell.Colspan = 4;
table.AddCell(cell);
table.AddCell(groupBy);
table.AddCell(col1);
table.AddCell(col2);
table.AddCell("Event");
while (sqdr.Read())
{
table.AddCell(Convert.ToString(sqdr["GroupBy"].ToString()));
table.AddCell(Convert.ToString(sqdr["Col1"].ToString()));
table.AddCell(Convert.ToString(sqdr["Col2"].ToString()));
table.AddCell(Convert.ToString(sqdr["Events"].ToString()));
}
doc.Add(table);
doc.Close();
}
catch (Exception)
{
}
return System.Convert.ToBase64String(m.ToArray());
}
jQuery
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(params),
url: '@Url.Action("CreateCustomReport")',
error: function(error) {
debugger;
alert("Search failed.");
},
success: function(data) {
var openpdf = $('<a id="openpdf" download="Report.pdf" href="data:application/pdf;base64,' + data + '" target="new">');
$('body').append(openpdf);
document.getElementById("openpdf").click();
$("#openpdf").remove();
}
});
【问题讨论】:
标签: c# jquery asp.net-mvc pdf itextsharp