Saving <div> as an image cuts out huge part of the image

Donald Symmons 3,066 Reputation points
2023-12-15T06:48:35.96+00:00

I tried to capture an image displayed on a web page into pdf, the entire image is cut during the capturing.

After I uploaded a certificate image ( in .jpeg or .png), I tried to capture the whole certificate using the html2canvas library but the image is cut. The only image I see is the top-left corner of the certificate image. But when the image is in image format, the entire image shows. I think the issue could be from where the captured image is converted into pdf

How can I make it to capture the entire certificate, please?

Here is my result when converting to PDF

cut out

You can sse that I have only top-left part of the certificate. 

But this is the result when the capture is in image format (.png)

HTML

Here is my HTML and JavaScript

<div class="row col-sm-12" style="width: 100%; margin: 0 auto; padding: 6px; margin-right: auto; margin-left: auto; margin-bottom: 20px">
                <div class="col-sm-3" style="width: 100%; margin: 0 auto; padding: 7px; margin-top: 10px;">
                    <div class="row">
                        <div class="col-md-12">
                            <div class="form-group">
                                <asp:Label runat="server">Choose Font</asp:Label>
                                <div class="input-group">
                                    <input type="text" runat="server" class="fonts form-control" id="fonts" />
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-12">
                            <div class="form-group">
                                <label runat="server" id="Label6">Name Font Size</label>
                                <div class="input-group">
                                    <asp:DropDownList ID="NameFontSize" runat="server" CssClass="form-control" onchange="NameSize(this.value)">
                                    </asp:DropDownList>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-12">
                            <div class="form-group">
                                <label runat="server" id="Label22">Date Font Size</label>
                                <div class="input-group">
                                    <asp:DropDownList ID="DateFontSize" runat="server" CssClass="form-control" onchange="ChangeDateSize(this.value)">
                                    </asp:DropDownList>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="btnfront" runat="server" id="portraitBtn" style="margin: 0 auto; width: 100%; margin-top: 5%; padding-bottom: 6px;">
                        <asp:Button ID="SaveCert" runat="server" CssClass="btn btn-primary navbar-btn" Text="Save Certificate" OnClick="ConvertImgTopdf" UseSubmitBehavior="false" OnClientClick="return ConvertCert(this)" />
                    </div>
                    <div id="dvMessage" runat="server" visible="false" class="alert alert-danger" style="margin-bottom: 1%; padding: 6px;">
                        <asp:Label ID="lblMessage" runat="server" Font-Size="9pt" />
                    </div>
                </div>
                <div class="col-sm-9" runat="server" id="section">
                    <asp:Image Class="imgfile" ID="imgfile" runat="server" ImageUrl="~/images/4.jpeg" />
                    <asp:Label ID="LabelName" runat="server" Text="Recipient Name"></asp:Label>
                    <asp:Label ID="LabelDate" runat="server" Text="Date"></asp:Label>
                </div>
                <asp:HiddenField ID="ImageDatahf" runat="server" />
            </div>
                <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>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js" integrity="sha384-cs/chFZiN24E4KMATLdqdvsezGxaGsi4hLGOzlXwp5UZB1LY//20VyM2taTB4QvJ" 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 src="js/bootstrap.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            function selectFontAndApplyToEle(fontName, callback) {
                $('div.font-select').find('.fs-results li').removeClass('active');
                var dropEle = $('div.font-select').find('.fs-drop');
                var fontToSelect = $('div.font-select').find('.fs-results li:contains(' + fontName + ')');
                dropEle.addClass('fs-drop-op');
                var posFont = fontToSelect.offset().top
                var posFontOffset = $('div.font-select').find('.fs-results li:first').offset().top
                $('div.font-select').find('.fs-results').scrollTop(posFont - posFontOffset);
                fontToSelect.addClass('active').trigger('click');
                setTimeout(function () {
                    $('div.font-select a div').trigger('click');
                    dropEle.removeClass('fs-drop-op');
                    callback && callback(fontToSelect.data('value').replace(/\+/g, ' '));
                }, 500);
            }
            $(function () {
                $('input.fonts').fontselect({
                    style: 'font-select',
                    placeholder: 'Select a font',
                    lookahead: 2
                }).on('change', function (e) {
                    var fontFamily = $(this).val().replace(/\+/g, ' ');
                    $('#LabelName').css('font-family', fontFamily);
                    $('#LabelDate').css('font-family', fontFamily);
                });
                selectFontAndApplyToEle('Anton', function (fontFamily) {
                    $('#LabelName').css('font-family', fontFamily);
                    $('#LabelDate').css('font-family', fontFamily);
                    setTimeout(function () {
                        selectFontAndApplyToEle('Anonymous Pro', function (fontFamily) {
                            $('#LabelName').css('font-family', fontFamily);
                            $('#LabelDate').css('font-family', fontFamily);
                        });
                    }, 1000);
                });
            });
        });
    </script>
    <script type="text/javascript" src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>
    <script type="text/javascript">
        function ConvertCert(SaveCert) {
            html2canvas($("#section")[0], { scale: 3 })
                .then(function (canvas) {
                    var base64 = canvas.toDataURL();
                    $("[id*=ImageDatahf]").val(base64);
                    __doPostBack(SaveCert.name, "");
                });
        }
    </script>

C#

        //This is when the Image is downloaded in it's normal format e.g. .png or .jpeg
        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();
        }
        //This is the code that it converts to PDF
        protected void ConvertImgTopdf(object sender, EventArgs e)
        {
            string imagedata = ImageDatahf.Value;
            string convert = imagedata.Replace("data:image/png;base64,", String.Empty);
            byte[] imagebytes = Convert.FromBase64String(convert);

            //Initialize the PDF document object.
            using (Document pdfDoc = new Document())
            {
                PdfWriter writer = PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
                pdfDoc.Open();

                //Add the Image file to the PDF document object.
                iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(imagebytes);
                pdfDoc.Add(img);
                pdfDoc.Close();

                //Download the PDF file.
                Response.ContentType = "application/pdf";
                Response.AddHeader("content-disposition", "attachment;filename=ImageExport.pdf");
                Response.Cache.SetCacheability(HttpCacheability.NoCache);
                Response.Write(pdfDoc);
                Response.End();
            }
        }
Developer technologies | .NET | Other
Developer technologies | ASP.NET | Other
{count} votes

Accepted answer
  1. Lan Huang-MSFT 30,191 Reputation points Microsoft External Staff
    2023-12-15T10:16:22.3466667+00:00

    Hi @Donald Symmons,

    I found that there is a way to design the image size in the iTextSharp library, maybe you can try it.

    The following places need to be changed:

     <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>
    
     //Add the Image file to the PDF document object.
                    iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(imagebytes);
                    img.SetDpi(100, 100);
    
                    img.ScaleToFit(500f, 1000f);
                    pdfDoc.Add(img);
                    pdfDoc.Close();
    

    User's image

    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.