I have a concerning issue and that is, when I tried to download in PDF format in my application some elements did not download.
Please is there a way that I can download a section of my web page in PDF format and all the element displays.
I have GridView where BoundField Datafield is used to display data from database. The GridView contains currency symbol.
But the issue is that when I try to download other elements download in the PDF bu the label which holds the currency symbol is not included in the PDF.
Here is my code
GridView (I think it could because I don't have asp:Label control inside of the GridView that display all the data). Since the currncy sumbol is dipsplay directly in Server-Side (C#) Code.
<asp:GridView ID="Gridview1" runat="server" class="table" Font-Size="10pt" HeaderStyle-Font-Size="11pt" AutoGenerateColumns="False" Style="max-width: 100%" RowStyle-Height="40px" HeaderStyle-ForeColor="#00003D"
BorderStyle="None" GridLines="None" Height="50px" HeaderStyle-Height="28px" HeaderStyle-BackColor="#fdfdfd">
<Columns>
<asp:BoundField DataField="Item" HeaderText="Description" ItemStyle-Width="45%" HeaderStyle-Font-Bold="false" />
<asp:BoundField DataField="Qty" HeaderText="Quantity" ItemStyle-Width="10%" HeaderStyle-Font-Bold="false" />
<asp:BoundField DataField="Rate" HeaderText="Rate" ItemStyle-Width="30%" HeaderStyle-Font-Bold="false" />
<asp:BoundField DataField="Amount" HeaderText="Amount" ItemStyle-Width="45%" HeaderStyle-Font-Bold="false" />
</Columns>
<HeaderStyle Height="25px" />
</asp:GridView>
<hr />
<div class="summary" runat="server" id="marking" style="width: 100%; margin: 0 auto; font-weight: 500; margin-top: 3%; margin-bottom: 10%;">
<div class="total" style="float: right; width: 350px; margin-right: 0%; text-align: right; margin-bottom: 3%; font-size: 12px; padding: 12px; line-height: 24.50px; border-radius: 6px; border: 1px solid #e2e2e2;">
<div runat="server" id="stotal" style="margin-bottom: 1%;">
<asp:Label ID="Label1" runat="server" Text="Subtotal:"></asp:Label>
<asp:Label ID="currence" runat="server" Text=""></asp:Label>
<asp:Label ID="lblTotal" runat="server" Font-Size="10pt" Text=""></asp:Label>
</div>
<div runat="server" id="addedtx" style="margin-bottom: 1%;">
<asp:Label ID="Label5" runat="server" Visible="false" Text="VAT(%):"></asp:Label>
<asp:Label ID="vatlbl" runat="server" Text=""></asp:Label>
</div>
<div>
<asp:Label ID="Label6" runat="server" Text="Total:"></asp:Label>
<asp:Label ID="curcy" runat="server" Text=""></asp:Label>
<asp:Label ID="lblGrandTotal" runat="server" Font-Size="11pt" Text=""></asp:Label>
</div>
</div>
</div>
This is where I display from data database and onto my web page
private void ShowDocumentData()
{
try
{
if (Session["InvoiceID"] != null)
{
DataTable dt = new DataTable();
dt.Columns.Add("Item");
dt.Columns.Add("Qty");
dt.Columns.Add("Rate");
dt.Columns.Add("Amount");
dt.Columns.Add("CSymbol");
using (SqlConnection con = new SqlConnection())
{
con.ConnectionString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
using (SqlCommand cmd = new SqlCommand("SELECT Item,Qty,Rate,Amount,CSymbol FROM DocumentTable WHERE (Id = '" + Session["Id"] + "')", con))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
con.Open();
cmd.CommandType = CommandType.Text;
sda.SelectCommand = cmd;
sda.Fill(dt);
DataTable dt1 = dt.Clone();
foreach (DataRow dr in dt.Rows)
{
for (int i = 0; i < dr["Item"].ToString().Split(',').Length; i++)
{
if (!string.IsNullOrEmpty(dr["Item"].ToString().Split(',')[i]))
{
DataRow dr1 = dt1.NewRow();
dr1["Item"] = dr["Item"].ToString().Split(',')[i].Trim();
dr1["Qty"] = dr["Qty"].ToString().Split(',')[i].Trim();
dr1["Rate"] = string.Format("{0} {1}", dr["CSymbol"].ToString(), dr["Rate"].ToString().Split(',')[i].Trim());
dr1["Amount"] = string.Format("{0} {1}", dr["CSymbol"].ToString(), dr["Amount"].ToString().Split(',')[i].Trim());
dt1.Rows.Add(dr1.ItemArray);
}
}
Gridview1.DataSource = dt1;
Gridview1.DataBind();
}
con.Close();
}
}
}
DisplayData();
}
else
{
Response.Redirect("invoice.aspx");
}
}
catch (SqlException ex)
{
string msg = "Error:";
msg += ex.Message;
throw new Exception(msg);
}
}
private void DisplayData()
{
try
{
using (SqlConnection con = new SqlConnection())
{
con.ConnectionString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
using (SqlCommand cmd = new SqlCommand("SELECT * FROM DocumentTable WHERE Id= @Id", con))
{
cmd.Parameters.AddWithValue("@Id", Session["Id"]);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
Lblname.Text = dr["fname"].ToString();
compsign.InnerText = dr["fname"].ToString();
Lbladdress.Text = dr["faddress"].ToString();
Lblmail.Text = dr["fmail"].ToString();
Lblphone.Text = dr["fphone"].ToString();
DateTime time1 = Convert.ToDateTime(dr["CreatedDate"]);
TimeZoneInfo serverTimeZone = TimeZoneInfo.FindSystemTimeZoneById("GMT Standard Time");
DateTime userLocalTime = TimeZoneInfo.ConvertTime(time1, serverTimeZone, TimeZoneInfo.Local);
datLbl.Text = userLocalTime.ToString("ddd, MMM dd, yyyy");
lblprefix.Text = dr["Invoice_no"].ToString();
nameLbl.Text = dr["Tname"].ToString();
addressLbl.Text = dr["Taddress"].ToString();
mailLbl.Text = dr["Tmail"].ToString();
phoneLbl.Text = dr["Tphon"].ToString();
DateTime time2 = Convert.ToDateTime(dr["Datdue"]);
TimeZoneInfo serverTimeZone1 = TimeZoneInfo.FindSystemTimeZoneById("GMT Standard Time");
DateTime userLocalTime1 = TimeZoneInfo.ConvertTime(time2, serverTimeZone1, TimeZoneInfo.Local);
dateLbl.Text = userLocalTime1.ToString("ddd, MMM dd, yyyy");
currence.Text = dr["CSymbol"].ToString();
lblTotal.Text = Convert.ToDecimal(dr["Total"]).ToString("N", new CultureInfo("en-US"));
string WHTax = dr["holdtax"].ToString();
if (WHTax == "0")
{
Labelwht.Visible = false;
whttx.Visible = false;
holdingtx.Visible = false;
}
else
{
Labelwht.Visible = true;
whttx.Text = dr["holdtax"].ToString();
}
string StampDuty = dr["stampD"].ToString();
if (StampDuty == "0")
{
Label20.Visible = false;
stmpd.Visible = false;
duty.Visible = false;
}
else
{
Label20.Visible = true;
stmpd.Text = dr["stampD"].ToString();
}
string TaxValue = dr["VAT"].ToString();
if (TaxValue == "0")
{
Label5.Visible = false;
vatlbl.Visible = false;
addedtx.Visible = false;
}
else
{
Label5.Visible = true;
vatlbl.Text = dr["VAT"].ToString();
}
curcy.Text = dr["CSymbol"].ToString();
lblGrandTotal.Text = Convert.ToDecimal(dr["GrandTotal"]).ToString("N", new CultureInfo("en-US"));
byte[] image = (byte[])dr["logo"];
imgFileUpload.ImageUrl = "data:image/jpeg;base64," + Convert.ToBase64String(image);
byte[] bytes = (byte[])dr["signature"];
Image2.ImageUrl = "data:image/jpeg;base64," + Convert.ToBase64String(bytes);
note.InnerText = dr["Notes"].ToString();
}
con.Close();
}
}
}
catch (SqlException ex)
{
string msg = "Error:";
msg += ex.Message;
throw new Exception(msg);
}
}
How I download in PDF
protected void Button3_Click(object sender, EventArgs e)
{
try
{
using (SqlConnection con = new SqlConnection())
{
con.ConnectionString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
using (SqlCommand cmd = new SqlCommand("SELECT * FROM DocumentTable WHERE Id =@Id", con))
{
cmd.Parameters.AddWithValue("@Id", lblprefix.Text);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
byte[] image = (byte[])dr["logo"];
imgFileUpload.ImageUrl = "data:image/jpeg;base64," + Convert.ToBase64String(image);
byte[] bytes = (byte[])dr["signature"];
Image2.ImageUrl = "data:image/jpeg;base64," + Convert.ToBase64String(bytes);
File.WriteAllBytes(Server.MapPath("logo.jpg"), image);
File.WriteAllBytes(Server.MapPath("sign.jpg"), bytes);
Image2.ImageUrl = GetUrl("sign.jpg");
imgFileUpload.ImageUrl = GetUrl("logo.jpg");
}
var ImagUrl = imgFileUpload.ImageUrl;
var ImgeUrl = Image2.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 + " Invoice" + DateTime.Now.ToString("MMM d, yyyy") + ".pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Write(pdfDoc);
File.Delete(Server.MapPath("sign.jpg"));
File.Delete(Server.MapPath("logo.jpg"));
Image2.ImageUrl = ImgeUrl;
imgFileUpload.ImageUrl = ImagUrl;
Response.End();
con.Close();
}
}
}
catch (SqlException ex)
{
string msg = "Error:";
msg += ex.Message;
throw new Exception(msg);
}
}