Download captured HTML Div as PDF and also send as PDF attachment to email

Donald Symmons 2,856 Reputation points
2024-04-16T22:16:51.26+00:00

I want to achieve 2 things:

  1. Capture HTML, convert to Image and download as PDF
  2. Send the captured and converted HTML div as PDF attachment to email

When I tried capturing the entire div and convert into image and download as PDF but it appears the ScaleToFit size makes the captured contents smaller. Please what Measurement should I use to make the pDF image looks like the original ?

When I tried to increase ScaleToFit from

image.ScaleToFit(500f, 1000f);

to this

 img.ScaleToFit(500f, 1200f);            

But it did not work.

There are two codes: The first code is to download as PDF, Second code Sends as attachment to email

        protected void ConvertTopdf(object sender, EventArgs e)
        {
            string imagedata = InvoiceimgData.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);
                img.SetDpi(100, 100);

                img.ScaleToFit(500f, 1200f);
                pdfDoc.Add(img);
                pdfDoc.Close();

                //Download the PDF file.
                Response.ContentType = "application/pdf";
                Response.AddHeader("content-disposition", "attachment;filename=" + nameLbl.Text + " Invoice.pdf");
                Response.Cache.SetCacheability(HttpCacheability.NoCache);
                Response.Write(pdfDoc);
                Response.End();
            }
        }

        protected void ExportToMail(object sender, EventArgs e)
        {
            string base64 = Request.Form[InvoiceimgData.UniqueID].Split(',')[1];
            byte[] Bytes = Convert.FromBase64String(base64);
            iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(Bytes);
            image.SetDpi(100, 100);
            image.ScaleToFit(500f, 1000f);

            MailMessage mm = new MailMessage();
            mm.From = new MailAddress("myemail@mail.com");
            string sentFrom = Lblname.Text;
            string[] ToAddress = TextBox1.Text.Split(',');
            foreach (string n in ToAddress)
            {
                mm.To.Add(new MailAddress(n));
            }
            mm.Subject = "INVOICE from " + sentFrom;
            mm.Body = bodyMail.Text;
            mm.Attachments.Add(new Attachment(new MemoryStream(Bytes), "Invoice.pdf"));
            mm.IsBodyHtml = true;
            SmtpClient smtp = new SmtpClient();
            smtp.Host = "relay-hosting.secureserver.net";
            smtp.EnableSsl = true;
            NetworkCredential NetworkCred = new NetworkCredential();
            NetworkCred.UserName = "myemail@mail.com";
            NetworkCred.Password = "*****************";
            smtp.UseDefaultCredentials = true;
            smtp.Credentials = NetworkCred;
            smtp.Port = 25;
            smtp.Send(mm);
            ClientScript.RegisterStartupScript(GetType(), "alert", "alert('Invoice sent to Recipient(s)');", true);
        }

Javascript

<script type="text/javascript" src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>
    <script type="text/javascript">
        function ConvertInvoice(Button2) {
            html2canvas($("#GridParent")[0], { scale: 3 })
                .then(function (canvas) {
                    var base64 = canvas.toDataURL();
                    $("[id*=InvoiceimgData]").val(base64);
                    __doPostBack(Button2.name, "");
                });
        }
    </script>
    <script type="text/javascript">
        function ConvertToMail(Button1) {
            html2canvas($("#GridParent")[0], { scale: 3 })
                .then(function (canvas) {
                    var base64 = canvas.toDataURL();
                    $("[id*=InvoiceimgData]").val(base64);
                    __doPostBack(Button1.name, "");
                });
        }
    </script>

HTML

(The Div tag used here has no contents in it because I am just presenting a sample)

<div class="parent" runat="server" id="GridParent" style="border: 0.5px solid #efefef; display: flex; background-color: #ffffff; width: 100%; height: auto; box-shadow: 0 1px 2px 0 rgba(0, 0.1, 0, 0.1);">

 </div>
<asp:HiddenField ID="InvoiceimgData" runat="server" />

<asp:Button ID="Button1" runat="server" CssClass="btn btn-primary" Font-Size="10pt" BackColor="#32657c" Text="Mail Invoice" OnClick="ExportToMail" UseSubmitBehavior="false" OnClientClick="return ConvertToMail(this)" />
<asp:Button ID="Button2" runat="server" CssClass="btn btn-primary" Font-Size="10pt" BackColor="#32657c" Text="Download Invoice" OnClick="ConvertTopdf" UseSubmitBehavior="false" OnClientClick="return ConvertInvoice(this)" />

.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,385 questions
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,262 questions
0 comments No comments
{count} votes

Accepted answer
  1. Lan Huang-MSFT 25,556 Reputation points Microsoft Vendor
    2024-04-17T07:34:23.55+00:00

    Hi @Donald Symmons,

    You can use img.ScaleAbsolute(500, 400); The number inside you can change according to your content.

    Below is an example of my simple test.

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
    </head>
        <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 ConvertInvoice(Button2) {
                html2canvas($("#GridParent")[0], { scale: 3 })
                    .then(function (canvas) {
                        var base64 = canvas.toDataURL();
                        $("[id*=InvoiceimgData]").val(base64);
                        __doPostBack(Button2.name, "");
                    });
            }
        </script>
        <script type="text/javascript">
            function ConvertToMail(Button1) {
                html2canvas($("#GridParent")[0], { scale: 3 })
                    .then(function (canvas) {
                        var base64 = canvas.toDataURL();
                        $("[id*=InvoiceimgData]").val(base64);
                        __doPostBack(Button1.name, "");
                    });
            }
        </script>
    <body>
        <form id="form1" runat="server">
            <div>
                <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
                <asp:Label ID="nameLbl" runat="server" Text="Test"></asp:Label> 
                <div class="parent" runat="server" id="GridParent" style="border: 0.5px solid #efefef; display: flex; background-color: #ffffff; width: 100%; height: auto; box-shadow: 0 1px 2px 0 rgba(0, 0.1, 0, 0.1);">
                    <asp:Image Class="imgfile" ID="imgfile" runat="server" Width="100%" Height="100%" ImageUrl="~/images/HTML.png" />
     </div>
    <asp:HiddenField ID="InvoiceimgData" runat="server" />
    <asp:Button ID="Button1" runat="server" CssClass="btn btn-primary" Font-Size="10pt" BackColor="#32657c" Text="Mail Invoice" OnClick="ExportToMail" UseSubmitBehavior="false" OnClientClick="return ConvertToMail(this)" />
    <asp:Button ID="Button2" runat="server" CssClass="btn btn-primary" Font-Size="10pt" BackColor="#32657c" Text="Download Invoice" OnClick="ConvertTopdf" UseSubmitBehavior="false" OnClientClick="return ConvertInvoice(this)" />
            </div>
        </form>
    </body>
    </html>
    
    protected void ConvertTopdf(object sender, EventArgs e)
    {
        string imagedata = InvoiceimgData.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);
            
            img.ScaleAbsolute(500, 400);
            pdfDoc.Add(img);
            pdfDoc.Close();
            //Download the PDF file.
            Response.ContentType = "application/pdf";
            Response.AddHeader("content-disposition", "attachment;filename=" + nameLbl.Text + " Invoice.pdf");
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.Write(pdfDoc);
            Response.End();
        }
    }
    protected void ExportToMail(object sender, EventArgs e)
    {
        string imagedata = InvoiceimgData.Value;
        string convert = imagedata.Replace("data:image/png;base64,", String.Empty);
        byte[] imagebytes = Convert.FromBase64String(convert);
        Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 10f);
        using (MemoryStream memoryStream = new MemoryStream())
        {
            PdfWriter writer = PdfWriter.GetInstance(pdfDoc, memoryStream);
            pdfDoc.Open();
            iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(imagebytes);
            img.ScaleAbsolute(500, 400);
            pdfDoc.Add(img);
            pdfDoc.Close();
            byte[] bytes = memoryStream.ToArray();
            memoryStream.Close();
            SmtpClient smtp = new SmtpClient();
            smtp.UseDefaultCredentials = false;
            smtp.Credentials = new NetworkCredential("****", "***");
            smtp.Port = 25;
            smtp.Host = "smtp.office365.com";
            smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
            smtp.EnableSsl = true;
            MailMessage mm = new MailMessage();
            mm.From = new MailAddress("****");
            string sentFrom = "text";
            string[] ToAddress = TextBox1.Text.Split(',');
            foreach (string n in ToAddress)
            {
                mm.To.Add(new MailAddress(n));
            }
            mm.Subject = "INVOICE from " + sentFrom;
            mm.Body = "text";
            mm.Attachments.Add(new Attachment(new MemoryStream(bytes), "Invoice.pdf"));
            mm.IsBodyHtml = true;
            smtp.Send(mm);
            ClientScript.RegisterStartupScript(GetType(), "alert", "alert('Invoice sent to Recipient(s)');", true);
        }
    }
    

    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