Generate Pdf via ajax.POST with Rotary

Asked

Viewed 198 times

1

I want to generate a. pdf file using Rotary, my ajax call is as follows:

$.ajax({
                    type: "POST",
                    url: "Home/Index",
                    data: { nome: inputName, laudos: laudos, imagem: imgSelecionada },
                });

And the code in Action is this:

[HttpPost]
    public ActionResult Index(UsuarioViewModel user)
    {
        string header = Server.MapPath("~/Views/Home/Header2.html");
        string footer = Server.MapPath("~/Views/Home/Footer.html");

        string customSwitches = string.Format("--header-html \"{0}\" " +
                                              "--header-spacing \"0\" " +
                                              "--footer-html \"{1}\" " +
                                              "--footer-spacing \"5\" ", header, footer);

        var pdf = new ViewAsPdf
        {
            ViewName = "Modelo",
            Model = user,
            CustomSwitches = customSwitches
        };


        return pdf;
    }

Is it really possible to do something like this or should I use another approach? After a lot of research, I saw in some places that the Rotary does not work very well with ajax requests.

1 answer

0

I think the problem is that the original wkhtmltopdf library is not able to resolve the request made with Ajax, with its respective callbacks.

In short, the rotary cannot support ajax calls.

I see that this statement repeats both in here stackoverflow and in open library issues.

However, we have a simple way around the problem.

Replacing the Ajax call with:

var form = document.createElement("form");

form.method = "post";
form.action = "Home/Index";
form.setAttribute("target", "ViewIndex");

var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "json");
hiddenField.setAttribute("name", "pData");
hiddenField.setAttribute("value", JSON.stringify({ nome: inputName, laudos: laudos, imagem: imgSelecionada }));

form.appendChild(hiddenField);

document.body.appendChild(form);
window.open('', 'ViewIndex');

form.submit();

Then by changing your controller method as follows:

[HttpPost]
public dynamic Index(string pData)
    {
    var user = JsonConvert.DeserializeObject<UsuarioViewModel>(pData);

    string header = Server.MapPath("~/Views/Home/Header2.html");
    string footer = Server.MapPath("~/Views/Home/Footer.html");

    string customSwitches = string.Format("--header-html \"{0}\" " +
                                          "--header-spacing \"0\" " +
                                          "--footer-html \"{1}\" " +
                                          "--footer-spacing \"5\" ", header, footer);

    return new ViewAsPdf
    {
        ViewName = "Modelo",
        Model = user,
        CustomSwitches = customSwitches
    };
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.