Search code examples
ruby-on-rails-3wkhtmltopdfwicked-pdf

Jquery trigger when PDF file downloaded


I am using wicked_pdf plug-in for generating pdf. I am showing message and spinner when user click on pdf link and i want to hide that when pdf is generated and pushed to browser for download/show. I have added jquery code on body onload which will not execute. Is there any other way to trigger jquery function when pdf file pushed to browser?


Solution

  • This is a rather complicated issue, but can be solved nicely if you are willing to use jQuery plugins. http://jqueryfiledownload.apphb.com/ is a plugin that can do exactly what you need if I understood you correctly.


    My frontend code looks like this

    $.fileDownload('/Content/Print', {
        successCallback: function (url) {
            $("#PrintingMessage").dialog('close');
        },
        failCallback: function (responseHtml, url) {
            $("#PrintingMessage").dialog('close');
    
            if (responseHtml.indexOf('Error403') != -1) {
                $("#PrintingFailedMessage").html("Error 403.");
            } else if (responseHtml.indexOf('Error500') != -1) {
                $("#PrintingFailedMessage").html("Error 500.");
            }
    
            $("#PrintingFailedMessage").dialog({ modal: true });
        },
        httpMethod: "POST",
        data: $('#PublishForm').serialize()
    });
    

    And my backend does this at the end of the process. You'll have to translate that yourself :)

    Response.SetCookie(new System.Web.HttpCookie("fileDownload", "true") { Path = "/" });
    return File(file, System.Net.Mime.MediaTypeNames.Application.Octet, filename);