Hi
I have a code that downloads or send a receipt in PDF format; once the button is clicked, it downloads the receipt and another button sends to email. But in this issue, there is a gridview color and font for the labels, which is set from database value. How do I make it that when the receipt is downloaded in PDF format, it will show the color and the font. Please note that the font and the gridview color are set from database value. Is there a way I can download as PDF and still keep the look of the receipt as it is showed in the page?
MY FULL HTML
<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='https://fonts.googleapis.com/css?family=Nunito' rel='stylesheet' />
<link href="css/bootstrap.min.css" rel="stylesheet" media="all" />
<link href="css/bootstrap.css" rel="stylesheet" media="all" />
<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png" />
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png" />
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png" />
<title></title>
<style type="text/css">
body {
font-size: 1.6rem;
line-height: 1.5;
color: #011b33;
}
.wrapper {
display: flex;
width: 100%;
align-items: stretch;
}
#Button1 {
font-family: 'Graphik', sans-serif;
border-radius: 5px;
background-color: #0ba4db;
color: #ffffff;
padding: 6px;
border-color: #0ba4db;
height: 32px;
line-height: 1.6;
padding-left: 1em;
padding-right: 1em;
display: inline-block;
font-size: 1.1rem;
white-space: nowrap;
vertical-align: middle;
}
.grids {
overflow-y: scroll;
height: 550px;
width: 100%;
}
.grid-corner {
border: 0px solid #C0C0C0;
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
border-radius: 4px;
overflow-x: scroll;
}
#GridParent {
background-color: #ffffff;
background-size: 100% 100%;
background-repeat: no-repeat;
height: auto;
box-shadow: 0 1px 2px 0 rgba(0, 0.1, 0, 0.1);
}
</style>
</head>
<body>
<form id="form1" runat="server">
<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="alan@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="dlaw@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>
<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>
</form>
</body>
</html>
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.IO;
using System.Data;
using System.Net.Mail;
using System.Configuration;
using System.Drawing;
using System.Data.SqlClient;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.tool.xml;
using iTextSharp.tool.xml.html;
using iTextSharp.tool.xml.parser;
using iTextSharp.tool.xml.pipeline.css;
using iTextSharp.tool.xml.pipeline.end;
using iTextSharp.tool.xml.pipeline.html;
protected void Page_Load(object sender, EventArgs e)
{
GetData();
GetDesignViews();
}
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 GetDesignViews()
{
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", 9);
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();
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=" + nameLbl.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())
{
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("josmadestores@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 = "josmadestores@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;
}