iTextSharp Pdftable Issue - c#

I am facing issue while generating pdf from Windows form using iTextSharp dll. I am populating more than 70 records at a time in a dataset and I am binding same to new table(pdfptable) by looping. But it says Object reference not set to instance of object. when I reduced number of rows to 68 it works fine. After analysis I found that table is not able to split along the multiple pages.
I am using following piece of code. Please help
float[] widths1 = new float[] { 1f, 2f,1f,1f,1f,1f,1f};
PdfPTable grd = new PdfPTable(GrdAnoSecList.Columns.Count);
grd.SetWidths(widths1);
for (int i = 0; i < GrdAnoSecList.Columns.Count; i++)
{
PdfPCell ph;
if (Convert.ToString(GrdAnoSecList.Columns[i].HeaderText) == "Job Name")
{
ph = new PdfPCell(new Phrase(GrdAnoSecList.Columns[i].HeaderText, grdfontHdr));
ph.BackgroundColor = new iTextSharp.text.Color(240, 240, 240);
ph.BorderWidthTop = 0;
ph.BorderWidthRight = 0;
ph.HorizontalAlignment = 1;
}
else
{
ph= new PdfPCell(new Phrase(GrdAnoSecList.Columns[i].HeaderText, grdfontHdr));
ph.BackgroundColor = new iTextSharp.text.Color(240, 240, 240);
ph.BorderWidthTop = 0;
ph.BorderWidthRight = 0;
ph.HorizontalAlignment = 1;
//ph.Width = 100f;
}
grd.AddCell(ph);
}
int ct = 0;
foreach (DataGridViewRow row in GrdAnoSecList.Rows)
{
foreach (DataGridViewCell cell in row.Cells)
{
ct++;
PdfPCell ph2;
if (Convert.ToString(cell.Value) == "Total")
{
ph2 = new PdfPCell(new Phrase(cell.Value.ToString(), grdfontHdr));
}
else
{
ph2 = new PdfPCell(new Phrase(cell.Value.ToString(), myfont));
}
if (cell.ValueType == typeof(decimal) || cell.ValueType == typeof(Int32))
{
ph2.HorizontalAlignment = 2;
}
else if (cell.ColumnIndex == 1 && Convert.ToString(cell.Value) != "Total")
{
ph2.HorizontalAlignment = 0;
}
else
{
ph2.HorizontalAlignment = 1;
}
grd.AddCell(ph2);
}
}
PdfPCell cellAmountText1 = new PdfPCell(new PdfPTable(grd));
cellAmountText1.Colspan = 6;
table.AddCell(cellAmountText1);

Related

Conversion from DataGridView to DataTable

these two functions take care of converting a datagridview into a datatable using c # when the conversion is carried out the file is printed on the pdf, but the name of the columns is embossed once the printing is done in pdf, how can I solve this? I have to make the column name appear
C# Code:
private DataTable GetDataTableFromDGV(DataGridView dgv)
{
var dt = new DataTable();
foreach (DataGridViewColumn column in dgv.Columns)
{
if (column.Visible)
{
dt.Columns.Add();
}
}
object[] cellValues = new object[dgv.Columns.Count];
foreach (DataGridViewRow row in dgv.Rows)
{
for (int i = 0; i < row.Cells.Count; i++)
{
cellValues[i] = row.Cells[i].Value;
}
dt.Rows.Add(cellValues);
}
return dt;
}
public void createPDF(DataTable dataTable, string destinationPath)
{
Document document = new Document();
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(destinationPath, FileMode.Create));
document.Open();
PdfPTable table = new PdfPTable(dataTable.Columns.Count);
table.WidthPercentage = 100;
//Set columns names in the pdf file
for (int k = 0; k < dataTable.Columns.Count; k++)
{
PdfPCell cell = new PdfPCell(new Phrase(dataTable.Columns[k].ColumnName));
cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
cell.VerticalAlignment = PdfPCell.ALIGN_CENTER;
cell.BackgroundColor = new iTextSharp.text.BaseColor(51, 102, 102);
table.AddCell(cell);
}
//Add values of DataTable in pdf file
for (int i = 0; i < dataTable.Rows.Count; i++)
{
for (int j = 0; j < dataTable.Columns.Count; j++)
{
PdfPCell cell = new PdfPCell(new Phrase(dataTable.Rows[i][j].ToString()));
cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
cell.VerticalAlignment = PdfPCell.ALIGN_CENTER;
table.AddCell(cell);
}
}
document.Add(table);
document.Close();
}
Try adding this in the foreach loop that adds columns:
dt.Columns.Add(column.Name, typeof(string));
Or alternatively:
dt.Columns.Add(column.HeaderText, typeof(string));
So it would look like this:
foreach (DataGridViewColumn column in dgv.Columns)
{
if (column.Visible)
{
dt.Columns.Add(column.Name, typeof(string));
}
}
I haven't tested this code but you have to explicitly add names to the Columns, tell me if it works...

Repeat Heading to table in pdf

I am using the Itextsharp PDF tool to generate PDF using asp.net and C# , In that in one PDFPtable the last row data is repeating on next page means part of a table forwarded to next page. so want to show header for that Table on next page.
This is my code.
Document doc = new Document(iTextSharp.text.PageSize.A4.Rotate(), 10, 10, 20, 10);
string pdfFilePath = Server.MapPath(".") + "/pdf/myPdf" + Guid.NewGuid().ToString("N") + ".pdf";
try
{
//Create Document class object and set its size to letter and give space left, right, Top, Bottom Margin
FileStream fs = new FileStream(pdfFilePath, FileMode.Create);
//
PdfWriter wri = PdfWriter.GetInstance(doc, fs);
//Header Section
string strImagePath = Server.MapPath("Images");
string strReportName = oReportDTO.strReportName + " " + oReportDTO.oDateRange.FromDate.ToString(DateFormat);
Chunk headerchunk = new Chunk(strReportName, new Font(1, 8.0f));
HeaderFooter oHeader = new HeaderFooter(new Phrase(headerchunk), false);
oHeader.Border = Rectangle.NO_BORDER;
oHeader.Alignment = 1;
doc.Header = oHeader;
//Footer Section
string name ="Logged in as : " +currentLoggedInUser.UserName + new string(' ',70)+ "Page Number : " + doc.PageNumber;
Chunk Footerchunk1 = new Chunk(name, new Font(1, 5.0f));
HeaderFooter oFooter1 = new HeaderFooter(new Phrase(Footerchunk1), true);
oFooter1.Border = Rectangle.NO_BORDER;
oFooter1.Alignment = 1;
doc.Footer = oFooter1;
iTextSharp.text.Image imgFooter = iTextSharp.text.Image.GetInstance(System.Drawing.Image.FromFile(strImagePath + "/TransRisk Logo168x97.png"), System.Drawing.Imaging.ImageFormat.Jpeg);
imgFooter.ScaleAbsolute(80, 50);
Chunk footerchunk = new Chunk(imgFooter, 260.0f, 0.0f);
HeaderFooter oFooter = new HeaderFooter(new Phrase(name),new Phrase(footerchunk));
oFooter.Border =Rectangle.NO_BORDER;
doc.Footer = oFooter;
doc.Open();//Open Document to write
Font font8 = FontFactory.GetFont("ARIAL", 7);
HtmlTable dt = customMatrixReport;
if (dt.Rows.Count > 0)
{
//Craete instance of the pdf table and set the number of column in that table
int startColumnPosition = 1;
int endColumnPosition = 13;//End Column number in Pdf Page
int NoOfReports = Convert.ToInt32(Math.Ceiling((decimal)(dt.Rows[0].Cells.Count - 1) / endColumnPosition));//Count How many Pages to show
int pageRowCount = 0;
List<PdfPCell> lstHeaderCells = new List<PdfPCell>();
PdfPTable oPdfTable = null;
PdfPCell oPdfPCell = null;
for (int report = 1; report <= NoOfReports; ++report)
{
doc.Add(oHeader);
//ColumnText.ShowTextAligned(
int noOfColumns = -1;
if (endColumnPosition > dt.Rows[0].Cells.Count - 1) { endColumnPosition = dt.Rows[0].Cells.Count - 1; noOfColumns = (endColumnPosition - startColumnPosition) + 2; oPdfTable = new PdfPTable(noOfColumns); }
else
{
oPdfTable = new PdfPTable(14);
//Widths Count
noOfColumns = 14;
}
oPdfTable.TotalWidth = 650f;
List<float> lstwidths = new List<float>();
lstwidths.Add(100f);
for (int i = 2; i <= noOfColumns; ++i)
{
lstwidths.Add(80f);
}
oPdfTable.SetTotalWidth(lstwidths.ToArray());
pageRowCount = 0;
for (int rows = 0; rows < dt.Rows.Count; rows++)
{
//PageRowCount
pageRowCount = pageRowCount + 1;
//Description celll
if (rows == 0 )
{
//Background color for table header
oPdfPCell = new PdfPCell(new Phrase(new Chunk(dt.Rows[rows].Cells[0].InnerText, new Font(1, 8.0f, 1, Color.WHITE))));
oPdfPCell.BackgroundColor = new Color(118, 147, 199);
oPdfTable.AddCell(oPdfPCell);
}
else
{
//background color for Table cells
oPdfPCell = new PdfPCell(new Phrase(new Chunk(dt.Rows[rows].Cells[0].InnerText,new Font(1, 8.0f))));
oPdfPCell.BackgroundColor = new Color(232, 237, 255);
oPdfTable.AddCell(oPdfPCell);
}
//for header cel
if (rows == 0)
{
lstHeaderCells.Add(oPdfPCell);
}
for (int column = startColumnPosition; column <= endColumnPosition; column++)
{
if (rows == 0)
{
oPdfPCell = new PdfPCell(new Phrase(new Chunk(dt.Rows[rows].Cells[column].InnerText, new Font(1, 8.0f, 1, Color.WHITE))));
oPdfPCell.BackgroundColor = new Color(118, 147, 199);
oPdfTable.AddCell(oPdfPCell);
}
else
{
oPdfPCell = new PdfPCell(new Phrase(new Chunk(dt.Rows[rows].Cells[column].InnerText, new Font(1, 8.0f))));
oPdfPCell.BackgroundColor = new Color(232, 237, 255);
oPdfPCell.Column.Alignment = 2;
oPdfTable.AddCell(oPdfPCell);
}
if (rows == 0)
{
lstHeaderCells.Add(oPdfPCell);
}
}
if (pageRowCount >= 40 && rows != (dt.Rows.Count - 1))
{
pageRowCount = 0; doc.Add(oPdfTable); doc.NewPage(); doc.Add(oHeader); oPdfTable = new PdfPTable(noOfColumns); oPdfTable.SetTotalWidth(lstwidths.ToArray()); foreach (PdfPCell oHeaderCell in lstHeaderCells) { oPdfTable.AddCell(oHeaderCell); }
}
}
startColumnPosition = endColumnPosition + 1;
endColumnPosition = endColumnPosition + 13;
oPdfTable.SpacingBefore = 10;
oPdfTable.SpacingAfter = 10;
doc.Add(oPdfTable);
//doc.NewPage();
}
}
else
doc.Add(oHeader);
}
finally
{
doc.Close();
}
help me..
Change this line-
if (endColumnPosition > dt.Rows[0].Cells.Count - 1) { endColumnPosition = dt.Rows[0].Cells.Count - 1; noOfColumns = (endColumnPosition - startColumnPosition) + 2; oPdfTable = new PdfPTable(noOfColumns); }
To this-
if (endColumnPosition > dt.Rows[0].Cells.Count - 1) { endColumnPosition = dt.Rows[0].Cells.Count - 1; noOfColumns = (endColumnPosition - startColumnPosition) + 2; oPdfTable = new PdfPTable(noOfColumns); oPdfTable.HeaderRows = 1;}
After this line-
oPdfTable = new PdfPTable(14);
Add this-
oPdfTable.HeaderRows = 1;
Change this line-
pageRowCount = 0; doc.Add(oPdfTable); doc.NewPage(); doc.Add(oHeader); oPdfTable = new PdfPTable(noOfColumns); oPdfTable.SetTotalWidth(lstwidths.ToArray()); foreach (PdfPCell oHeaderCell in lstHeaderCells) { oPdfTable.AddCell(oHeaderCell); }
To this-
pageRowCount = 0; doc.Add(oPdfTable); doc.NewPage(); doc.Add(oHeader); oPdfTable = new PdfPTable(noOfColumns); oPdfTable.HeaderRows = 1; oPdfTable.SetTotalWidth(lstwidths.ToArray()); foreach (PdfPCell oHeaderCell in lstHeaderCells) { oPdfTable.AddCell(oHeaderCell); }

XML to Word Table

I am trying to create a word table from xml file but the rows are not in their proper order,ie the first element occurs as last row, 2nd as 1st row and so on. Where am i going wrong?
Word.Table oTable;
Word.Range wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
oTable = oDoc.Tables.Add(wrdRng, ds.Tables[0].Rows.Count, ds.Tables[0].Columns.Count, ref oMissing, ref oMissing);
oTable.Range.ParagraphFormat.SpaceAfter = 6;
oTable.Borders.InsideLineStyle = Word.WdLineStyle.wdLineStyleSingle;
oTable.Borders.OutsideLineStyle = Word.WdLineStyle.wdLineStyleSingle;
for (int r = 1; r <= ds.Tables[0].Rows.Count; r++)
{
for (int c = 1; c <= ds.Tables[0].Columns.Count; c++)
{
oTable.Cell(r, c).Range.Text = ds.Tables[0].Rows[r-1].ItemArray[c-1].ToString();
}
}
Here is the sample code to create simple word file with Table. It will give you a loop hint how to proceed with it.
class Program
{
static void Main(string[] args)
{
Document doc = new Document();
Section s = doc.AddSection();
Table table = s.AddTable(true);
//Create Header and Data
String[] header = { "Item", "Description", "Qty", "Unit Price", "Price" };
String[][] data = {
new String[]{ "Spire.Doc for .NET",".NET Word Component","1","$799.00","$799.00"},
new String[]{"Spire.XLS for .NET",".NET Excel Component","2","$799.00","$1,598.00"},
new String[]{"Spire.Office for .NET",".NET Office Component","1","$1,899.00","$1,899.00"},
new String[]{"Spire.PDF for .NET",".NET PDFComponent","2","$599.00","$1,198.00"},
};
//Add Cells
table.ResetCells(data.Length + 1, header.Length);
//Header Row
TableRow fRow = table.Rows[0];
fRow.IsHeader = true;
//Row Height
fRow.Height = 23;
//Header Format
fRow.RowFormat.BackColor = Color.AliceBlue;
for (int i = 0; i < header.Length; i++)
{
//Cell Alignment
Paragraph p = fRow.Cells[i].AddParagraph();
fRow.Cells[i].CellFormat.VerticalAlignment = VerticalAlignment.Middle;
p.Format.HorizontalAlignment = HorizontalAlignment.Center;
//Data Format
TextRange TR = p.AppendText(header[i]);
TR.CharacterFormat.FontName = "Calibri";
TR.CharacterFormat.FontSize = 14;
TR.CharacterFormat.TextColor = Color.Teal;
TR.CharacterFormat.Bold = true;
}
//Data Row
for (int r = 0; r < data.Length; r++)
{
TableRow dataRow = table.Rows[r + 1];
//Row Height
dataRow.Height = 20;
//C Represents Column.
for (int c = 0; c < data[r].Length; c++)
{
//Cell Alignment
dataRow.Cells[c].CellFormat.VerticalAlignment = VerticalAlignment.Middle;
//Fill Data in Rows
Paragraph p2 = dataRow.Cells[c].AddParagraph();
TextRange TR2 = p2.AppendText(data[r][c]);
//Format Cells
p2.Format.HorizontalAlignment = HorizontalAlignment.Center;
TR2.CharacterFormat.FontName = "Calibri";
TR2.CharacterFormat.FontSize = 12;
TR2.CharacterFormat.TextColor = Color.Brown;
}
}
//Save and Launch
doc.SaveToFile("WordTable.docx", FileFormat.Docx2013);
System.Diagnostics.Process.Start("WordTable.docx");
Console.ReadLine();
}

Grouping elements while exporting dataGridView to PDF using iTextSharp

I'm trying to export my datagridview to PDF however while doing that I want to group the rows which have the same Group name.
The code I use to export to pdf is at the below;
private void PrintReport_Click(object sender, EventArgs e)
{
try
{
//create iTextSharp table
PdfPTable pdfTable = new PdfPTable(dataGridView1.ColumnCount);
pdfTable.DefaultCell.Padding = 3;
pdfTable.WidthPercentage = 30;
pdfTable.HorizontalAlignment = Element.ALIGN_LEFT;
pdfTable.DefaultCell.BorderWidth = 1;
//Adding Header row
PdfPCell cell = new PdfPCell(new Phrase("Report"));
cell.Colspan = 11;
cell.BackgroundColor = new iTextSharp.text.Color(50, 50, 120);
cell.HorizontalAlignment = 1;
pdfTable.TotalWidth = 1200f;
pdfTable.LockedWidth = true;
pdfTable.AddCell(cell);
pdfTable.AddCell("Group");
pdfTable.AddCell("Numara");
pdfTable.AddCell("Müşteri ID");
pdfTable.AddCell("Tanım");
pdfTable.AddCell("IP Adresi");
pdfTable.AddCell("Kullanıcı");
pdfTable.AddCell("Şifre");
pdfTable.AddCell("Domain");
pdfTable.AddCell("2.IP");
pdfTable.AddCell("2.Kullanıcı");
pdfTable.AddCell("2.Kullanıcı Şifre");
//Adding DataRow
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
for (int j = 0; j < dataGridView1.Columns.Count; j++)
{
if (dataGridView1.Rows[i].Cells[j].Value != null)
{
if (j == 6|| j == 10)
{
pdfTable.AddCell("*****");
}
else if(j==0)
{
pdfTable.AddCell(dataGridView1.Rows[i].Cells[6].Value.ToString());
}
else if(j==6)
{
pdfTable.AddCell(dataGridView1.Rows[i].Cells[0].Value.ToString());
}
else
{
pdfTable.AddCell(dataGridView1.Rows[i].Cells[j - 1].Value.ToString());
}
}
else
{
pdfTable.AddCell(" ");
}
}
}
//pdfTable.AddCell(cells.Value.ToString());
//Exporting to PDF
string folderPath = "C:\\PDFs\\";
if (!Directory.Exists(folderPath))
{
Directory.CreateDirectory(folderPath);
}
using (FileStream stream = new FileStream(folderPath + "Rapor.pdf", FileMode.Create))
{
Document pdfDoc = new Document(PageSize.A2, 10f, 10f, 10f, 0f);
PdfWriter.GetInstance(pdfDoc, stream);
pdfDoc.Open();
pdfDoc.Add(pdfTable);
pdfDoc.Close();
stream.Close();
}
MessageBox.Show("C:\\PDFs uzantısına rapor kaydedildi!");
}
catch (Exception msg)
{
MessageBox.Show(msg.Message, "Error");
}
}
Code works pretty well, it exports the datagridview to pdf file but it does not work the way I want, It does not group columns by 'Group Name'
I'm stuck in this problem any help would be appreciated.
Can you just sort the results, create a pdfTable for each 'group' that has data?
I have solved the problem with a little trick, I have listed all the groups in a list named 'testlist' So I can manage the handle the sutiation within 1 pdfTable
There is the code snippet:
for (int element = 0; element < testList.Count;element++ )
{
string name = testList.ElementAt(element).ToString();
PdfPCell cell1 = new PdfPCell(new Phrase(name));
cell1.BackgroundColor = new iTextSharp.text.Color(160, 160, 210);
cell1.Colspan = 11;
cell1.HorizontalAlignment = 1;
pdfTable.AddCell(cell1);
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
for (int j = 0; j < dataGridView1.Columns.Count; j++)
{
if (dataGridView1.Rows[i].Cells[j].Value != null)
{
if(dataGridView1.Rows[i].Cells[6].Value.ToString() == name.ToString())
{
if (j == 6 || j == 10)
{
pdfTable.AddCell("*****");
}
else if (j == 0)
{
pdfTable.AddCell(dataGridView1.Rows[i].Cells[6].Value.ToString());
}
else if (j == 6)
{
pdfTable.AddCell(dataGridView1.Rows[i].Cells[0].Value.ToString());
}
else
{
pdfTable.AddCell(dataGridView1.Rows[i].Cells[j - 1].Value.ToString());
}
}
}
else
{
pdfTable.AddCell(" ");
}
}
}
}

Office Open XMl SDK Writing Numbers to Sheet

I am trying wo write Numbers from a DataTable to an Datasheet - unfortunately, this does not work as expected, e. g. the DataSheet is corrupted.
I am using the following code:
private void AddDataToSheet(ExcelViewData data, SheetData sheetData)
{
var excelData = data.WriteableDataTable;
// this returns a datatable
// the numbers have a format like "8,1" "8,0" etc.
for (int i = 0; i < excelData.Rows.Count; i++)
{
Row row = new Row();
//row.RowIndex = (UInt32)i;
for (int c = 0; c < excelData.Columns.Count; c++)
{
Cell cell = new Cell();
CellValue cellvalue = new CellValue();
//cell.CellReference = SharedMethods.GetExcelColumnName(i + 1) + (c + 1).ToString();
cell.DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.Number;
cellvalue.Text = excelData.Rows[i][c].ToString().Replace(",",".");
cell.Append(cellvalue);
row.Append(cell);
}
sheetData.Append(row);
}
}
Any Idea why this fails? I have seem multiple tutorials with the same approach.
Try out this method:
public void InsertDataTableIntoExcel(SpreadsheetDocument _excelDoc, SheetData SheetData, DataTable excelData, int rowIndex = 1)
{
if (_excelDoc != null && SheetData != null)
{
if (excelData.Rows.Count > 0)
{
try
{
uint lastRowIndex = (uint)rowIndex;
for (int row = 0; row < excelData.Rows.Count; row++)
{
Row dataRow = GetRow(lastRowIndex, true);
for (int col = 0; col < excelData.Columns.Count; col++)
{
Cell cell = GetCell(dataRow, col + 1, lastRowIndex);
string objDataType = excelData.Rows[row][col].GetType().ToString();
//Add text to text cell
if (objDataType.Contains(TypeCode.Int32.ToString()) || objDataType.Contains(TypeCode.Int64.ToString()) || objDataType.Contains(TypeCode.Decimal.ToString()))
{
cell.DataType = new EnumValue<CellValues>(CellValues.Number);
cell.CellValue = new CellValue(objData.ToString());
}
else
{
cell.CellValue = new CellValue(objData.ToString());
cell.DataType = new EnumValue<CellValues>(CellValues.String);
}
}
lastRowIndex++;
}
}
catch (OpenXmlPackageException ex)
{
throw ex;
}
catch (Exception ex)
{
throw ex;
}
}
else
{
OpenXmlPackageException openEx = new OpenXmlPackageException("No data from datatable");
throw openEx;
}
}
else
{
OpenXmlPackageException openEx = new OpenXmlPackageException("Workbook not found");
throw openEx;
}
}

Categories

Resources