Generate a PDF file from two gridviews using iTextSharp - c#

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();

Related

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

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;

Generating PDF from a DataGridView in Winforms

I'm attempting to create a PDF from a DataGridView populated from a database.
I have just started trying to learn how to use iTextSharp to accomplish this.
The result of my code is a PDF that will not open. I get an error saying "File cannot be opened"
Here is my code to generate the PDF
void SendToPDF(string heading, string filename)
{
try
{
Document doc = new Document(PageSize.A4.Rotate(), 30, 30, 20, 20);
string myDocs = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
if (!Directory.Exists(myDocs + #"\Production Reports"))
Directory.CreateDirectory(myDocs + #"\Production Reports");
PdfWriter.GetInstance(doc, new FileStream(myDocs + #"\Production Reports\" + filename + ".pdf", FileMode.Append, FileAccess.Write));
iTextSharp.text.Font titleFont = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 14.0F, iTextSharp.text.Font.BOLD, BaseColor.BLACK);
iTextSharp.text.Font tableFont = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 12.0F, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);
iTextSharp.text.Font headerfont = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 12.0F, iTextSharp.text.Font.BOLD, BaseColor.BLACK);
PdfPTable table = new PdfPTable(GridView.Columns.Count);
//table.TotalWidth = GridView.Width;
//There are ALWAYS 10 columns
float[] widths = new float[] { GridView.Columns[0].Width, GridView.Columns[1].Width, GridView.Columns[2].Width,
GridView.Columns[3].Width, GridView.Columns[4].Width, GridView.Columns[5].Width,
GridView.Columns[6].Width, GridView.Columns[7].Width, GridView.Columns[8].Width,
GridView.Columns[9].Width };
table.SetWidths(widths);
table.HorizontalAlignment = 1; // 0 - left, 1 - center, 2 - right;
table.SpacingBefore = 2.0F;
PdfPCell cell = null;
doc.Open();
Phrase p = new Phrase(new Chunk(heading, titleFont));
doc.Add(p);
foreach (DataGridViewColumn c in GridView.Columns)
{
cell = new PdfPCell(new Phrase(new Chunk(c.HeaderText, headerfont)));
cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
cell.VerticalAlignment = PdfPCell.ALIGN_CENTER;
table.AddCell(cell);
}
if (GridView.Rows.Count > 0)
{
for (int i = 0; i < GridView.Rows.Count - 1; i++)
{
for (int j = 0; j < GridView.Columns.Count - 1; j++)
{
cell = new PdfPCell(new Phrase(GridView.Rows[i].Cells[j].Value.ToString(), tableFont));
cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
cell.VerticalAlignment = PdfPCell.ALIGN_CENTER;
table.AddCell(cell);
}
}
}
doc.Add(table);
doc.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + "\r\n" + ex.StackTrace, "Error Generating PDF", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
I'm guessing my problem has to do with setting column widths, but I'm not sure. One time, and only one time..I saw an error when I tried to open the PDF that said "illegal floating point division by 0" or something along those lines.
Any help is greatly appreciated.
It may sound obvious, but your program isn't running and locking the pdf file to its process thus preventing adobe pdf reader from reading it is it?
private void jbtnPdf_Click(object sender, EventArgs e)
{
try
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "All Files | *.* ";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
string path = saveFileDialog.FileName;
Document pdfdoc = new Document(PageSize.A4); // Setting the page size for the PDF
PdfWriter writer = PdfWriter.GetInstance(pdfdoc, new FileStream(path + ".pdf", FileMode.Create)); //Using the PDF Writer class to generate the PDF
writer.PageEvent = new PDFFooter();
// Opening the PDF to write the data from the textbox
PdfPTable table = new PdfPTable(jdgvChild.Columns.Count);
//table.TotalWidth = GridView.Width;
float[] widths = new float[] { jdgvChild.Columns[0].Width, jdgvChild.Columns[1].Width, jdgvChild.Columns[2].Width,
jdgvChild.Columns[3].Width, jdgvChild.Columns[4].Width, jdgvChild.Columns[5].Width,
jdgvChild.Columns[6].Width, jdgvChild.Columns[7].Width};
table.SetWidths(widths);
table.HorizontalAlignment = 1; // 0 - left, 1 - center, 2 - right;
table.SpacingBefore = 2.0F;
PdfPCell cell = null;
pdfdoc.Open();
//doc.Open();
// Phrase p = new Phrase(new Chunk(heading, titleFont));
// doc.Add(p);
foreach (GridViewDataColumn c in jdgvChild.Columns)
{
cell = new PdfPCell(new Phrase(new Chunk(c.HeaderText)));
cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
cell.VerticalAlignment = PdfPCell.ALIGN_CENTER;
table.AddCell(cell);
}
if (jdgvChild.Rows.Count > 0)
{
for (int i = 0; i < jdgvChild.Rows.Count; i++)
{
PdfPCell[] objcell = new PdfPCell[jdgvChild.Columns.Count];
for (int j = 0; j < jdgvChild.Columns.Count-1; j++)
{
cell = new PdfPCell(new Phrase(jdgvChild.Rows[i].Cells[j].Value.ToString()));
cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
cell.VerticalAlignment = PdfPCell.ALIGN_CENTER;
// table.AddCell(cell);
//lstCells.Add(cell);
objcell[j] = cell;
}
PdfPRow newrow = new PdfPRow(objcell);
table.Rows.Add(newrow);
}
}
pdfdoc.Add(table);
MessageBox.Show("Pdf Generation Successfully.");
pdfdoc.Close();
}
}
catch (Exception ex)
{
MessageBox.Show("Error in pdf Generation.");
}
}

iTextsharp landscape document

I am trying to create Landscape PDF using iTextSharp but It is still showing portrait. I am using following code with rotate:
Document document = new Document(PageSize.A4, 0, 0, 150, 20);
FileStream msReport = new FileStream(Server.MapPath("~/PDFS/") + "Sample1.pdf", FileMode.Create);
try
{
// creation of the different writers
PdfWriter writer = PdfWriter.GetInstance(document, msReport);
document.Open();
PdfPTable PdfTable = new PdfPTable(1);
PdfTable.SpacingBefore = 30f;
PdfPCell PdfPCell = null;
Font fontCategoryheader = new Font(Font.HELVETICA, 10f, Font.BOLD, Color.BLACK);
for (int i = 0; i < 20; i++)
{
PdfPCell = new PdfPCell(new Phrase(new Chunk("Sales Manager: ", fontCategoryheader)));
PdfPCell.BorderWidth = 0;
PdfPCell.HorizontalAlignment = Element.ALIGN_LEFT;
if (i % 2 == 0)
PdfPCell.BackgroundColor = Color.LIGHT_GRAY;
PdfPCell.PaddingBottom = 5f;
PdfPCell.PaddingLeft = 2f;
PdfPCell.PaddingTop = 4f;
PdfPCell.PaddingRight = 4f;
PdfTable.AddCell(PdfPCell);
}
document.Add(PdfTable);
document.NewPage();
}
catch (Exception ex)
{
Console.Error.WriteLine(ex.Message);
}
finally
{
// we close the document
document.Close();
}
Please suggest solution.
Thanks.
Try this
Document Doc = new Document(new Rectangle(288f, 144f), 10, 10, 10, 10);
Doc.SetPageSize(iTextSharp.text.PageSize.A4.Rotate());
you might also need this to expand a table to max width.
var _pdf_table = new PdfPTable(2); // table with two columns
PdfPCell hc = new PdfPCell();
_pdf_table.WidthPercentage = 100; //table width to 100per
_pdf_table.SetTotalWidth(new float[] { 25, iTextSharp.text.PageSize.A4.Rotate().Width - 25 });// width of each column
You must make sure that when setting the page size you do it before a call to Doc.Open();
Regards.
No need to initialize the Document and reset the page size...
Document doc = new Document(iTextSharp.text.PageSize.A4.Rotate(), 10, 10, 10, 10);
...will do the trick.
(4.1.6.0)

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