We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy. Image for the cookie policy date
close icon

Open pdf from $.ajax()

Hi

I'm calling my Controller via jquery ajax, but i can't figure out how to show the pdf
if i show the result in a alert() message the message is : %PDF-1.5%����

my code
Script
 $.ajax({
                url: '@Url.Action("GetDocumentByModel","Rapport")',
                type: "GET",
                contentType: "application/xml; charset=utf-8",
                data: { itType: itType, modelId: modelId },
                beforeSend: function() {
                    $("#inProgress").show();
                },
                complete: function() {
                    $("#inProgress").hide();

                },
                success: function(data) {
                   alert(data);
                },
                error: function() {
                    $("#inProgress").hide();
                    toastr.options = {
                        positionClass: "toast-top-left",
                        showMethod: "slideDown",
                        closeButton: "true",
                        titimeOut: "3000"
                    };
                    toastr.error("Kunne ikke generere dokument", "Error");
                }
            });


my controller:
 [HttpGet]
        public ActionResult GetDocumentByModel(string itType, string modelId)
        {

.....

//Class to handle Pdf creation
            var pdf = new CreatePDF();

            var document = pdf.CreateModelDocument(rapportItem, displayName);

            return document.ExportAsActionResult("pdf", HttpContext.ApplicationInstance.Response, Syncfusion.Pdf.HttpReadType.Open);
          
        }

9 Replies

PH Praveenkumar H Syncfusion Team December 22, 2014 04:07 AM UTC

Hi Jacob,

Thank you for using syncfusion products,

The line  "return document.ExportAsActionResult("pdf", HttpContext.ApplicationInstance.Response, Syncfusion.Pdf.HttpReadType.Open);" automatically opens the pdf in browser itself.

the "alert" function shows the string , so we suggested to use iframe to display the pdf in client side instead of using alert function.

 success: function(data)
        {
            var iframe = $('<iframe>');
            iframe.attr('src','/pdf/yourpdf.pdf?options=first&second=here');
            $('#targetDiv').append(iframe);
        }
Please try this and let us know your result.

With Regards,
Praveen


DG Dominic Gutridge January 20, 2015 04:12 PM UTC

Hi all,

I am at the point where I can open a pdf through a form submit - like in the sample, but cannot recreate the same with an ajax post - opening a pdf in the browser. Does the method only work when a form is submitted? How could I mimic a form post with an ajax post?

How would one return the data to an ajax success: function (data), with the relevant pdf view display? What datatype would it be?

At the moment I am getting the same %PDF-1.5 %���� 37 0 obj << /Type /Catalog /Pages 38 0 R /AcroForm 39 0 R >> endobj 1 0 obj <<, when returning the: document.ExportAsActionResult("pdf", HttpContext.ApplicationInstance.Response, Syncfustion.Pdf.HttpReadType.Open)

There is not much in the way of documentation with regards to the above, you state put the pdf in an iframe, but nowhere do you use the data in the code.

I'll be appreciative of help.

Regards.




PH Praveenkumar H Syncfusion Team January 21, 2015 12:22 PM UTC

Hi Dominic,

Thank you for your update,

I have attached simple mvc sample to generate and show the PDF document in the browser, can you please add your ajax post code in this and send the sample back to us or send us the sample which your trying , it will help us to check the possibilities to open a pdf using ajax.

http://www.syncfusion.com/downloads/support/directtrac/117808/PDF_sample_With_Header277866561.zip

In my previous update I have provided the code snippet to open a pdf from the local folder using iframe, can your please try this and let us know, that satisfies your need here.

 success: function(data)
        {
            var iframe = $('<iframe>');
            iframe.attr('src','/pdf/yourpdf.pdf?options=first&second=here');
            $('#targetDiv').append(iframe);
        }

With Regards,

Praveen




ØK Øystein Karlsen August 8, 2018 11:22 AM UTC

Hi.

I have the exact same issue. Did you find a solution to this?

Best regards
Øysten


KC Karthikeyan Chandrasekar Syncfusion Team August 9, 2018 08:40 AM UTC

Hi Øysten, 
Did you tested the solution using iframe, is it producing any error. You may also refer the below KB article to get a working sample, please refer this and check if it satisfies your requirement. 

Regards, 
Karthikeyan 



ØK Øystein Karlsen August 10, 2018 06:47 PM UTC

Hi, and thanks for the quick response.

Yes I did try the solution using iframe, but I was hoping it would be possible to do this without storing the actual file on the server first.

The reason for me to use ajax is that I need a spinner or some other way to show the user that the system is working. I'm generating a quite large PDF. Do you know any other way I can show a spinner or a progress bar while the PDF is generated?

Best regards
Øystein


KC Karthikeyan Chandrasekar Syncfusion Team August 13, 2018 09:12 AM UTC

Hi Øystein, 
If you wish not to save the PDF in the server, we shall use some workaround trick to check the status of the PDF generation using ajax call and setInterval. I have attached the code snippet and sample for your reference. 

Razor 
@using (Html.BeginForm("GeneratePDF", "Home", FormMethod.Get)) 
{ 
    <input type="submit" value="Create PDF" onclick="GeneratePDF()" /> 
} 
 
<div id="spinner"></div> 
 
<script type="text/javascript"> 
    function GeneratePDF() { 
 
        var spinnerDiv = document.getElementById("spinner"); 
        spinnerDiv.innerHTML = '<i class="fa fa-circle-o-notch fa-spin" style="font-size:24px"></i >'; 
 
        var refreshIntervalId = window.setInterval(function () { 
        $.ajax({ 
            type: "GET", 
            url: '@Url.Action("GetStatus", "Home")', 
            contentType: "application/json; charset=utf-8", 
            dataType: "json", 
            success: function (response) { 
                if (response.responseText == 'True') { 
                    document.getElementById("spinner").innerHTML = ''; 
                    window.clearInterval(refreshIntervalId); 
                } 
            }, 
            error: function (response) { 
                if (response.responseText == 'True') { 
                    document.getElementById("spinner").innerHTML = ''; 
                    window.clearInterval(refreshIntervalId); 
                } 
            } 
            }); 
        }, 1000); 
 
    } 
</script> 

Controller 
 
static bool taskCompleted = false; 
 
public ActionResult GeneratePDF() 
{ 
    taskCompleted = false; 
    System.Threading.Thread.Sleep(5000); 
    // Create a new PdfDocument 
    PdfDocument document = new PdfDocument(); 
 
    // Add a page to the document 
    PdfPage page = document.Pages.Add(); 
 
    // Create Pdf graphics for the page 
    PdfGraphics graphics = page.Graphics; 
 
    // Create a solid brush 
    PdfBrush brush = new PdfSolidBrush(Color.Black); 
 
    // Set the font 
    PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 20f); 
 
    // Draw the text 
    graphics.DrawString("Hello world!", font, brush, new PointF(20, 20)); 
 
    taskCompleted = true; 
 
    //Export the document after saving 
    return document.ExportAsActionResult("output.pdf", HttpContext.ApplicationInstance.Response, HttpReadType.Save); 
} 
public bool GetStatus() 
{ 
    return taskCompleted; 
} 

Regards, 
Karthikeyan 



ØK Øystein Karlsen August 13, 2018 05:24 PM UTC

Thanks a lot Karthikeyan, it worked like a charm. :)



KC Karthikeyan Chandrasekar Syncfusion Team August 14, 2018 04:37 AM UTC

Hi Øystein, 
We are happy to know that your requirement is fulfilled. 
 
Regards, 
Karthikeyan 


Loader.
Live Chat Icon For mobile
Up arrow icon