Dynamically creating a grid view in pdf using itextsharp - c#

protected void ExportToPdf(DataTable dt, string str)
{
ArrayList ADA = new ArrayList();
ADA.Add(FirstAssignment.SelectedItem);
ADA.Add(SecondAssignment.SelectedItem);
GridView GridView1 = new GridView();
GridView GridView2 = new GridView();
GridView1.ShowHeaderWhenEmpty = true;
GridView1.AllowPaging = false;
GridView1.DataSource = dt;
GridView1.DataBind();
int i1 = GridView1.Columns.Count;
GridView1.HeaderRow.Cells[1].Text = ADA[0].ToString();
GridView1.HeaderRow.Cells[2].Text = ADA[1].ToString();
GridView1.HeaderRow.Cells[3].Text = "% of Improvement from " + (ADA[0].ToString()) + " to " + (ADA[1].ToString());
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.ContentType = "application/pdf";
HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + str + ".pdf");
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView1.AllowPaging = false;
GridView1.HeaderRow.ForeColor = System.Drawing.Color.Black;
GridView1.FooterRow.ForeColor = System.Drawing.Color.Black;
GridView1.HeaderRow.Style.Add("font-Color", "Black");
GridView1.HeaderRow.Style.Add("font-size", "13px");
GridView1.HeaderRow.Style.Add("text-decoration", "none");
GridView1.HeaderRow.Style.Add("font-family", "Arial, Helvetica, sans-serif;");
GridView1.Style.Add("font-Color", "Black");
GridView1.Style.Add("text-decoration", "none");
GridView1.Style.Add("font-family", "Arial, Helvetica, sans-serif;");
GridView1.Style.Add("font-size", "11px");
GridView1.ForeColor = System.Drawing.Color.Black;
Document pdfDoc = new Document(PageSize.A2, 7f, 7f, 7f, 0f);
GridView1.RenderControl(hw);
StringReader sr = new StringReader(sw.ToString());
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
// HTMLWorker htmlparser1 = new HTMLWorker(pdfDoc);
PdfWriter.GetInstance(pdfDoc, HttpContext.Current.Response.OutputStream);
pdfDoc.Open();
pdfDoc.Add(new Paragraph("hey! rashmi"));
htmlparser.Parse(sr);
pdfDoc.Close();
HttpContext.Current.Response.Write(pdfDoc);
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
This is for creating one grid view. can any one help me to create a dynamic grid view using this code.I have tried to giving a for loop GridView1.RenderControl(hw); but I am getting single grid view with same data.Thanks in advance.

If you want show gridview in pdf,you can show as table also here is
code :
public void createPdf()
{
// step 1
using (MemoryStream ms = new MemoryStream())
{
Document document = new Document(iTextSharp.text.PageSize.A4, 10, 22, 34, 34);
// step 2
PdfWriter writer = PdfWriter.GetInstance(document, ms);
// step 3
document.Open();
MemoryStream stream = new MemoryStream();
// step 4 how many tables you want to create
for (int i = 0; i < 5; i++)
{
document.Add(new Paragraph("Table:"));
document.Add(createFirstTable());
}
// step 5
document.Close();
writer.Close();
Response.ContentType = "pdf/application";
Response.AddHeader("content-disposition",
"attachment;filename=First PDF document.pdf");
Response.OutputStream.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length);
}
}
public static PdfPTable createFirstTable(DataTable dt)
{
// a table with three columns
PdfPTable table = new PdfPTable(dt.Columns.Count);
// the cell object
PdfPCell cell;
// we add a cell with colspan 3
//cell = new PdfPCell(new Phrase("Cell with colspan 3"));
table.AddCell(cell);
//// now we add a cell with rowspan 2
cell = new PdfPCell(new Phrase("Cell with rowspan 2"));
table.AddCell("ADXHGS");
table.AddCell("WFEWSA");
table.AddCell("EWSFCEDSW");
table.AddCell("EWSEWSFDFCEDSW");
//PdfTable.SpacingBefore = 15f; // Give some space after the text or it may overlap the table
return table;
}

Related

Saving Exported PDF File to Specified Location in ASP.NET Project Folder

May i know how to specify the path to save the exported PDF File with the codes below?
The file will be later required to be used as an attachment with an email.
Been looking at different posts on stackoverflow can't seem to find one that solves my issue.
protected void BTN_Export_Click(object sender, EventArgs e)
{
Document pdfDocument = new Document(PageSize.A4, 40f, 40f, 40f, 40f);
Font NormalFont = FontFactory.GetFont("Arial", 12, Font.NORMAL, BaseColor.BLACK);
Font BoldFontForHeader = FontFactory.GetFont("Arial", 13, Font.BOLD, BaseColor.BLACK);
//String path = Server.MapPath("C:\\Users\\Dom\\Downloads\\WebFormApplication\\WebFormApplication\\WebFormApplication\\Exported Documents");
using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
{
PdfWriter writer = PdfWriter.GetInstance(pdfDocument, memoryStream);
//var output = new FileStream(Path.Combine("C:\\Users\\Dom\\Downloads\\WebFormApplication\\WebFormApplication\\WebFormApplication\\Exported Documents", "BedsListExport.pdf"), FileMode.Create);
//PdfWriter.GetInstance(pdfDocument, new FileStream(path, FileMode.Create));
//Phrase phrase = null;
PdfPCell cell = null;
//PdfPTable bedsTable = null;
PdfPTable bedsTable = new PdfPTable(Beds.HeaderRow.Cells.Count);
bedsTable.TotalWidth = 550f;
bedsTable.LockedWidth = true;
bedsTable.HorizontalAlignment = Element.ALIGN_CENTER;
bedsTable.SetWidths(new float[] { 0.3f, 0.3f, 0.5f, 0.2f, 0.2f, 0.2f, 0.3f, 0.5f });
bedsTable.SpacingBefore = 30f;
//Headers
string[] headersName = { "Bed ID", "Patient ID", "Patient Name", "Class", "Block", "Level", "Staff Incharge ID", "Date & Time Assigned" };
for (int i = 0; i < headersName.Length; i++)
{
PdfPCell hCell = new PdfPCell(new Phrase(headersName[i].ToString(), BoldFontForHeader));
bedsTable.AddCell(hCell);
}
foreach (GridViewRow row in Beds.Rows)
{
foreach (TableCell tableCell in row.Cells)
{
cell = new PdfPCell(new Phrase(tableCell.Text));
cell.Padding = 5;
bedsTable.AddCell(cell);
}
}
pdfDocument.Open();
//Top of Document
Paragraph p1 = new Paragraph("Mount Olympus Hospital", new Font(Font.FontFamily.HELVETICA, 18));
Paragraph p2 = new Paragraph("24 Jalan Kapal Street 42 Singapore 554524", new Font(Font.FontFamily.HELVETICA, 12));
Paragraph p3 = new Paragraph("Telephone: 6550-9514 Fax: 6550-9245", new Font(Font.FontFamily.HELVETICA, 12));
p1.Alignment = Element.ALIGN_CENTER;
p2.Alignment = Element.ALIGN_CENTER;
p3.Alignment = Element.ALIGN_CENTER;
pdfDocument.Add(p1);
pdfDocument.Add(p2);
pdfDocument.Add(p3);
Paragraph p4 = new Paragraph("Beds List", new Font(Font.FontFamily.HELVETICA, 16));
p4.Alignment = Element.ALIGN_LEFT;
p4.SpacingBefore = 20f;
pdfDocument.Add(p4);
pdfDocument.Add(bedsTable);
pdfDocument.Close();
byte[] bytes = memoryStream.ToArray();
memoryStream.Close();
Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=BedsListExport.pdf");
Response.ContentType = "application/pdf";
Response.Buffer = true;
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.BinaryWrite(bytes);
Response.End();
Response.Close();
}
}
Added these lines of codes, but still doesn't work
using (System.IO.FileStream fs = new System.IO.FileStream(Server.MapPath("C:\\Users\\Dom\\Downloads\\WebFormApplication\\WebFormApplication\\WebFormApplication\\Exported Documents") + fileName, System.IO.FileMode.CreateNew, System.IO.FileAccess.ReadWrite))
{
memoryStream.Position = 0;
memoryStream.CopyTo(fs);
}
I have tried different lines of codes from different sources too. This is my first time using MemoryStream, FileStream and iTextSharp...
Appreciate any help please.

How to clear gridview after generating pdf

I have a project where I want to generate a PDF from gridview but after generating Pdf I want to refresh my gridview and add new data.
private void Generate_PDF()
{
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
StringBuilder sb = new StringBuilder();
StringBuilder sb1 = new StringBuilder();
//Generate Invoice (Bill) Header.
sb.Append("<table width='100%' cellspacing='0' cellpadding='2'>");
sb.Append("<tr><td align='center' style='background-color: #18B5F0' colspan = '2'><b>Bill Report</b></td></tr>");
sb.Append("<tr><td colspan = '2'></td></tr>");
sb.Append("<tr><td><b>Bill No: </b>");
sb.Append(HiddenField1.Value);
sb.Append("</td><td align = 'right'><b>Date: </b>");
sb.Append(DateTime.Now);
sb.Append(" </td></tr>");
sb.Append("</table>");
sb.Append("<br />");
GridOfTestRequest.RenderControl(hw);
StringReader sr = new StringReader(sw.ToString());
StringReader sr1 = new StringReader(sb.ToString());
sb1.Append("<table border = '1'>");
sb1.Append("<tr><td align = 'right' colspan = '");
sb1.Append(GridOfTestRequest.HeaderRow.Cells.Count - 1);
sb1.Append("'>Total</td>");
sb1.Append("<td>");
sb1.Append(testList.Sum(x=>x.testFee));
sb1.Append("</td>");
sb1.Append("</tr></table>");
StringReader sr2 = new StringReader(sb1.ToString());
testList.Clear();
GridOfTestRequest.DataSource = null;
GridOfTestRequest.DataBind();
Document pdfDoc = new Document(PageSize.A5, 10f, 10f, 10f, 0f);
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
PdfWriter writer = PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
htmlparser.Parse(sr1);
htmlparser.Parse(sr);
htmlparser.Parse(sr2);
pdfDoc.Close();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=Invoic.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Write(pdfDoc);
Response.Flush();
Response.ClearContent();
Response.Clear();
Response.Cookies.Clear();
Response.End();
}
After execution of this method in a button click, I want to clear the Gridview. How can I do it? I tried to clear it with gridview.datasource=null but it doesn't work.

Background Color of Table is not shown in iTextSharp PDF

I generate a Table object where some cells have a background-color. This background-color is dynamically loaded from a database.
I set the BackColor in my code with the following lines:
TableCell tCell = new TableCell();
tCell.BackColor = (Color)converter.ConvertFromString(color_startBorderCrtColor);
tCell.Text = Convert.ToString(row[column.ColumnName]);
tRow.Cells.Add(tCell);
When I append the rendered table to a StringBuilder and write it into a PDF using iTextSharp the Background-Color of the cells is not shown. Instead when I write the StringBuilder into a literal the cells are painted correctly.
Here is the code how I convert the Table and append it to my StringBuilder:
TextWriter tw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(tw);
Table myGenTable = (Table)genObjects[0];
myGenTable.RenderControl(hw);
sb.Append(tw.ToString()); //sb is the StringBuilder I'm working with
Is there a way where I can paint the ccells even in the pdf codument?
The same problem exists with the border of the table which is set as attributes to the table itself with the following code:
tblcblCellsCQ.BorderColor = Color.Black;
tblcblCellsCQ.BorderWidth = 2;
tblcblCellsCQ.BorderStyle = BorderStyle.Dashed;
Here is the code where I write the StringBuilder into the PDF file:
StringReader sr = new StringReader(sb.ToString());
Document pdfDoc = new Document(PageSize.A4.Rotate(), 10f, 10f, 10f, 0f);
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
PdfWriter writer = PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
htmlparser.Parse(sr);
pdfDoc.Close();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=" + friendlyName + ".pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Write(pdfDoc);
Response.End();
Try this :
for (int i = 0; i < col.Length; ++i)
{
Cell cell = new Cell(new Phrase(col[i], new iTextSharp.text.Font(iTextSharp.text.Font.COURIER, 5)));
cell.Header = true;
cell.BackgroundColor = new iTextSharp.text.Color(204, 204, 204);
table.AddCell(cell);
}
check the answer at : https://forums.asp.net/t/1577892.aspx?iTextSharp+table+headers

Change the Color of header when exporting gridview to PDf

I'm exporting gridview to pdf. Everything works, however, when PDF is generated the background is white and the header font color is grey. It's really hard to see. I'm trying to change the header forecolor to black before the export. It's not working.
Any suggestions?
public void ExportToPDF()
{
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=CallDetail.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView1.AllowPaging = false;
this.GetData();
GridView1.RenderControl(hw);
HtmlForm frm = new HtmlForm();
frm.Attributes["runat"] = "server";
GridView1.HeaderRow.Style.Add("width", "15%");
GridView1.HeaderRow.Style.Add("font-size", "10px");
GridView1.Style.Add("text-decoration", "none");
GridView1.Style.Add("font-family", "Arial, Helvetica, sans-serif;");
GridView1.Style.Add("font-size", "26px");
for (int col = 0; col < GridView1.HeaderRow.Controls.Count; col++)
{
TableCell tc = GridView1.HeaderRow.Cells[col];
tc.Style.Add("color", "#FFFFFF");
tc.Style.Add("background-color", "#444");
}
StringReader sr = new StringReader(sw.ToString());
Document pdfDoc = new Document(PageSize.A2, 7f, 7f, 7f, 0f);
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
htmlparser.Parse(sr);
pdfDoc.Close();
Response.Write(pdfDoc);
Response.End();
}
UPDATE*** added updated code and screenshot.
Directly setting the header's ForeColor before export doesn't really affect the headerstyle. May be an alternative is to iterate over all the header cells and set to whatever styles you need (this really works). You can try changing the below line of code
GridView1.HeaderStyle.ForeColor = System.Drawing.Color.Black;
with
for (int col = 0; col < GridView1.HeaderRow.Controls.Count; col++)
{
TableCell tc = GridView1.HeaderRow.Cells[col];
tc.Style.Add("color", "#FFFFFF");
tc.Style.Add("background-color", "#444");
}

Set font for all text from Pdfptable with Itextsharp

var htmlarraylist = HTMLWorker.ParseToList(new StringReader(htmlText), styles);
document.Open();
BaseFont Vn_Helvetica = BaseFont.CreateFont(#"C:\Windows\Fonts\arial.ttf",
"Identity-H", BaseFont.EMBEDDED);
Font fontNormal = new Font(Vn_Helvetica, 12, Font.NORMAL);
foreach (var t in htmlarraylist)
{
if (t is PdfPTable)
{
//how set fontNormal all text from Pdfptable ?
}
document.Add((IElement)t);
}
document.Close();
Can someone help me please
Please try by setting font to the PdfPTable.DefaultCell property in you foreach loop
Example:
t.DefaultCell.Phrase = new Phrase() { Font = fontNormal };
i have try set font family in pdf template. and show the following error also
'BaseFont' does not contain a definition for 'Cambria'
please suggest me...thanks
public void abcd()
{
try
{
string UniqueNumber = Request.QueryString["UniqueNumber"];
string strFileName = UniqueNumber;
string strFileExtension = ".pdf";
string strContentType = FileManager.FileContentType_application_pdf;
string strExportData = string.Empty;
Document pdfDoc = new Document();
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
var output = new MemoryStream();
BaseFont bfTimes = BaseFont.CreateFont(BaseFont.Cambria, BaseFont.CP1252, false);
//Font ChronicleFont = new Font(bfTimes, 26f);
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
StringReader sr;
sr = new StringReader(Convert.ToString(ExportData.UserDetails(UniqueNumber)));
PdfWriter.GetInstance(pdfDoc, output);
pdfDoc.Open();
htmlparser.Parse(sr);
pdfDoc.Close();
strFileName = strFileName.Replace(" - ", "-").Replace(" ", "-").Replace("--", "-");
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", string.Format("attachment; filename={0}{1}", strFileName, strFileExtension));
Response.ContentType = strContentType;
Response.Charset = "";
Response.BinaryWrite(output.ToArray());
Response.Flush();
Response.End();
}
catch (Exception ex)
{
//
}
}

Categories