Articles in this section
Category / Section

How to download a PDF using AJAX Call?

4 mins read

Syncfusion Essential PDF is a .NET PDF library used to create, read, and edit PDF documents. Using this library, you can download PDF documents using AJAX Call.

A file cannot be downloaded with AJAX directly. You can request a file using AJAX, but AJAX response will contain the actual file stream. Due to JavaScript limitations, you cannot save the stream on the user’s machine with a file download dialog. As a work around, you can check the status of the PDF generation and then export the document after saving in the disk using AJAX call.

Steps to download PDF using AJAX call programmatically:

  1. Create a new ASP.NET MVC application project. Create a ASP.NET MVC application project
  2. Install the Syncfusion.Pdf.AspNet.Mvc NuGet package as a reference to your .NET Framework application from NuGet.org. NuGet package reference
  3. A default controller with name HomeController.cs gets added on creation of ASP.NET MVC project. Include the following namespaces in that HomeController.cs file.

C#

using Syncfusion.Pdf;
using Syncfusion.Pdf.Graphics;
using System.Drawing;

 

VB.NET

Imports Syncfusion.Pdf
Imports Syncfusion.Pdf.Graphics
Imports System.Drawing

 

  1. Add a following code in the index.cshtml.
    @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>
    

 

  1. Add a new action method named GeneratePDF in HomeController.cs and include the following code snippet to download PDF using AJAX call.

C#

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);
}
        
//Get the status of PDF generation
public bool GetStatus()
{
    return taskCompleted;
}

 

VB.NET

Shared taskCompleted As Boolean = False
Public Function GeneratePDF() As ActionResult
    taskCompleted = False
    System.Threading.Thread.Sleep(5000)
    'Create a new PdfDocument
    Dim document As New PdfDocument()
    'Add a page to the document
    Dim page As PdfPage = document.Pages.Add()
    'Create Pdf graphics for the page
    Dim graphics As PdfGraphics = page.Graphics
    'Create a solid brush
    Dim brush As PdfBrush = New PdfSolidBrush(Color.Black)
    'Set the font
    Dim font As PdfFont = New PdfStandardFont(PdfFontFamily.Helvetica, 20.0F)
    '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)
End Function
'Get the status of PDF generation 
Public Function GetStatus() As Boolean
    Return taskCompleted
End Function

 

A complete working sample can be downloaded from AjaxCall.zip.

By executing the program, you will get the PDF document as follows. Output document screenshot

Refer here to explore the rich set of Syncfusion Essential PDF features.

Note:

Starting with v16.2.0.x, if you reference Syncfusion assemblies from trial setup or from the NuGet feed, include a license key in your projects. Refer to link to learn about generating and registering Syncfusion license key in your application to use the components without trail message.

 

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please sign in to leave a comment
Access denied
Access denied