【问题标题】:Create PDF server side and open in new browser window or tab创建 PDF 服务器端并在新的浏览器窗口或选项卡中打开
【发布时间】: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


    【解决方案1】:

    您将返回生成的 PDF 的 Base-64 编码表示,然后使用该字符串创建链接并设置 href 内联。然后你触发点击链接。看起来很复杂。

    我会采取不同的方法...

    让服务器返回 PDF 字节(我假设 PdfWriter 有办法访问字节 []):

    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 将显示在新的浏览器窗口/选项卡中。

    【讨论】:

    • 这样更简洁,但我之所以这样做,是因为 PDF 是根据用户输入生成的,需要在用户单击按钮发送时将其发回它。我排除了 CreateCustomReport 方法的参数,因为我认为它们不相关。
    【解决方案2】:

    Nava 的回答并没有解决 OP 的问题,因为它仍然下载文件而不是在新选项卡中打开它。您需要修改响应标头才能做到这一点。

    public FileResult CreateCustomReport()
    {
        ...
        Response.AppendHeader("Content-Disposition", "inline; filename=Out.pdf");
        return File(m.ToArray(), "application/pdf" );
    }
    

    然后在你看来:

    &lt;a href="@Url.Action("CreateCustomReport")" target="_blank"&gt;Download PDF&lt;/a&gt;

    如果您想在点击后隐藏下载链接,您可以在锚点添加onclick

    &lt;a href="@Url.Action("CreateCustomReport")" target="_blank" onclick="this.style.display='none'"&gt;Download PDF&lt;/a&gt;

    编辑:我无法评论其他答案,但从您的评论中阅读,您似乎需要通过 POST 请求传递参数。如果您确实需要通过 POST 执行此操作,则可以使用隐藏表单和 target="_blank" 属性。如果你可以通过 GET 来完成,那么你可以将数据嵌入到你的 URL 中,然后你可以只使用一个简单的锚标记。

    【讨论】:

    • 我很惊讶这个答案不是更高,关键在响应头上,“Content-Disposition”需要是“内联”。
    猜你喜欢
    • 2021-03-04
    • 2016-09-24
    • 2014-03-19
    • 2011-11-06
    • 2015-06-11
    • 1970-01-01
    • 2016-02-26
    • 2023-03-21
    相关资源
    最近更新 更多