Manipulating width and height of rows and cells in iTextSharp - c#

I have used the following code to fill my PdfPTable:
public PdfPTable GetTable(List<hsp_Narudzbe_IzdavanjeFakture4_Result> proizvodi)
{
PdfPTable table = new PdfPTable(5);
table.WidthPercentage = 100F;
table.DefaultCell.UseAscender = true;
table.DefaultCell.UseDescender = true;
Font f = new Font(Font.FontFamily.HELVETICA, 13);
f.Color = BaseColor.WHITE;
PdfPCell cell = new PdfPCell(new Phrase("Stavke narudžbe: ", f));
cell.BackgroundColor = BaseColor.BLACK;
cell.HorizontalAlignment = Element.ALIGN_CENTER;
cell.Colspan = 5;
table.AddCell(cell);
for (int i = 0; i < 2; i++)
{
table.AddCell("Redni broj");
table.AddCell("Proizvod");
table.AddCell("Cijena");
table.AddCell("Šifra proizvoda");
table.AddCell("Kolicina");
}
table.DefaultCell.BackgroundColor = BaseColor.LIGHT_GRAY;
table.HeaderRows = 3;
table.FooterRows = 1;
int broj = 0;
table.DeleteLastRow();
foreach (hsp_Narudzbe_IzdavanjeFakture4_Result p in proizvodi)
{
broj++;
table.AddCell(broj.ToString());
table.AddCell(p.Naziv);
table.AddCell(p.Cijena);
table.AddCell(p.Sifra);
table.AddCell(p.Kolicina.ToString());
}
float[] widths = { 15.00F, 15.00F,15.00F,15.00F};
table.GetRow(1).SetWidths(widths);
return table;
}
Little explanation of code:
broj++; represents the row number which gets incremented each time a new row is added. That way I get the number for each row.
Now my question is: how can I manipulate width of the first column (which represents the row number). I have tried the following code:
float[] widths = { 15.00F, 15.00F,15.00F,15.00F};
table.GetRow(1).SetWidths(widths);
Can someone help me out with this ?

Combining your original post and your comment, I see two questions:
You want to create a table where the first column isn't as wide as the other columns.
You want the content in those columns to be center-aligned.
I have written a small sample named ColumnWidthExample that should result in such a PDF:
This is the Java code that produces this PDF:
public void createPdf(String dest) throws IOException, DocumentException {
Document document = new Document(PageSize.A4.rotate());
PdfWriter.getInstance(document, new FileOutputStream(dest));
document.open();
float[] columnWidths = {1, 5, 5};
PdfPTable table = new PdfPTable(columnWidths);
table.setWidthPercentage(100);
table.getDefaultCell().setUseAscender(true);
table.getDefaultCell().setUseDescender(true);
Font f = new Font(FontFamily.HELVETICA, 13, Font.NORMAL, GrayColor.GRAYWHITE);
PdfPCell cell = new PdfPCell(new Phrase("This is a header", f));
cell.setBackgroundColor(GrayColor.GRAYBLACK);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setColspan(3);
table.addCell(cell);
table.getDefaultCell().setBackgroundColor(new GrayColor(0.75f));
for (int i = 0; i < 2; i++) {
table.addCell("#");
table.addCell("Key");
table.addCell("Value");
}
table.setHeaderRows(3);
table.setFooterRows(1);
table.getDefaultCell().setBackgroundColor(GrayColor.GRAYWHITE);
table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
for (int counter = 1; counter < 101; counter++) {
table.addCell(String.valueOf(counter));
table.addCell("key " + counter);
table.addCell("value " + counter);
}
document.add(table);
document.close();
}
It should be fairly simple to adapt this code to C#.
The first problem is solved by defining the column widths at the level of the table. For instance like this (there are other ways to get the same result):
float[] columnWidths = {1, 5, 5};
PdfPTable table = new PdfPTable(columnWidths);
The values 1, 5, and 5 aren't absolute widths. As we define the width of the table as 100% of the available width within the margins of the page, iText will divide the available width by 11 (1 + 5 + 5) and the first column will measure 1 time this value, whereas column two and three will measure 5 times this value.
Your second problem can be solved by changing the horizontal alignment. If you work with an explicit PdfPCell object, you need to change the value at the cell level, as is done in the following line:
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
If you leave it to iText to create the PdfPCell object, you need to change the alignment at the level of the default cell:
table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
Note that the default cell properties are not applied when you add a PdfPCell object to the table. In that case, the properties of that PdfPCell are used.

Okay so I managed to center the cell's text in every column, now I just can't figure out how to make first row to have smallest width...
Here is the code
public PdfPTable GetTable(List<hsp_Narudzbe_IzdavanjeFakture4_Result> proizvodi)
{
PdfPTable table = new PdfPTable(5);
table.WidthPercentage = 100F;
table.DefaultCell.UseAscender = true;
table.DefaultCell.UseDescender = true;
Font f = new Font(Font.FontFamily.HELVETICA, 13);
f.Color = BaseColor.WHITE;
PdfPCell cell = new PdfPCell(new Phrase("Stavke narudžbe: ", f));
cell.BackgroundColor = BaseColor.BLACK;
cell.HorizontalAlignment = Element.ALIGN_CENTER;
cell.Colspan = 5;
table.AddCell(cell);
for (int i = 0; i < 2; i++)
{
table.AddCell(new PdfPCell(new Phrase("Redni broj"))
{
VerticalAlignment = Element.ALIGN_MIDDLE,
HorizontalAlignment = Element.ALIGN_CENTER,
BackgroundColor = BaseColor.LIGHT_GRAY
});
table.AddCell(new PdfPCell(new Phrase("Proizvod"))
{
VerticalAlignment = Element.ALIGN_MIDDLE,
HorizontalAlignment = Element.ALIGN_CENTER,
BackgroundColor = BaseColor.LIGHT_GRAY
});
table.AddCell(new PdfPCell(new Phrase("Cijena"))
{
VerticalAlignment = Element.ALIGN_MIDDLE,
HorizontalAlignment = Element.ALIGN_CENTER,
BackgroundColor = BaseColor.LIGHT_GRAY
});
table.AddCell(new PdfPCell(new Phrase("Šifra"))
{
VerticalAlignment = Element.ALIGN_MIDDLE,
HorizontalAlignment = Element.ALIGN_CENTER,
BackgroundColor = BaseColor.LIGHT_GRAY
});
table.AddCell(new PdfPCell(new Phrase("Kolicina"))
{
VerticalAlignment = Element.ALIGN_MIDDLE,
HorizontalAlignment = Element.ALIGN_CENTER,
BackgroundColor = BaseColor.LIGHT_GRAY
});
}
table.DefaultCell.BackgroundColor = BaseColor.LIGHT_GRAY;
table.HeaderRows = 3;
table.FooterRows = 1;
int broj = 0;
table.DeleteLastRow();
foreach (hsp_Narudzbe_IzdavanjeFakture4_Result p in proizvodi)
{
broj++;
table.AddCell(new PdfPCell(new Phrase(broj.ToString()))
{
VerticalAlignment = Element.ALIGN_MIDDLE,
HorizontalAlignment = Element.ALIGN_CENTER
});
table.AddCell(new PdfPCell(new Phrase(p.Naziv))
{
VerticalAlignment = Element.ALIGN_MIDDLE,
HorizontalAlignment = Element.ALIGN_CENTER
});
table.AddCell(new PdfPCell(new Phrase(p.Cijena))
{
VerticalAlignment = Element.ALIGN_MIDDLE,
HorizontalAlignment = Element.ALIGN_CENTER
});
table.AddCell(new PdfPCell(new Phrase(p.Sifra))
{
VerticalAlignment = Element.ALIGN_MIDDLE,
HorizontalAlignment = Element.ALIGN_CENTER
});
table.AddCell(new PdfPCell(new Phrase(p.Kolicina.ToString()))
{
VerticalAlignment = Element.ALIGN_MIDDLE,
HorizontalAlignment = Element.ALIGN_CENTER
});
}
return table;
}
Can someone help me figure out how to set the width of each row to a custom size?
Thanks !

Related

how to add footer (with variables/class) with itextsharp pdf

I have this code and I want to add a table as a footer. But the problem is I cannot pass the variables:
Document doc = new Document();
doc.AddTitle("e-8D Report_" + report.OSIE8DNO + ".pdf");
PdfWriter writer = PdfWriter.GetInstance(doc, fs);
doc.SetPageSize(PageSize.A4);
doc.SetMargins(18f, 18f, 18f, 18f); // 0.25 inch margins
doc.Open();
PdfPTable table = new PdfPTable(10)
{
WidthPercentage = 100,
LockedWidth = true,
TotalWidth = 560f
};
float[] widths = new float[] { 32f, 73f, 70f, 70f, 70f, 70f, 70f, 70f, 73f, 32f };
table.SetWidths(widths);
// rest of the document
// ...
// rest of the document
// Below is the part that I want to add as footer
#region Footer
// left margin
cell = new PdfPCell(new Phrase(" ", font6))
{
Border = Rectangle.NO_BORDER
};
table.AddCell(cell);
cell = new PdfPCell(new Phrase("Reviewed & Approved by :", font6))
{
Colspan = 4,
BackgroundColor = bgBlue,
HorizontalAlignment = Element.ALIGN_LEFT,
Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER
};
table.AddCell(cell);
cell = new PdfPCell(new Phrase("For document approval by email, no Manual / e-Signature required &", font2))
{
Colspan = 4,
BackgroundColor = bgBlue,
HorizontalAlignment = Element.ALIGN_LEFT,
Border = Rectangle.TOP_BORDER | Rectangle.RIGHT_BORDER
};
table.AddCell(cell);
// right margin
cell = new PdfPCell(new Phrase(" ", font6))
{
Border = Rectangle.NO_BORDER
};
table.AddCell(cell);
// the rest of the cell
//...
// the rest of the cell
#endregion
doc.Add(table);
//writer.PageEvent = new PDFFooter();
doc.Close();
With this variables, I can't make the footer with PdfPageEventHelper from this source:
Footer in pdf with iTextSharp
Please help
Already got the answer. I add parameter to the PdfPageEventHelper Class:
public PdfPTable footer { get; set; }
public override void OnEndPage(PdfWriter writer, Document document)
{
base.OnEndPage(writer, document);
document.Add(footer);
}
And call from the page (create complete table first on the page):
writer.PageEvent = new PDFHeaderFooter() { footer = table };

Horizontal alignment on row PdfPRow itextsharp (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

iTextSharp NET Remove spacing between cells

I'm trying to add three cells in one row, which have colored background with the same color. The problem is that I see space (or vertical border) between these cells, but I don't need this space.
As you can see on the image, there is some space. Maybe this is the wrong way to do what I need. I need this green text in the center of page and white text on the right side at the same row and with the same background color.
This is my code:
PdfPCell emptyCell = new PdfPCell();
emptyCell.BackgroundColor = BaseColor.DARK_GRAY;
emptyCell.HorizontalAlignment = Element.ALIGN_JUSTIFIED;
emptyCell.VerticalAlignment = Element.ALIGN_CENTER;
emptyCell.MinimumHeight = 30f;
emptyCell.Colspan = 3;
emptyCell.Border = Rectangle.NO_BORDER;
_currentTable.AddCell(emptyCell);
iTextSharp.text.Font clubFont = new iTextSharp.text.Font(Font.FontFamily.HELVETICA, 12, Font.NORMAL, new BaseColor(0.541f, 0.765f, 0f));
PdfPCell cell = new PdfPCell();
Paragraph clubName = new Paragraph(clubString, clubFont) {Alignment = Element.ALIGN_CENTER};
cell.AddElement(clubName);
cell.BackgroundColor = BaseColor.DARK_GRAY;
cell.HorizontalAlignment = Element.ALIGN_JUSTIFIED;
cell.VerticalAlignment = Element.ALIGN_CENTER;
cell.MinimumHeight = 30f;
cell.Colspan = _currentTable.NumberOfColumns - 6;
cell.Border = Rectangle.NO_BORDER;
_currentTable.AddCell(cell);
iTextSharp.text.Font dispFont = new iTextSharp.text.Font(Font.FontFamily.HELVETICA, 10, Font.NORMAL, BaseColor.WHITE);
PdfPCell dispCell = new PdfPCell();
Paragraph dispersion = new Paragraph(dispersionString, dispFont);
dispersion.Alignment = Element.ALIGN_CENTER;
dispCell.AddElement(dispersion);
dispCell.HorizontalAlignment = Element.ALIGN_JUSTIFIED;
dispCell.VerticalAlignment = Element.ALIGN_CENTER;
dispCell.MinimumHeight = 30f;
dispCell.Colspan = 3;
dispCell.BackgroundColor = BaseColor.DARK_GRAY;
dispCell.Border = Rectangle.NO_BORDER;
_currentTable.AddCell(dispCell);

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