Keep headerstyle color and also div font style in pdf format

Donald Symmons 3,066 Reputation points
2024-11-01T07:32:54.2366667+00:00

I have asked a similar question in one of my posts. However, this has a bit of twist. I have a code that downloads or send a receipt to an email in PDF format. Once the button is clicked, it downloads the receipt and another button sends to email. The twist I mentioned is that there is a grid view header style color and font style set from database value onto the receipt. I was able to make the receipt print the grid view header style color but two issues arise:

1. The grid view header style color downloads in pdf format with the color, but the grid view does not cover the width of the paper. Here is how it is

half gridview 2. I wanted the font to show on the entire receipt, but the font style does not show when it downloads in pdf

HTML

<div class="wrapper">
            <div class="col-sm-10" runat="server" id="Template" style="width: 100%; margin: 0 auto; padding: 6px; margin-bottom: 20px;">
                <div class="col-sm-10" style="width: 100%; margin: 0 auto; padding: 6px;">
                    <asp:Panel ID="Panel1" runat="server" Width="100%">
                        <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 class="grid-corner" style="width: 100%; font-size: 9pt; margin: 0 auto; padding: 10px; padding-bottom: 6px;">
                                <div class="heading" style="font-size: 20px; margin-top: 2%; margin-bottom: 4%">
                                    <div style="width: 100%; display: inline-block; font-size: 10px; line-height: 1.4;">
                                        <div style="float: left; text-align: left;">
                                            <div>
                                                <asp:Image ID="Imglogo" runat="server" Height="48" ImageUrl="~/images/myfavicon.png" />
                                            </div>
                                            <div style="font-weight: 600;">
                                                <asp:Label ID="Lblname" runat="server" Text="Alan Shopping Mall" Font-Size="12pt"></asp:Label>
                                            </div>
                                            <div>
                                                <asp:Label ID="Lbladdress" runat="server" Font-Size="10pt" Text="10 Tims Avenue"></asp:Label>
                                            </div>
                                            <div>
                                                <asp:Label ID="Lblphone" runat="server" Text="00000000000" Font-Size="10pt"></asp:Label>
                                            </div>
                                            <div>
                                                <asp:Label ID="MailLabel" runat="server" Font-Size="10pt" Text="******@mail.com"></asp:Label>
                                            </div>
                                        </div>
                                        <div style="margin-bottom: 3%; float: right; display: inline-block;">
                                            <label runat="server" id="header" style="font-size: 16pt; font-weight: 600;">Receipt</label>
                                            <div>
                                                <asp:Label ID="lblprefix" class="ui-widget-content" runat="server" Font-Size="11pt" Text="Ref No: A098448300"></asp:Label>
                                            </div>
                                        </div>
                                    </div>
                                    <hr style="height: 0.5px; color: #ccc;" />
                                </div>
                                <asp:Label ID="securelbl" runat="server" Visible="false" ForeColor="#40576d" Text=""></asp:Label>
                                <div class="customer" style="width: 100%; line-height: 1.4; margin-top: 3%; margin-bottom: 10%;">
                                    <div style="float: left; text-align: start; margin-bottom: 5%; font-size: 1.6rem;">
                                        <div>
                                            <asp:Label ID="Label4" class="ui-widget-content" runat="server" Text="Bill To:" Font-Size="10pt"></asp:Label>
                                        </div>
                                        <div style="font-weight: 600;">
                                            <asp:Label ID="nameLbl" class="ui-widget-content" runat="server" Font-Size="11pt" Text="Dominic Lawrence"></asp:Label>
                                        </div>
                                        <div>
                                            <asp:Label ID="addressLbl" class="ui-widget-content" runat="server" Font-Size="10pt" Text="38 Royal Gardens Road"></asp:Label>
                                        </div>
                                        <div>
                                            <asp:Label ID="phoneLbl" class="ui-widget-content" runat="server" Text="08011111111" Font-Size="10pt"></asp:Label>
                                        </div>
                                        <div>
                                            <asp:Label ID="mailLbl" CssClass="ui-widget-content" runat="server" Text="******@mail.com" Font-Size="10pt"></asp:Label>
                                        </div>
                                    </div>
                                    <div style="float: right; text-align: right; margin-bottom: 5%;">
                                        <div>
                                            <asp:Label ID="Label9" class="ui-widget-content" runat="server" Font-Size="10pt" type="date" Text="Date: "></asp:Label>
                                            &nbsp;<asp:Label ID="dateLbl" class="ui-widget-content" runat="server" Font-Size="10pt" Text="October 31, 2024"></asp:Label>
                                        </div>
                                    </div>
                                </div>
                                <br />
                                <div style="width: 100%; margin-top: 10%; margin-bottom: 2%;">
                                    <asp:GridView ID="Gridview2" runat="server" HorizontalAlign="Center" RowStyle-Width="100%" RowStyle-CssClass="table" CssClass="table table-condensed" Font-Size="10pt" HeaderStyle-Width="100%" HeaderStyle-Font-Bold="true" HeaderStyle-Font-Size="10pt" AutoGenerateColumns="False" Style="width: 100%; font-weight: 400;" RowStyle-Height="50px"
                                        BorderStyle="None" GridLines="None" Height="70px" HeaderStyle-Height="50px">
                                        <Columns>
                                            <asp:BoundField DataField="Item" HeaderText="Items/Goods" />
                                            <asp:BoundField DataField="Quantity" HeaderText="Quantity" />
                                            <asp:BoundField DataField="Price" HeaderText="Price" />
                                            <asp:BoundField DataField="Amount" HeaderText="Amount" />
                                        </Columns>
                                        <HeaderStyle Height="35px" />
                                    </asp:GridView>
                                    <hr />
                                </div>
                                <div runat="server" style="width: 100%; margin: 0 auto; font-weight: 500; margin-bottom: 10%;">
                                    <div class="total" style="float: right; margin-right: 0%; margin-bottom: 3%; font-size: 12px; padding: 10px; line-height: 24.50px; border-radius: 6px;">
                                        <div style="float: left; text-align: right; margin-right: 50px;">
                                            <div style="margin-bottom: 4px;">
                                                <asp:Label ID="Label2" runat="server" Text="Subtotal:"></asp:Label>
                                            </div>
                                            <div>
                                                <asp:Label ID="Label6" runat="server" Text="Total:"></asp:Label>
                                            </div>
                                        </div>
                                        <div style="float: right; text-align: right; display: inline-block;">
                                            <div runat="server" id="stotal" style="margin-bottom: 4px;">
                                                <asp:Label ID="currency" runat="server" Font-Size="10pt" Text=""></asp:Label>
                                                <asp:Label ID="lblTotal" runat="server" Font-Size="10pt" Text="2,100"></asp:Label>
                                            </div>
                                            <div>
                                                <label runat="server" id="getCrrency" style="font-size: 11pt; font-weight: 500;"></label>
                                                <asp:Label ID="lblGrandTotal" runat="server" Font-Size="11pt" Text="2,100"></asp:Label>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </asp:Panel>
                </div>
                <div style="margin-top: 1%; padding: 10px;">
                    <div class="container-fluid col-sm-11" id="Card1" style="width: 100%; margin: 0 auto; border: 1px solid #e4e7e8; border-radius: 6px; background: #fff;">
                        <div style="width: 100%; margin: 0 auto; padding: 10px; position: center; width: 100%; font-weight: 500; font-size: 10pt;">
                            <p style="font-size: 10pt; font-weight: 400; color: #145c7c; text-align: center;">Download receipt or send receipt to customer via email in PDF Format</p>
                            <div class="row">
                                <div class="col-md-12">
                                    <div class="form-group">
                                        <div class="input-group">
                                            <asp:TextBox ID="TextBox1" placeholder="email address" Width="300px" Height="30px" CssClass="form-control" Font-Size="10pt" runat="server"></asp:TextBox>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-12">
                                    <div class="form-group">
                                        <div class="input-group">
                                            <asp:TextBox ID="bodyMail" runat="server" AutoCompleteType="None" CssClass="form-control" placeholder="Your message" TextMode="MultiLine" Style="overflow: hidden; resize: none;" oninput="Resize(this)" />
                                            <script type="text/javascript">
                                                function Resize(textbox) {
                                                    textbox.style.height = "";
                                                    textbox.style.height = Math.min(textbox.scrollHeight, 300) + "px";
                                                }
                                            </script>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <asp:Button ID="Button1" runat="server" CssClass="btn btn-primary" Font-Size="10pt" BackColor="#32657c" Text="Mail Receupt" OnClick="ExportReceiptToMail" />
                            <asp:Button ID="Button2" runat="server" CssClass="btn btn-primary" Font-Size="10pt" BackColor="#32657c" Text="Download Receipt" OnClick="DownloadReceipt" />
                            <br />
                        </div>
                    </div>
                </div>
                <br />
            </div>
        </div>
protected void Page_Load(object sender, EventArgs e)
        {
            GetData();
            GetDesign();
        }
        private void GetData()
        {
            if (!this.IsPostBack)
            {
                DataTable dt = new DataTable();
                dt.Columns.AddRange(new DataColumn[4] {
                            new DataColumn("Item", typeof(string)),
                            new DataColumn("Quantity", typeof(string)),
                            new DataColumn("Price", typeof(string)),
                            new DataColumn("Amount",typeof(string)) });
                dt.Rows.Add("Rice", "1", "500", "500");
                dt.Rows.Add("Corn", "1", "100", "100");
                dt.Rows.Add("Spoon", "10", "50", "500");
                dt.Rows.Add("Sneakers", "1", "1000", "1000");
                Gridview2.DataSource = dt;
                Gridview2.DataBind();
            }
        }
        private void GetDesign()
        {
            using (SqlConnection con = new SqlConnection())
            {
                con.ConnectionString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
                using (SqlCommand cmd = new SqlCommand("SELECT * FROM DesignTable WHERE CreatedBy = @CreatedBy", con))
                {
                    cmd.Parameters.AddWithValue("@CreatedBy", 1);
                    con.Open();
                    SqlDataReader dr = cmd.ExecuteReader();
                    if (dr.Read())
                    {
                        string Colorlbl = dr[7].ToString();
                        Color color = Color.FromName(Colorlbl);
                        var invertColor = Color.FromArgb(color.ToArgb() ^ 0xffffff);
                        Gridview2.HeaderStyle.BackColor = color;
                        Gridview2.HeaderStyle.ForeColor = invertColor;
                        Gridview2.ForeColor = color;
                        string LabelFont = dr[2].ToString();
                        Page.Header.Controls.Add(new System.Web.UI.LiteralControl("<link rel=\"stylesheet\" type=\"text/css\" href=\" https://fonts.googleapis.com/css?family=" + LabelFont + "\" />"));
                        Gridview2.Attributes["style"] = "font-family: \'" + LabelFont + "\';";
                    }
                    con.Close();
                }
            }
        }
        protected void DownloadReceipt(object sender, EventArgs e)
        {
            try
            {
                using (SqlConnection con = new SqlConnection())
                {
                    con.ConnectionString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
                    using (SqlCommand cmd = new SqlCommand("SELECT * FROM receipttable WHERE reference =@reference", con))
                    {
                        cmd.Parameters.AddWithValue("@reference", lblprefix.Text);
                        con.Open();
                        SqlDataReader dr = cmd.ExecuteReader();
                        if (dr.Read())
                        {
                            byte[] image = (byte[])dr["logo"];
                            Imglogo.ImageUrl = "data:image/jpeg;base64," + Convert.ToBase64String(image);
                            File.WriteAllBytes(Server.MapPath("logo.jpg"), image);
                            Imglogo.ImageUrl = GetUrl("logo.jpg");
                        }
                        var ImgUrl = Imglogo.ImageUrl;

                        StringWriter sw = new StringWriter();
						//Here I called the private void function GetDesign
                        GetDesign(); //This is where I added the function  that sets the color and font style to b downloaded in the pdf

                        HtmlTextWriter hw = new HtmlTextWriter(sw);
                        Panel1.RenderControl(hw);
                        StringReader sr = new StringReader(sw.ToString());
                        Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 10f);
                        PdfWriter PdfWriter = PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
                        HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);
                        htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());
                        ICSSResolver cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false);
                        cssResolver.AddCssFile(Server.MapPath("~/css/style2.css"), true);
                        IPipeline pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlContext, new PdfWriterPipeline(pdfDoc, PdfWriter)));
                        var worker = new XMLWorker(pipeline, true);
                        var xmlParse = new XMLParser(true, worker);
                        pdfDoc.Open();
                        xmlParse.Parse(sr);
                        xmlParse.Flush();
                        pdfDoc.Close();
                        Response.ContentType = "application/pdf";
                        Response.AddHeader("content-disposition", "attachment;filename=" + Lblname.Text + " Receipt - " + DateTime.Now.ToString("MMM dd yyyy") + ".pdf");
                        Response.Cache.SetCacheability(HttpCacheability.NoCache);
                        Response.Write(pdfDoc);
                        File.Delete(Server.MapPath("logo.jpg"));
                        Imglogo.ImageUrl = ImgUrl;
                        Response.End();
                        con.Close();
                    }
                }
            }
            catch (SqlException ex)
            {
                string msg = "Error:";
                msg += ex.Message;
                throw new Exception(msg);
            }
        }
        protected void ExportReceiptToMail(object sender, EventArgs e)
        {
            try
            {
                if (!string.IsNullOrEmpty(TextBox1.Text))
                {
                    using (SqlConnection con = new SqlConnection())
                    {
                        con.ConnectionString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
                        using (SqlCommand cmd = new SqlCommand("SELECT * FROM receipttable WHERE reference = @reference", con))
                        {
                            cmd.Parameters.AddWithValue("@reference", lblprefix.Text);
                            con.Open();
                            SqlDataReader dr = cmd.ExecuteReader();
                            if (dr.Read())
                            {
                                byte[] image = (byte[])dr["logo"];
                                Imglogo.ImageUrl = "data:image/jpeg;base64," + Convert.ToBase64String(image);

                                File.WriteAllBytes(Server.MapPath("logo.jpg"), image);
                                Imglogo.ImageUrl = GetUrl("logo.jpg");
                            }
                            var ImgeUrl = Imglogo.ImageUrl;

                            using (StringWriter sw = new StringWriter())
                            {
								//I also called the private void function "GetDesign" here
                                GetDesign(); //This is where I added the function  that sets the color and font style to b downloaded in the pdf

                                using (HtmlTextWriter hw = new HtmlTextWriter(sw))
                                {
                                    this.Panel1.RenderControl(hw);
                                    StringReader sr = new StringReader(sw.ToString());
                                    Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
                                    using (MemoryStream memoryStream = new MemoryStream())
                                    {
                                        PdfWriter PdfWriter = PdfWriter.GetInstance(pdfDoc, memoryStream);
                                        HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);
                                        htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());
                                        ICSSResolver cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false);
                                        cssResolver.AddCssFile(Server.MapPath("~/css/style2.css"), true);
                                        IPipeline pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlContext, new PdfWriterPipeline(pdfDoc, PdfWriter)));
                                        var worker = new XMLWorker(pipeline, true);
                                        var xmlParse = new XMLParser(true, worker);
                                        pdfDoc.Open();
                                        xmlParse.Parse(sr);
                                        xmlParse.Flush();
                                        pdfDoc.Close();
                                        File.Delete(Server.MapPath("logo.jpg"));
                                        Imglogo.ImageUrl = ImgeUrl;
                                        byte[] bytes = memoryStream.ToArray();
                                        memoryStream.Close();

                                        MailMessage mm = new MailMessage();
                                        mm.From = new MailAddress("******@josmade.com");
                                        string sentFrom = Lblname.Text;
                                        string[] ToAddress = TextBox1.Text.Split(',');
                                        foreach (string n in ToAddress)
                                        {
                                            mm.To.Add(new MailAddress(n));
                                        }
                                        mm.Subject = "RECEIPT from " + sentFrom;
                                        mm.Body = bodyMail.Text;
                                        mm.Attachments.Add(new Attachment(new MemoryStream(bytes), Lblname.Text + " Receipt - " + DateTime.UtcNow.ToString("MMM dd, yyyy") + ".pdf"));
                                        mm.IsBodyHtml = true;
                                        SmtpClient smtp = new SmtpClient();
                                        smtp.Host = "relay-hosting.secureserver.net";
                                        smtp.EnableSsl = false;
                                        System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
                                        NetworkCred.UserName = "******@josmade.com";
                                        NetworkCred.Password = "***************";
                                        smtp.UseDefaultCredentials = true;
                                        smtp.Credentials = NetworkCred;
                                        smtp.Port = 25;
                                        smtp.Send(mm);
                                    }
                                }
                            }
                            con.Close();
                        }
                    }
                    string message = "alert('Reeipt successfully sent to customer!')";
                    ScriptManager.RegisterClientScriptBlock((sender as Control), this.GetType(), "alert", message, true);
                }
                else
                {
                    string message = "alert('Please add customer email address')";
                    ScriptManager.RegisterClientScriptBlock((sender as Control), this.GetType(), "alert", message, true);
                }
            }
            catch (SqlException ex)
            {
                string msg = "Error:";
                msg += ex.Message;
                throw new Exception(msg);
            }
        }
        public string GetUrl(string imagepath)
        {
            string[] splits = Request.Url.AbsoluteUri.Split('/');
            if (splits.Length >= 2)
            {
                string url = splits[0] + "//";
                for (int i = 2; i < splits.Length - 1; i++)
                {
                    url += splits[i];
                    url += "/";
                }
                return url + imagepath;
            }
            return imagepath;
        }

Developer technologies | .NET | Other
Developer technologies | Visual Studio | 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
    2024-11-01T10:06:38.5633333+00:00

    Hi @Donald Symmons,

    The grid view header style color downloads in pdf format with the color, but the grid view does not cover the width of the paper. Here is how it is

    In gridview style add width: 100%.

     Gridview2.Attributes["style"] = "font-family: \'" + LabelFont + "\';width:100%";
    

    I wanted the font to show on the entire receipt, but the font style does not show when it downloads in pdf

    From my research, this seems to be a design issue with iTextSharp itself, which cannot preserve styles.

    Since iTextSharp is a third-party library, I am not very familiar with it. Maybe you can look for support for iTextSharp.

    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

    1 person found this answer helpful.

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.