Click here to Skip to main content
15,885,365 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Below is my aspx page


<%@ Page Title="" Language="C#" MasterPageFile="~/Site1.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="CHEWGB.Default" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <style type="text/css">
        body {
            background-color: none;
        }

        .control-label {
            color: black;
            font-weight: 600;
            font-size: 17px;
            text-align: center;
            font: bolder;
        }

        .submitBtn {
            padding: 10px 20px 11px !important;
            font-size: 21px !important;
            background-color: orange;
            font-weight: bold;
            text-shadow: 1px 1px #F36C8C;
            color: black;
            border-radius: 100px;
            -moz-border-radius: 100px;
            -webkit-border-radius: 100px;
            border: 1px solid #F36C8C;
            cursor: pointer;
            box-shadow: 0 1px 0 rgba(255, 255, 255, 0.5) inset;
            -moz-box-shadow: 0 1px 0 rgba(255, 255, 255, 0.5) inset;
            -webkit-box-shadow: 0 1px 0 rgba(255, 255, 255, 0.5) inset;
        }

            .submitBtn:hover {
                -webkit-transform: scale(1.3);
                transform: scale(1.3);
            }

            #dvProgressBar {
              position: fixed;
              z-index: 1031;
              top: 50%;
              left: 50%;
              transform: translate(-50%, -50%);
            }
            #pageloadicon {
              position: fixed;
              z-index: 1031;
              top: 50%;
              left: 50%;
              transform: translate(-50%, -50%);
            }
            #pageloadicon:after{
                  content: "Please wait..";
                  display: block;
                  position: absolute;
                  top: 50%;
                  left: 50%;
                  transform: translate(-50%, -50%)
                }

            #myOverlay{position:absolute;top:0;left:0;height:100%;width:100%;}
            #myOverlay{background:black;backdrop-filter:blur(3px);opacity:.3;z-index:2;display:none;}
    </style>

    <table style="background-color: none; border-collapse: separate; border-spacing: 20px; font: bold; font-size:larger">
        <tr>
            <td align="center">
                <asp:Label ID="Label1" runat="server" CssClass="control-label" Text="Enter Number : " BackColor="Aquamarine"></asp:Label>
            </td>
            <td align="center">
                <asp:TextBox ID="txtPoNumber" runat="server" autocomplete="off"></asp:TextBox>
            </td>
            <td align="center">
                <asp:Button ID="submtBtn" CssClass="submitBtn"  runat="server" Text="Submit" Style="float: right;" />
            </td>
        </tr>
    </table>

    <div id="myOverlay"></div>
    <div id="dvProgressBar"></div>
    <div id="pageloadicon"><img src="pageLoad.gif"/></div>

  <br style="clear:both" />

      <link href = "Css/jquery-ui.css" rel = "stylesheet"/>
      <script src = "Scripts/jquery-1.10.2.js"></script>
      <script src = "Scripts/jquery-ui.js"></script>
      <script type="text/javascript">

          $(document).ready(function () {
              $('#pageloadicon').hide(); 
              

              $("input[id$='submtBtn']").click(function () {
                   $('#myOverlay').show();
                 $('#dvProgressBar').html('<img src="myloading.gif"/><br/>Please wait while we collect the data and generate pdf..');
                  $.ajax({
                      type: "POST",
                      url: "Default.aspx/startPdfGenerate",
                      data: {},
                      async: true,
                      contentType: "application/json; charset=utf-8",
                      dataType: "json",
                      success: function (response) {
                           alert(response);
                      },
                      complete: function () {
                           $('#myOverlay').hide();
                          $("#dvProgressBar").css("display", "none");
                      },
                      error: function (response) {
                          $('#myOverlay').hide();
                          $("#dvProgressBar").css("display", "none");
                          alert("Something went wrong");
                          alert(response.status);
                      }
                  });
              });
          });
    </script>
</asp:Content>



Below is my code behind


using iTextSharp.text;
using iTextSharp.text.pdf;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Services;

namespace CHEWGB
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }


        [WebMethod]
        public static string startPdfGenerate()
        {
            try
            {
                string status = string.Empty;
                status = GetQualityScannedImg();

                return status;
            }
            catch (Exception ex)
            {
                return "failure";
            }
        }
        public static string GetQualityScannedImg()
        {
            try
            {
                //Initialize the PDF document object.
                using (Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 45f, 25f))
                {
                    PdfWriter writer = PdfWriter.GetInstance(pdfDoc, System.Web.HttpContext.Current.Response.OutputStream);
                    writer.PageEvent = new ITextEvents();

                    PdfDestination pdfDest = new PdfDestination(PdfDestination.XYZ, 0, pdfDoc.PageSize.Height, 1f);
                    pdfDoc.Open();

                    PdfAction action = PdfAction.GotoLocalPage(1, pdfDest, writer);
                    writer.SetOpenAction(action);

                    DirectoryInfo dirInfo = new DirectoryInfo(@"\\Sharedfolder\Images");

                    //Excludes Hidden Files
                    FileInfo[] files = dirInfo.GetFiles().Where(file => (file.Attributes & FileAttributes.Hidden) == 0).ToArray();

                    Image img = null;

                    float documentWidth = pdfDoc.PageSize.Width - pdfDoc.LeftMargin - pdfDoc.RightMargin;
                    float documentHeight = pdfDoc.PageSize.Height - pdfDoc.TopMargin - pdfDoc.BottomMargin;

                    foreach (FileInfo filePath in files)
                    {

                        //Add the Image file to the PDF document object.
                        img = Image.GetInstance(filePath.FullName);
                        img.ScaleToFit(documentWidth, documentHeight);
                        pdfDoc.Add(img);
                        break;
                    }
                    pdfDoc.Close();

                    img = null;
                    //Download the PDF file.
                    HttpContext.Current.Response.ContentType = "application/pdf";
                    HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=ImageExport.pdf");
                    HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
                    HttpContext.Current.Response.Write(pdfDoc);
                    //HttpContext.Current.Response.End();
                    HttpContext.Current.ApplicationInstance.CompleteRequest();
                }
                return "success";
            }
            catch (Exception ex)
            {
                return "failure";
            }
        }  
    }
}



The issue here is pdf file is not generating after ajax call.

What I have tried:

Instead of ajax i tried with normal onclick function of the button to check the code function. It works fine and pdf is getting generated. But when i use ajax it is not downloading.
Posted
Updated 19-Jun-20 3:49am
Comments
F-ES Sitecore 19-Jun-20 9:22am    
You can't download files via ajax. Just redirect to the url that instigates the download in a new tab. Modern browsers won't actually show you the new tab, they'll see if is a file download and show you the download manager instead.
Member 14636607 19-Jun-20 9:26am    
Can you just post a sample on how to do that..

Thanks
F-ES Sitecore 19-Jun-20 12:48pm    
Change your submtBtn asp:Button to a normal <a> tag like

<a href="startPdfGenerate.aspx" target="_blank">Download</a>

now create a page called startPdfGenerate.aspx and in its load event put your "GetQualityScannedImg" code.
Member 14636607 19-Jun-20 13:26pm    
What about ajax call?? What i need is.. i jus want to show loading icon till pdf gets generated....


Thanks man

1 solution

F-ES Sitecore:
You can't download files via ajax. Just redirect to the url that instigates the download in a new tab. Modern browsers won't actually show you the new tab, they'll see if is a file download and show you the download manager instead.
Member 14636607:
Can you just post a sample on how to do that..
Simple- you add the target attribute to the link
HTML
<a href="http://www.example.com/" target="_blank">PDF Name</a>
Reference:
HTML a tag[^]
 
Share this answer
 
Comments
Member 14636607 19-Jun-20 10:01am    
I didnt understand where to put this... Anyway thanks for your help!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900