[英]Create PDF server side and open in new browser window or tab
我正在尝试在服务器上创建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();
}
});
您将返回生成的PDF的Base-64编码表示,然后使用该字符串创建链接并设置href内联。 然后,您触发对链接的单击。 似乎很复杂。
我会采取不同的方法...
让服务器返回PDF字节(我假设PdfWriter可以访问byte []):
public ActionResult CreateCustomReport()
{
byte[] contents = doc.GetBytes(); //?????
return File(contents, "application/pdf", "test.pdf");
}
然后,不要使用AJAX调用,而是将用户重定向到url:
<a href="@Url.Action("CreateCustomReport")" target="_blank">Download PDF</a>
这种方法不依赖JavaScript,并且可以在IE或Chrome上运行,而不会提示用户下载/保存文件。 PDF将显示在新的浏览器窗口/标签中。
Nava的答案不能解决OP的问题,因为它仍然下载文件,而不是在新选项卡中打开文件。 您需要修改响应标头才能实现。
public FileResult CreateCustomReport()
{
...
Response.AppendHeader("Content-Disposition", "inline; filename=Out.pdf");
return File(m.ToArray(), "application/pdf" );
}
然后您认为:
<a href="@Url.Action("CreateCustomReport")" target="_blank">Download PDF</a>
如果要在单击后隐藏下载链接,则只需在锚点上添加onclick
即可:
<a href="@Url.Action("CreateCustomReport")" target="_blank" onclick="this.style.display='none'">Download PDF</a>
编辑:我无法评论其他答案,但是从您的评论中读取似乎您需要通过POST请求传递参数。 如果确实需要通过POST进行此操作,则可以使用隐藏的表单和target="_blank"
属性。 如果可以通过GET进行操作,则可以将数据嵌入到URL中,然后可以使用简单的定位标记。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.