Horizontal alignment on row PdfPRow itextsharp (c#) - c#

Need some help here. I'm trying text within a row looks in the same horizontal line as it's corresponding dotted lines
This is the result
And this is the part of my code related to the image:
Font coverHeaderFont = new Font(Font.FontFamily.HELVETICA, 18, Font.BOLD, BaseColor.BLACK);
Font tableContentFont = new Font(Font.FontFamily.HELVETICA, 16, Font.BOLDITALIC, BaseColor.BLACK);
Font textIndexFont = new Font(Font.FontFamily.HELVETICA, 11, Font.BOLD, BaseColor.BLACK);
Font invisibleFont = new Font(Font.FontFamily.HELVETICA, 11, Font.BOLD, BaseColor.WHITE);
Font underText = new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD | Font.ITALIC, BaseColor.BLACK);
//table creation
PdfPTable tblCon = new PdfPTable(3); //3 columns
tblCon.WidthPercentage = 90f; //wide %
tblCon.HorizontalAlignment = 1; //centered
//tblCon.LockedWidth = true;
//relative col widths in proportions - 1/3 and 2/3
float[] widths = new float[] { 4f, 6f, 2f };//{ 6f, 4f, 2f };
tblCon.SetWidths(widths);
//leave a gap before and after the table
tblCon.SpacingBefore = 20f;
tblCon.SpacingAfter = 30f;
//Header Cell
string appHeader = "Applications";
Chunk cAppHeader = new Chunk(appHeader, underText);
// CELLS
PdfPCell cellName = new PdfPCell();
cellName.PaddingTop = 10f;
cellName.VerticalAlignment = PdfPCell.ALIGN_TOP;
cellName.BorderWidth = 1;
cellName.MinimumHeight = 30f;
//cellName.HorizontalAlignment = 0; //0=Left, 1=Center, 2=Right
PdfPCell cellSeparator = new PdfPCell();
cellSeparator.PaddingTop = 10f;
cellSeparator.VerticalAlignment = PdfPCell.ALIGN_TOP;
cellSeparator.BorderWidth = 1;
cellSeparator.MinimumHeight = 20f;
PdfPCell cellPage = new PdfPCell();
cellPage.PaddingTop = 10f;
cellPage.VerticalAlignment = PdfPCell.ALIGN_TOP;
cellPage.BorderWidth = 1;
cellPage.MinimumHeight = 30f;
for (int i = 0; i < listOfDetailsPDF.Count; i++)
{
if (i == 0) //first column, just header
{
cellName.AddElement(new Paragraph(cAppHeader));
cellSeparator.AddElement(new Paragraph(".", invisibleFont));
cellPage.AddElement(new Paragraph("1", invisibleFont));
}
var obj = listOfDetailsPDF[i];
String title = (string)obj.GetType().GetProperty("applicantName").GetValue(obj, null);
Chunk cTitle = new Chunk(title, textIndexFont);
int pNPage = (int)obj.GetType().GetProperty("pdfPages").GetValue(obj, null);
String numberPage = pNPage.ToString();
Chunk cNumPage = new Chunk(numberPage, textIndexFont);
cellName.AddElement(new Paragraph(cTitle));
cellSeparator.AddElement(new Paragraph(dottedLine));
cellPage.AddElement(new Paragraph(cNumPage));
}
tblCon.Rows.Add(new PdfPRow(new PdfPCell[] { cellName, cellSeparator, cellPage }));
I just want: the name with the dotted line with the number page look in the same line in every row.
Thank you

Related

Change the border color in individual cells in Spire.PDF grid C#

I am using Spire.PDF library to create a PDF in server side and return it to mobile side. Everything is working great. But I wanna access to each cell's border in the grid. I wanna change the color of the border.
https://www.e-iceblue.com/Tutorials/Spire.PDF/Spire.PDF-Program-Guide/Table/How-to-Change-the-Color-of-Grid-Border-in-PDF-in-C.html
Current code..
public HttpResponseMessage GET_MOTOR_RENWAL_PDF()
{
AgentDAL agntDAL = new AgentDAL();
//Create a pdf document.
PdfDocument doc = new PdfDocument();
PdfSection sec = doc.Sections.Add();
sec.PageSettings.Width = PdfPageSize.A4.Width;
sec.PageSettings.Height = PdfPageSize.A4.Height;
sec.PageSettings.Margins = new PdfMargins(20f, 5f, 20f, 5f);
PdfPageBase page = sec.Pages.Add();
//title
PdfBrush brush1 = PdfBrushes.Black;
PdfTrueTypeFont font1 = new PdfTrueTypeFont(new Font("Times New Roman", 11f, FontStyle.Bold));
PdfStringFormat format1 = new PdfStringFormat(PdfTextAlignment.Center);
page.Canvas.DrawString("Monthly", font1, brush1, page.Canvas.ClientSize.Width / 2, 60, format1);
page.Canvas.DrawString("Report generated", font1, brush1, page.Canvas.ClientSize.Width / 2, 76, format1);
//grid
PdfGrid grid = new PdfGrid();
grid.Columns.Add(5);
float gridWidth = page.Canvas.ClientSize.Width - (grid.Columns.Count + 1);
for (int j = 0; j < grid.Columns.Count; j++)
{
grid.Columns[j].Width = gridWidth * 0.20f;
}
PdfGridRow row0 = grid.Rows.Add();
PdfGridRow row1 = grid.Rows.Add();
PdfGridRow row2 = grid.Rows.Add();
PdfGridRow row3 = grid.Rows.Add();
row0.Style.Font = new PdfTrueTypeFont(new Font("Times New Roman", 11f, FontStyle.Regular), true);
row1.Style.Font = new PdfTrueTypeFont(new Font("Times New Roman", 11f, FontStyle.Regular), true);
row2.Style.Font = new PdfTrueTypeFont(new Font("Times New Roman", 11f, FontStyle.Regular), true);
row3.Style.Font = new PdfTrueTypeFont(new Font("Times New Roman", 11f, FontStyle.Regular), true);
row0.Cells[2].ColumnSpan = 3;
row1.Cells[2].ColumnSpan = 3;
row2.Cells[2].ColumnSpan = 3;
row3.Cells[2].ColumnSpan = 3;
row0.Cells[2].RowSpan = 4;
row0.Cells[0].Value = "Policy";
row0.Cells[1].Value = "VM5115001510000009";
row1.Cells[0].Value = "Vehicle";
row1.Cells[1].Value = "BBP";
row2.Cells[0].Value = "Premium";
row2.Cells[1].Value = "7,366.10";
row3.Cells[0].Value = "Date";
row3.Cells[1].Value = "03-Jan-2020";
float gridHeight = 20.0f;
for (int i = 0; i < grid.Rows.Count; i++)
{
grid.Rows[i].Height = gridHeight;
}
grid.Draw(page, new PointF(0, 120));
MemoryStream stream = new MemoryStream();
doc.SaveToStream(stream);
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
result.Content = new ByteArrayContent(stream.ToArray());
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
doc.Close();
return result;
}
What I get from this...
What I want...
I tried to do this, but it didn't work.
row0.Cells[0].Style.Borders.Right.Color = Color.DarkRed;
row1.Cells[0].Style.Borders.Right.Color = Color.DarkRed;
row2.Cells[0].Style.Borders.Right.Color = Color.DarkRed;
row3.Cells[0].Style.Borders.Right.Color = Color.DarkRed;
Try the below code:
float gridHeight = 20.0f;
for (int i = 0; i < grid.Rows.Count; i++)
{
grid.Rows[i].Height = gridHeight;
grid.Rows[i].Cells[0].Style.Borders.Right = new PdfPen(PdfBrushes.DarkRed);
grid.Rows[i].Cells[1].Style.Borders.Left = new PdfPen(PdfBrushes.DarkRed);
}

How to create PDF Template using iTextSharp

My task is to create a PDF template which contains multiple pages and multiple tables. Below is code I wrote to create a table. I don't know how to create a template of that table.
When I change the value of pageSize.GetLeft(40), pageSize.GetBottom(200), there is no effect in the template.
Rectangle pageSize = document.PageSize;
Department = "Town Development Department";
WebSite = "www.cmdachennai.gov.in";
VersionNumber = "1.0.77";
Phrase cc = new Phrase("This is report", H2);
Paragraph hp = new Paragraph();
hp.Add(cc);
Phrase c1 = new Phrase("Check List Report", H5);
Phrase c2 = new Phrase("Report Generated On : ", H3);
Phrase c3 = new Phrase(DateTime.Now.ToString("dd-MM-yyyy"), H3);
Phrase c5 = new Phrase("Version Number : ", H3);
Phrase c6 = new Phrase(VersionNumber, H3);
//Phrase c7 = new Phrase("Version Number : ", H3);
Paragraph hp4 = new Paragraph();
hp4.Add(c5);
hp4.Add(c6);
Paragraph hp1 = new Paragraph();
hp1.Add(c2);
hp1.Add(c3);
hp.Alignment = 1;
PdfPTable tblTopHeading = new PdfPTable(1);
tblTopHeading.WidthPercentage = 100;
PdfPCell Topcell = new PdfPCell();
Topcell.AddElement(hp);
Topcell.HorizontalAlignment = 1;
Topcell.BorderWidthBottom = 0f;
Topcell.BorderWidthLeft = 0f;
Topcell.BorderWidthRight = 0f;
Topcell.BorderWidthTop = 0f;
tblTopHeading.AddCell(Topcell);
document.Add(tblTopHeading);
Paragraph hp2 = new Paragraph(Department, H4);
Paragraph hp3 = new Paragraph(WebSite, H4);
Phrase c = new Phrase("\n", H4);
PdfPTable tblHeading = new PdfPTable(new float[] { 100f, 60f });
tblHeading.WidthPercentage = 100;
PdfPCell cell_1 = new PdfPCell();
PdfPCell cell_2 = new PdfPCell();
Paragraph hp5 = new Paragraph();
hp5.Add(c1);
//hp5.Add(c2);
cell_1.AddElement(hp5);
hp1.Alignment = 2;
hp2.Alignment = 2;
hp3.Alignment = 2;
hp4.Alignment = 2;
cell_2.AddElement(hp1);
cell_2.AddElement(hp4);
cell_1.BorderWidthBottom = 0f;
cell_1.BorderWidthLeft = 0f;
cell_1.BorderWidthRight = 0f;
cell_1.BorderWidthTop = 0f;
cell_2.BorderWidthBottom = 0f;
cell_2.BorderWidthLeft = 0f;
cell_2.BorderWidthRight = 0f;
cell_2.BorderWidthTop = 0f;
tblHeading.AddCell(cell_1);
tblHeading.AddCell(cell_2);
document.Add(tblHeading);
cb.AddTemplate(template, pageSize.GetLeft(40), pageSize.GetBottom(200));
As it turned out in comments, the template you add to cb (whatever cb may be) here
cb.AddTemplate(template, pageSize.GetLeft(40), pageSize.GetBottom(200));
is empty:
variable declare PdfTemplate template; and in OnOpenDocument method template = cb.CreateTemplate(300, 800); is create template
You merely create it and then add it. Thus, it is not surprising that adding that template at different positions makes no difference because an empty template effectively is invisible.
Now you ask
can you explain how to put table in pdftemplate because right now i just create template
A PdfTemplate is derived from PdfContentByte, and to add structured content (Paragraph, PdfPTable, ...) to a PdfContentByte you use the ColumnText class, e.g. like this:
using (FileStream output = new FileStream(#"TemplateWithTable.pdf", FileMode.Create, FileAccess.Write))
using (Document document = new Document(PageSize.A4))
{
PdfWriter writer = PdfWriter.GetInstance(document, output);
document.Open();
PdfPTable table = new PdfPTable(2);
table.AddCell("Test");
table.AddCell("Table");
PdfContentByte canvas = writer.DirectContent;
PdfTemplate template = canvas.CreateTemplate(300, 800);
Rectangle pageSize = document.PageSize;
canvas.AddTemplate(template, pageSize.GetLeft(40), pageSize.GetBottom(200));
ColumnText ct = new ColumnText(template);
ct.SetSimpleColumn(new Rectangle(100, 100, 300, 600));
ct.AddElement(table);
ct.Go();
document.Close();
}

how to add background color to last line of GridView

I am using iText to export GridView to pdf.
I was able to add header color to my pdf.
I would like to add background color to the last (total) line/row of pdf in the Gridview?
I am using iText library to export GridView to Pdf.
Here is my pdf function :
public void ExpToPdf_Click(object sender, EventArgs e)
{
getHTMLGridView();
}
private void getHTMLGridView()
{
BaseFont bfTimes = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, false);
iTextSharp.text.Font times16 = new iTextSharp.text.Font(bfTimes, 16, iTextSharp.text.Font.NORMAL, iTextSharp.text.Color.BLACK);
Paragraph p1 = new Paragraph("Texas Tech University", times16);
p1.Alignment = 1;
iTextSharp.text.Font times14 = new iTextSharp.text.Font(bfTimes, 14, iTextSharp.text.Font.NORMAL, iTextSharp.text.Color.BLACK);
Paragraph p2 = new Paragraph("Department of Institutional Research", times14);
Paragraph p3 = new Paragraph(caption.Text.ToUpper(), times14);
p2.Alignment = 1;
p3.Alignment = 1;
//iTextSharp.text.Font times10 = new iTextSharp.text.Font(bfTimes, 10, iTextSharp.text.Font.NORMAL, iTextSharp.text.Color.BLACK);
//Paragraph p4 = new Paragraph("(Uncertified Data)", times10);
//p4.Alignment = 1;
Paragraph p5 = new Paragraph(" ");
iTextSharp.text.Font times8 = new iTextSharp.text.Font(bfTimes, 8, iTextSharp.text.Font.NORMAL, iTextSharp.text.Color.BLACK);
iTextSharp.text.Font times11 = new iTextSharp.text.Font(bfTimes, 10, iTextSharp.text.Font.NORMAL, iTextSharp.text.Color.WHITE);
iTextSharp.text.Color BackgroundColor = new iTextSharp.text.Color(System.Drawing.ColorTranslator.FromHtml("#CC0000"));
PdfPTable HeaderTable = new PdfPTable(4);
//actual width of table in points
HeaderTable.TotalWidth = 600f;
//fix the absolute width of the table
HeaderTable.LockedWidth = true;
//relative col widths in proportions - 1/3 and 2/3
float[] Headerwidths = new float[] { 1f, 1f, 1f, 1f};
HeaderTable.SetWidths(Headerwidths);
HeaderTable.HorizontalAlignment = 1;
//leave a gap before and after the table
//HeaderTable.SpacingBefore = 30f;
//HeaderTable.SpacingAfter = 30f;
foreach (TableCell cell in MyGridView.HeaderRow.Cells)
{
PdfPCell pdfCell = new PdfPCell(new Phrase(cell.Text, times11));
// Set the PDF cell backgroundcolor to GridView header row BackgroundColor color
pdfCell.BackgroundColor = BackgroundColor;
pdfCell.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right
// Add the cell to PDF table
HeaderTable.AddCell(pdfCell);
}
PdfPTable table = new PdfPTable(4);
//actual width of table in points
table.TotalWidth = 600f;
//fix the absolute width of the table
table.LockedWidth = true;
//relative col widths in proportions
float[] widths = new float[] { 1f, 1f, 1f, 1f};
table.SetWidths(widths);
table.HorizontalAlignment = 1;
//leave a gap before and after the table
//table.SpacingBefore = 30f;
//table.SpacingAfter = 30f;
string connect = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["ConnStringExtracts_IRDW"].ConnectionString;
DataSet ds = new DataSet();
using (SqlConnection conn = new SqlConnection(connect))
{
string query = "dbo.sp_FB_APPADM_IRDW";
SqlCommand cmd = new SqlCommand(query, conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#reportType", reportType);
cmd.Parameters.AddWithValue("#term_Code", ENRDropDownList.SelectedValue);
try
{
int i;
conn.Open();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
// Fill the DataSet.
adapter.Fill(ds);
foreach (DataRow row in ds.Tables[0].Rows)
{
for (i = 0; i < 2; i++)
{
PdfPCell pdfCell4 = new PdfPCell(new Phrase(row[i].ToString(), times8));
pdfCell4.HorizontalAlignment = 0; //0=Left, 1=Centre, 2=Right
// Add the cell to PDF table
table.AddCell(pdfCell4);
}
for (i = 2; i < ds.Tables[0].Columns.Count; i++)
{
PdfPCell pdfCell4 = new PdfPCell(new Phrase(row[i].ToString(), times8));
pdfCell4.HorizontalAlignment = 2; //0=Left, 1=Centre, 2=Right
// Add the cell to PDF table
table.AddCell(pdfCell4);
}
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
//Create the PDF Document
Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
pdfDoc.SetPageSize(iTextSharp.text.PageSize.A4.Rotate());
PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
//open the stream
pdfDoc.Open();
//add the table to the document
pdfDoc.Add(p1);
pdfDoc.Add(p2);
pdfDoc.Add(p3);
pdfDoc.Add(p5);
pdfDoc.Add(HeaderTable);
pdfDoc.Add(table);
//close the document stream
pdfDoc.Close();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;" + "filename=Enrollment_Major_Classification.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Write(pdfDoc);
Response.End();
}
}
I tried using: GridView1.Rows[GridView1.Rows.Count - 1] to get the last row of gridview. But, I did not seem to make my way around it, to add color to last row.
Any help much appreciated.
You can simply do this:
GridView1.Rows[GridView1.Rows.Count - 1].BackColor = Color.Green;
Or if the row is a FooterRow:
GridView1.FooterRow.BackColor = Color.Red;

Generate a PDF file from two gridviews using iTextSharp

I use to generate a PDF file from a gridview using iTextSharp.
I need a help because I am not familiar with iTextSharp.
I'm using two gridviews in my aspx page: gvProducts and gvUsers.
The generation a PDF file from a single (gvProducts) gridview using iTextSharp working correctly.
I can't print the first and second GridView in the same PDF.
This is what I want:
Open PDF document;
Print result of my first GridView;
Print result of my second GridView;
Close, Save and download PDF document in the client.
Anybody know how can I do that?
Thank you in advance.
My code below.
protected void ExportToPDFWithFormatting()
{
//link button column is excluded from the list
int colCount = gvProducts.Columns.Count - 1;
//Create a table
PdfPTable table = new PdfPTable(colCount);
table.HorizontalAlignment = 1;
table.WidthPercentage = 100;
//create an array to store column widths
int[] colWidths = new int[gvProducts.Columns.Count];
PdfPCell cell;
string cellText;
//create the header row
for (int colIndex = 0; colIndex < colCount; colIndex++)
{
table.SetWidths(new int[] { 0, 40, 120, 110, 60, 60, 100, 90, 100, 50, 50, 50, 40, 30, 260, 200, 0 });
//fetch the header text
cellText = Server.HtmlDecode(gvProducts.HeaderRow.Cells[colIndex].Text);
//create a new cell with header text
BaseFont bf = BaseFont.CreateFont(
BaseFont.HELVETICA,
BaseFont.CP1252,
BaseFont.EMBEDDED,
false);
iTextSharp.text.Font font = new iTextSharp.text.Font(bf, 10, iTextSharp.text.Font.BOLD, BaseColor.WHITE);
cell = new PdfPCell(new Phrase(cellText.Replace("<br />", Environment.NewLine), font));
cell.HorizontalAlignment = Element.ALIGN_CENTER;
cell.VerticalAlignment = Element.ALIGN_MIDDLE;
cell.FixedHeight = 45f;
//set the background color for the header cell
cell.BackgroundColor = new BaseColor(System.Drawing.ColorTranslator.FromHtml("#a52a2a"));
//add the cell to the table. we dont need to create a row and add cells to the row
//since we set the column count of the table to 4, it will automatically create row for
//every 4 cells
table.AddCell(cell);
}
//export rows from GridView to table
for (int rowIndex = 0; rowIndex < gvProducts.Rows.Count; rowIndex++)
{
if (gvProducts.Rows[rowIndex].RowType == DataControlRowType.DataRow)
{
for (int j = 0; j < gvProducts.Columns.Count - 1; j++)
{
//fetch the column value of the current row
cellText = Server.HtmlDecode(gvProducts.Rows[rowIndex].Cells[j].Text);
//create a new cell with column value
cell = new PdfPCell(new Phrase(cellText, FontFactory.GetFont("PrepareForExport", 8)));
cell.HorizontalAlignment = Element.ALIGN_CENTER;
cell.VerticalAlignment = Element.ALIGN_MIDDLE;
cell.FixedHeight = 25f;
//Set Color of Alternating row
if (rowIndex % 2 != 0)
{
cell.BackgroundColor = new BaseColor(System.Drawing.ColorTranslator.FromHtml("#f5f5dc"));
}
else
{
cell.BackgroundColor = new BaseColor(System.Drawing.ColorTranslator.FromHtml("#fcfcfc"));
}
//add the cell to the table
table.AddCell(cell);
}
}
}
//Create the PDF Document
Document pdfDoc = new Document(PageSize.A3.Rotate(), 30f, 30f, 30f, 0f);
PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
//open the stream
pdfDoc.Open();
table.HeaderRows = 1;
iTextSharp.text.Font fdefault = FontFactory.GetFont("Verdana", 18, iTextSharp.text.Font.BOLD, BaseColor.BLUE);
string s = "Report";
pdfDoc.Add(new Paragraph(s, fdefault));
//add the table to the document
pdfDoc.Add(table);
//close the document stream
pdfDoc.Close();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;" + DateTime.Now + ".pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Write(pdfDoc);
Response.End();
}
Edit #1
This is my code for generate pdf on GridView number two (gvUsers).
The code working but in the headers columns I have the names of GridView number one (gvProducts)... why?
//start pdf gridview number two
int colCountUsers = gvUsers.Columns.Count - 1;
PdfPTable tableUsers = new PdfPTable(colCountUsers);
tableUsers.HorizontalAlignment = 1;
tableUsers.WidthPercentage = 100;
int[] colWidthsUsers = new int[gvUsers.Columns.Count];
PdfPCell cellUsers;
string cellTextUsers;
for (int colIndexUsers = 0; colIndexUsers < colCountUsers; colIndexUsers++)
{
tableUsers.SetWidths(new int[] { 0, 40, 120, 110, 60, 60, 100 });
cellTextUsers = Server.HtmlDecode(gvProducts.HeaderRow.Cells[colIndexUsers].Text);
BaseFont bfUsers = BaseFont.CreateFont(
BaseFont.HELVETICA,
BaseFont.CP1252,
BaseFont.EMBEDDED,
false);
iTextSharp.text.Font fontUsers = new iTextSharp.text.Font(bfUsers, 10, iTextSharp.text.Font.BOLD, BaseColor.WHITE);
cellUsers = new PdfPCell(new Phrase(cellTextUsers.Replace("<br />", Environment.NewLine), fontUsers));
cellUsers.HorizontalAlignment = Element.ALIGN_CENTER;
cellUsers.VerticalAlignment = Element.ALIGN_MIDDLE;
cellUsers.FixedHeight = 45f;
cellUsers.BackgroundColor = new BaseColor(System.Drawing.ColorTranslator.FromHtml("#a52a2a"));
tableUsers.AddCell(cellUsers);
}
for (int rowIndexUsers = 0; rowIndexUsers < gvUsers.Rows.Count; rowIndexUsers++)
{
if (gvUsers.Rows[rowIndexUsers].RowType == DataControlRowType.DataRow)
{
for (int j = 0; j < gvUsers.Columns.Count - 1; j++)
{
cellTextUsers = Server.HtmlDecode(gvUsers.Rows[rowIndexUsers].Cells[j].Text);
cellUsers = new PdfPCell(new Phrase(cellTextUsers, FontFactory.GetFont("PrepareForExport", 8)));
cellUsers.HorizontalAlignment = Element.ALIGN_CENTER;
cellUsers.VerticalAlignment = Element.ALIGN_MIDDLE;
cellUsers.FixedHeight = 25f;
tableUsers.AddCell(cellUsers);
}
}
}
Document pdfDocUsers = new Document(PageSize.A3.Rotate(), 30f, 30f, 30f, 0f);
PdfWriter.GetInstance(pdfDocUsers, Response.OutputStream);
pdfDocUsers.Open();
tableUsers.HeaderRows = 1;
iTextSharp.text.Font fdefaultUsers = FontFactory.GetFont("Verdana", 18, iTextSharp.text.Font.BOLD, BaseColor.BLUE);
string sUsers = "Users";
pdfDocUsers.Add(new Paragraph(sUsers, fdefaultUsers));
pdfDocUsers.Add(tableUsers);
pdfDocUsers.Close();
//end pdf gridview number two
//in first pdf gridview
//add the table to the document
pdfDoc.Add(table);
pdfDoc.Add(tableUsers);
int colCount1 = gvProducts1.Columns.Count - 1;
//Create a table
PdfPTable table1 = new PdfPTable(colCount1);
table1.HorizontalAlignment = 1;
table1.WidthPercentage = 100;
//create an array to store column widths
int[] colWidths1 = new int[gvProducts1.Columns.Count];
PdfPCell cell1;
string cellText1;
//create the header row
for (int colIndex1 = 0; colIndex1 < colCount1; colIndex1++)
{
table1.SetWidths(new int[] { 0, 40, 120, 110, 60, 60, 100, 90, 100, 50, 50, 50, 40, 30, 260, 200, 0 });
//fetch the header text
cellText1 = Server.HtmlDecode(gvProducts1.HeaderRow.Cells[colIndex1].Text);
//create a new cell with header text
BaseFont bf1 = BaseFont.CreateFont(
BaseFont.HELVETICA,
BaseFont.CP1252,
BaseFont.EMBEDDED,
false);
iTextSharp.text.Font font1 = new iTextSharp.text.Font(bf, 10, iTextSharp.text.Font.BOLD, BaseColor.WHITE);
cell1 = new PdfPCell(new Phrase(cellText.Replace("<br />", Environment.NewLine), font));
cell1.HorizontalAlignment = Element.ALIGN_CENTER;
cell1.VerticalAlignment = Element.ALIGN_MIDDLE;
cell1.FixedHeight = 45f;
//set the background color for the header cell
cell1.BackgroundColor = new BaseColor(System.Drawing.ColorTranslator.FromHtml("#a52a2a"));
//add the cell to the table. we dont need to create a row and add cells to the row
//since we set the column count of the table to 4, it will automatically create row for
//every 4 cells
table1.AddCell(cell1);
}
//export rows from GridView to table
for (int rowIndex1 = 0; rowIndex1 < gvProducts1.Rows.Count; rowIndex1++)
{
if (gvProducts.Rows[rowIndex1].RowType == DataControlRowType.DataRow)
{
for (int j1 = 0; j1 < gvProducts1.Columns.Count - 1; j1++)
{
//fetch the column value of the current row
cellText1 = Server.HtmlDecode(gvProducts1.Rows[rowIndex1].Cells[j].Text);
//create a new cell with column value
cell1 = new PdfPCell(new Phrase(cellText1, FontFactory.GetFont("PrepareForExport", 8)));
cell1.HorizontalAlignment = Element.ALIGN_CENTER;
cell1.VerticalAlignment = Element.ALIGN_MIDDLE;
cell1.FixedHeight = 25f;
//Set Color of Alternating row
if (rowIndex1 % 2 != 0)
{
cell1.BackgroundColor = new BaseColor(System.Drawing.ColorTranslator.FromHtml("#f5f5dc"));
}
else
{
cell1.BackgroundColor = new BaseColor(System.Drawing.ColorTranslator.FromHtml("#fcfcfc"));
}
//add the cell to the table
table1.AddCell(cell1);
}
}
}
//Create the PDF Document
//open the stream
//add the table to the document
pdfDoc.Add(table1);
//close the document stream
pdfDoc.Close();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;" + DateTime.Now + ".pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Write(pdfDoc);
Response.End();

Code isn't drawing a horizontal line in my PDF

I'm trying to add a horizontal line on top to divide the header text from the actual values in my pdf file:
Here's my code:
public class StudentList
{
public void PrintStudentList(int gradeParaleloID)
{
StudentRepository repo = new StudentRepository();
var students = repo.FindAllStudents()
.Where(s => s.IDGradeParalelo == gradeParaleloID);
try
{
Document document = new Document(PageSize.LETTER);
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + "\\Alumnos.pdf", FileMode.Create));
document.Open();
PdfContentByte cb = writer.DirectContent;
cb.SetLineWidth(2.0f); // Make a bit thicker than 1.0 default
cb.SetGrayStroke(0.95f); // 1 = black, 0 = white
cb.MoveTo(20, 30);
cb.LineTo(400, 30);
cb.Stroke();
PdfPTable table = new PdfPTable(3);
float[] widths = new float[] { 0.6f, 0.75f, 2f };
table.SetWidths(widths);
PdfPCell numeroCell = new PdfPCell(new Phrase("Nro."));
numeroCell.Border = 0;
numeroCell.HorizontalAlignment = 0;
table.AddCell(numeroCell);
PdfPCell codigoCell = new PdfPCell(new Phrase("RUDE"));
codigoCell.Border = 0;
codigoCell.HorizontalAlignment = 0;
table.AddCell(codigoCell);
PdfPCell nombreCell = new PdfPCell(new Phrase("Apellidos y Nombres"));
nombreCell.Border = 0;
nombreCell.HorizontalAlignment = 0;
table.AddCell(nombreCell);
int c = 1;
foreach (var student in students)
{
PdfPCell cell = new PdfPCell(new Phrase(c.ToString()));
cell.Border = 0;
cell.HorizontalAlignment = 0;
table.AddCell(cell);
cell = new PdfPCell(new Phrase(student.Rude.ToString()));
cell.Border = 0;
cell.HorizontalAlignment = 0;
table.AddCell(cell);
cell = new PdfPCell(new Phrase(student.LastNameFather + " " + student.LastNameMother + " " + student.Name));
cell.Border = 0;
cell.HorizontalAlignment = 0;
table.AddCell(cell);
c++;
}
table.SpacingBefore = 20f;
table.SpacingAfter = 30f;
document.Add(table);
document.Close();
}
catch (DocumentException de)
{
Debug.WriteLine(de.Message);
}
catch (IOException ioe)
{
Debug.WriteLine(ioe.Message);
}
}
}
I don't understand why the cb.Stroke() isn't working. Any suggestions?
Drawing with iTextSharp's PdfContentByte class can be a little confusing. The height is actually relative to the bottom, not the top. So the top of the page is not 0f, but instead is actually document.Top, which on your page size of PageSize.LETTER is 726f. So if you want to draw your line 30 units from the top, try:
cb.MoveTo(20, document.Top - 30f);
cb.LineTo(400, document.Top - 30f);
Just curious -- why do it the hard way instead of using table borders? (I noticed you set your borders to 0) Trying to space out lines by hand is the biggest pain. If you ever move content in your PDF around, you'll have to make sure your measurements still work.
Try this:
numeroCell.Border = 0;
numeroCell.BorderColorBottom = new BaseColor(System.Drawing.Color.Black);
numeroCell.BorderWidthBottom = 1f;
codigoCell.Border = 0;
codigoCell.BorderColorBottom = new BaseColor(System.Drawing.Color.Black);
codigoCell.BorderWidthBottom = 1f;
nombreCell.Border = 0;
nombreCell.BorderColorBottom = new BaseColor(System.Drawing.Color.Black);
nombreCell.BorderWidthBottom = 1f;
That should give you a nice solid black line under your header row, no measurements needed:

Categories