Button click delay during click event

Donald Symmons 3,066 Reputation points
2023-12-20T07:46:30.11+00:00

When trying to capture and convert HTML DIV to image, the button click event does not fire immediately, I always have to click the button twice or more in order for it to work.

May I please ask why button click does not fire immediately after it is clicked, in this regard?

How can this be corrected please?

<asp:Label ID="LabelName" runat="server" Text="Richard"></asp:Label>
<asp:Image Class="imgfile" ID="imgfile" runat="server" />
<br />
<asp:Button ID="SaveDoc" runat="server" CssClass="btn btn-primary navbar-btn" Text="Save Document" OnClick="DownloadDocument_Click" UseSubmitBehavior="false" OnClientClick="return ConvertDocument(this)" />

<asp:HiddenField ID="ImageDatahf" runat="server" />

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>
    <script type="text/javascript">
        function ConvertDocument(SaveDoc) {
            html2canvas($("#section")[0], { scale: 3 })
                .then(function (canvas) {
                    var base64 = canvas.toDataURL();
                    $("[id*=ImageDatahf]").val(base64);
                    __doPostBack(SaveDoc.name, "");
                });
        }
    </script>
protected void DownloadDocument_Click(object sender, EventArgs e)
        {
            try
            {
                using (SqlConnection con = new SqlConnection())
                {
                    con.ConnectionString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;

                    string base64 = Request.Form[ImageDatahf.UniqueID].Split(',')[1];
                    byte[] imageBytes = Convert.FromBase64String(base64);
                    iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(imageBytes);
                    using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
                    {
                        if (Convert.ToInt64(image.Width.ToString()) > Convert.ToInt64(image.Height.ToString()))
                        {
                            using (Document document = new Document(new RectangleReadOnly(842, 595), 0f, 0f, 0f, 0f))
                            {
                                PdfWriter writer = PdfWriter.GetInstance(document, memoryStream);
                                document.Open();
                                image.SetDpi(100, 100);
                                image.ScaleToFit(500f, 1000f);
                                document.Add(image);
                                document.Close();
                            }
                        }
                        else
                        {
                            using (Document document = new Document(new RectangleReadOnly(595, 842), 0f, 0f, 0f, 0f))
                            {
                                PdfWriter writer = PdfWriter.GetInstance(document, memoryStream);
                                document.Open();
                                image.SetDpi(100, 100);
                                image.ScaleToFit(500f, 1000f);
                                document.Add(image);
                                document.Close();
                            }
                        }
                        byte[] bytes = memoryStream.ToArray();
                        memoryStream.Close();
                        // Code for saving binary data in daabase.
                        using (SqlCommand cmd = new SqlCommand("INSERT INTO DocumentTable (filename, ContentType, Data, Recipient)" + "VALUES(@filename, @ContentType, @Data, @Recipient)", con))
                        {
                            cmd.Parameters.AddWithValue("@filename", "Certificate.pdf");
                            cmd.Parameters.AddWithValue("@ContentType", "application/pdf");
                            cmd.Parameters.AddWithValue("@Data", bytes);
                            cmd.Parameters.AddWithValue("@Recipient", LabelName.Text.Trim());
                            con.Open();
                            cmd.ExecuteNonQuery();
                            con.Close();
                            Response.Redirect(Request.Url.AbsoluteUri);
                        }
                    }
                }
            }
            catch (SqlException ex)
            {
                string msg = "Error:";
                msg += ex.Message;
                throw new Exception(msg);
            }
        }
Developer technologies .NET Other
Developer technologies ASP.NET Other
Developer technologies C#
{count} votes

Accepted answer
  1. Lan Huang-MSFT 30,186 Reputation points Microsoft External Staff
    2023-12-21T07:19:12.9533333+00:00

    Hi @Donald Symmons,

    I tested your code and there is nothing wrong with the code itself. I think the problem you're talking about is that because the file is large, it takes a certain amount of time to load. I think you could add a please wait "animated" gif so it doesn't misunderstand the user.

       <div id="mywaitmsg" style="display: none; width: 300px">
                            <h6>Loading data - please wait</h6>
                            <div style="text-align: center">
                                <img src="../images/wait.gif" style="height: 64px; width: 70px" />
                            </div>
                        </div>
    
                        <div class="btnfront" runat="server" id="portraitBtn" style="margin: 0 auto; width: 100%; margin-top: 5%; padding-bottom: 6px;">
                            <asp:Button ID="SaveDoc" runat="server" CssClass="btn btn-primary navbar-btn" Text="Save Document" OnClick="DownloadDocument_Click" UseSubmitBehavior="false" OnClientClick="return ConvertDocument(this)" />
                        </div>
    
     <script type="text/javascript">
            function ConvertDocument(SaveDoc) {
    
                html2canvas($("#section")[0], { scale: 3 })
                    .then(function (canvas) {
                        var base64 = canvas.toDataURL();
                        $("[id*=ImageDatahf]").val(base64);
                        __doPostBack(SaveDoc.name, "");
                    });
                var mywait = document.getElementById("mywaitmsg")
                mywait.style.display = 'block';
            }
        </script>
    
     protected void DownloadDocument_Click(object sender, EventArgs e)
            {
                System.Threading.Thread.Sleep(2000);
    

    I discovered a problem during testing. Maybe you haven't updated yet, so I'll mention it here.

    According to your previous requirements, the picture completely fills the PDF. You need to change the relevant code as follows:

     <div class="col-sm-9" runat="server" id="section" style="width: 80%; height: 80%">
                        <asp:Image Class="imgfile" ID="imgfile" runat="server" Width="100%" Height="100%" ImageUrl="~/images/4.PNG" />
                        <asp:Label ID="LabelName" runat="server" Text="Recipient Name"></asp:Label>
                        <asp:Label ID="LabelDate" runat="server" Text="Date"></asp:Label>
                    </div>
    

    User's image

    3

    Best regards,
    Lan Huang


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.