获取当前页面MVC 5的pdf

时间:2015-04-02 14:05:02

标签: javascript jquery ajax asp.net-mvc pdf

我想在我的视野中获得一个div的pdf。

我正在做以下事情: 我得到元素,uri编码它的html,然后通过ajax传递给一个方法:

AJAX:

function getPDF(html) {
    $.ajax({
        type: "POST",
        url: "@Url.Action("printPage")",
        data: { html: encodeURIComponent(html) }

    }).done(function (result) {
        window.open("data:application/pdf; " + result);
        $("#printArea").html(result);
    }).fail(function (data) {
        alert("Failed");
    });
}

方法:

[HttpPost]
public void printPage(string html)
{
    String decoded = System.Uri.UnescapeDataString(html);
    var cd = new System.Net.Mime.ContentDisposition
    {
        FileName = "something.pdf",
        Inline = false
    };
    Response.AppendHeader("Content-Disposition", cd.ToString());
    var mem = Bcs.Common.Utilities.HTMLtoPDF.getPDF(decoded);
    //var base64EncodedPDF = System.Convert.ToBase64String(pdfByteArray);
    Response.BinaryWrite(mem.ToArray());
    //return File(mem, System.Net.Mime.MediaTypeNames.Application.Octet);
}

最后我得到一个弹出窗口打开一个pdf,但它不会打开,根据adobe acrobat它已经腐败了。

我尝试将html作为参数发送到方法,但是参数太长了

HTTP Error 404.15 - Not Found The request filtering module is configured to deny a request where the query string is too long.

这样做的好方法。

1 个答案:

答案 0 :(得分:0)

public JsonResult printPage(String html)
        {
            String decoded = System.Uri.UnescapeDataString(html);
            var cd = new System.Net.Mime.ContentDisposition
            {
                FileName = "something.pdf",
                Inline = false
            };
            var mem = Bcs.Common.Utilities.HTMLtoPDF.getPDF(decoded);
            mem.Flush();
            mem.Position = 0;
            String b64Converted = Convert.ToBase64String(mem.ToArray());
            return Json(b64Converted, JsonRequestBehavior.AllowGet );

System.Net.Mime.MediaTypeNames.Application.Octet);             }

然后在视图中:

 $.ajax({
            type: "POST",
            url: "@Url.Action("printPage")",
            data: { html: encodeURIComponent(html) },

        }).done(function (result) {

            $("#printArea").append('<a href="data:application/pdf;base64,' + result + '">PDF</a>');
        }).fail(function (data) {
            alert("Failed");
        });

显然很容易 只需使用pdf并在json响应中发送它。