How do I convert Div tag and all its content to image and then save it as byte into database

Donald Symmons 3,066 Reputation points
2023-04-05T01:09:27+00:00

I was recently reading an article about converting HTML DIV to image using HTML Canvas. I tried to implement the same thing but when I click on my button, nothing happens. How do I convert a div tag with all its contents like labels, images etc.?

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css" integrity="sha512-iBBXm8fW90+nuLcSKlbmrPcLa0OT92xO1BIsZ+ywDWZCvqsWgccV3gFoRBv0z+8dLJgyAHIhR35VZc2oM/gI1w==" crossorigin="anonymous" referrerpolicy="no-referrer" />
    <link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" intergrity="sha384-AYmEC3Yw5cVb3ZcuHt0A9w35dYTsvhLPVnYs9eStHfGJv0vKxVfELGroGkvsg+p" crossorigin="anonymous" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" />
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous" />
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous" />
    <script defer="" src="https://use.fontawesome.com/releases/v5.0.13/js/fontawesome.js" integrity="sha384-6OIrr52G08NpOFSZdxxz1xdNSndlD4vdcf/q2myIUVO0VsqaGHJsB0RaBE01VTOY" crossorigin="anonymous"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/malihu-custom-scrollbar-plugin/3.1.5/jquery.mCustomScrollbar.min.css" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
    <link href="css/bootstrap.min.css" rel="stylesheet" media="all" />
    <link href="css/bootstrap.css" rel="stylesheet" media="all" />
    <link href="css/IdStyle.css" rel="stylesheet" />
     <title></title>
    <style type="text/css">
        #content {
            flex: auto;
        }

        @media screen and (min-width: 1200px) {
            #content {
                width: 100%;
            }
        }

        @media screen and (min-width: 360px) and (max-width:640px) {
            #content {
                width: 100%;
            }
        }

        #CardBtn { background-color: #145c7c; border-color: #145c7c; font-size: 9pt; color: #fff; margin: 0 auto; min-width: 100px;}
        @media print {
            body * {
                visibility: hidden;
            }
            .print-contents, .print-contents * {
                visibility: visible;
            }
            .print-contents {
                position: absolute;
                left: 0px;
                right: 0px;
            }
            #IDcard {
                visibility: visible;
            }
        }
                .front{width: 220px; height: 350px; background-color: transparent; border-radius: 10px; border: 1px solid #999; margin: 0 auto;}
        .back{width: 220px; height: 350px; background-color: white; border-radius: 10px; border: 1px solid #999; margin: 0 auto; margin-top: 2%;}
        .dp{width: 95px; position: relative; height: 95px; top: 30px; left: 50%; transform: translate(-50%); border-radius: 5px; border: 0.5px solid #f3f3f4;}
        #Image2 {width: auto; height: 100%;}
        .header h5{font-size: 8px;}
        .bottom{clear:both; width: 100%; height: 38%; background-color: transparent; border-radius: 10px; text-align: center;}
        .bottom h1{font-size: 15px; position: relative; top: 35%; text-transform: uppercase;}
        .bottom h5{font-size: 9px; position: relative; top: 50px; text-transform: uppercase;}
        .image{position: relative; top: 30px; float: right; margin: 0 auto; right: 5px;}
        .sign{position: relative; top: 30px; float: left; margin: 0 auto; left: 5px;}
        .imgQR{border: 1px solid #f3f3f4;}
        .holder{border: 1px solid #f3f3f4;}
        .info{font-size: 6px; margin: 10px 10px; margin-top: 6%; text-align: center; line-height: normal; vertical-align: baseline;}
        .roundline{height: 10px; width: 100%; background-color: #343339; position: relative; top: 1px; left: 50%; transform: translate(-50%); border-radius: 5px;}
        #adminsign{top: -4px; font-size: 4px;}
    </style>
</head>
<body style="background-color: #fdfdfd; font-family: 'Graphik', sans-serif; font-size: 17px; font-weight: 400;">
    <form id="form1" runat="server">
        <asp:ScriptManager ID="script" runat="server"></asp:ScriptManager>
        <div id="content" style="font-size: 10pt; width: 100%;">
            <div class="row col-sm-12" runat="server" style="width: 100%; margin: 0 auto; padding: 10px; margin-bottom: 0%;">
                <div class="col-sm-5" style="margin: 0 auto;">
                    <asp:Panel Class="print-contents" ID="pnlContents" runat="server">
                        <div class="front" runat="server" id="cardrear">
                            <div class="IDtop">
                                <div class="row" runat="server" id="header" style="width: 100%; margin-top: 5px;">
                                    <div class="col-2">
                                        <asp:Image ID="Image2" ImageUrl="~/images/logoquive.png" CssClass="idcardimg" AlternateText="logo" runat="server" Height="20" />
                                    </div>
                                    <div class="header col-9">
                                        <div style="text-align: center;">
                                            <h5>
                                                <asp:Label ID="lblName" runat="server" Text="Heritage International Schools"></asp:Label></h5>
                                        </div>
                                    </div>
                                </div>
                                <div class="type" id="type" style="text-align: center;">
                                    <asp:Label ID="typelbl" runat="server" Text="STAFF"></asp:Label>
                                    <span style="color: #999;">IDENTITY CARD</span>
                                </div>
                                <asp:Image ID="Image1" runat="server" CssClass="dp" />
                            </div>
                            <div class="bottom">
                                <h1>
                                    <asp:Label runat="server" ID="idname" Text="Gabriel Victor Johnson"></asp:Label></h1>
                                <h5>
                                    <asp:Label runat="server" ID="Designatelbl" Text="Engineering"></asp:Label></h5>
                                <h5>
                                    <asp:Label runat="server" ID="cardID" Text="008742"></asp:Label></h5>
                                <br />
                                <div class="sign">
                                    <asp:Image ID="Image4" runat="server" CssClass="holder" Height="30" BorderStyle="Dashed" />
                                    <p style="font-size: 8pt;">Holder's signature</p>
                                </div>
                                <div class="image">
                                    <asp:Image ID="Image3" runat="server" CssClass="imgQR" Height="50" BorderStyle="Solid" />
                                </div>
                            </div>
                        </div>
                    </asp:Panel>
                    <asp:HiddenField ID="ImageDatahf" runat="server" />
                    <!--UseSubmitBehavior property set to false and a Hidden Field to send the generated Base64 string to server.
                    The UseSubmitBehavior property is set to false in order to call the click event handler using JavaScript-->
                    <asp:Button ID="CardBtn" Text="Save Card" runat="server" CssClass="btn navbar-btn" UseSubmitBehavior="false" OnClick="ExportToImage" OnClientClick="return ConvertToImage(this)" />
                </div>
            </div>
        </div>
    </form>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js" integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i+tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.min.js" integrity="sha384-cVKIPhGWiC2Al4u+LWgxfKTRIcfu0JTxR+EQDz/bgldoEyl4H0zUF0QKbrJ0EcQF" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js" integrity="sha384-uefMccjFJAIv6A+rW+L4AHf99KvxDjWSu1z9VI8SKNVmz4sk7buKt/6v9KI65qnm" crossorigin="anonymous"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <link rel="stylesheet" href="https://rawgit.com/tommoor/fontselect-jquery-plugin/master/fontselect.css" />
    <script src="https://rawgit.com/tommoor/fontselect-jquery-plugin/master/jquery.fontselect.js"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript" src="http://cdn.rawgit.com/niklasvh/html2canvas/master/dist/html2canvas.min.js"></script>

    <!--When the Export button is clicked, the JavaScript ConvertToImage function is executed which captures a screenshot of HTML DIV using Html2Canvas library and then saves the Base64 string into the Hidden Field.-->
      <!--Then Server Side event of the Button is triggered using the ASP.Net __doPostBack method.-->
     <script type="text/javascript">
         function ConvertToImage(CardBtn) {
             html2canvas($("#cardrear")[0]).then(function (canvas) {
                 var base64 = canvas.toDataURL();
                 $("[id*=ImageDatahf]").val(base64);
                 __doPostBack(CardBtn.name, "");
             });
             return false;
         }
     </script>  
</body>
</html>
//Inside the click event handler of the Button, the Base64 string is fetched from the Hidden Field and it is converted to an Array of Bytes.
        //The array of bytes below are written to the Response and downloadeded as Image file.
        protected void ExportToImage(object sender, EventArgs e)
        {
            string base64 = Request.Form[ImageDatahf.UniqueID].Split(',')[1];
            byte[] bytes = Convert.FromBase64String(base64);
            Response.Clear();
            Response.ContentType = "image/png";
            Response.AddHeader("Content-Disposition", "attachment; filename=HTML.png");
            Response.Buffer = true;
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.BinaryWrite(bytes);
            Response.End();
        }
Developer technologies | .NET | Other
Developer technologies | ASP.NET | Other
0 comments No comments
{count} votes

Accepted answer
  1. Lan Huang-MSFT 30,191 Reputation points Microsoft External Staff
    2023-04-05T05:16:21.45+00:00

    Hi @Donald Symmons,

    I tried to implement the same thing but when I click on my button, nothing happens

    If there is no response, you can press F12 to view the error message. The reason why it doesn't work should be that you are using an outdated or unsupported library, you can use the following JS file.

    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
       <script type="text/javascript" src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script> 
    

    Code to store the image in the database:

                string base64 = Request.Form[ImageDatahf.UniqueID].Split(',')[1];
                byte[] bytes = Convert.FromBase64String(base64);
                string constr = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
                using (SqlConnection conn = new SqlConnection(constr))
                {
                    string sql = "INSERT INTO tblFiles (Id ,Data)VALUES(@Id, @Data)";
                    using (SqlCommand cmd = new SqlCommand(sql, conn))
                    {
                        cmd.Parameters.AddWithValue("@Id", Convert.ToInt32(TextBox1.Text));
                        cmd.Parameters.AddWithValue("@Data", bytes);
                        conn.Open();
                        cmd.ExecuteNonQuery();
                        conn.Close();
                    }
                }
    

    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 comments No comments

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.