Boa tarde, pessoal.
Tenho um botão que preenche um DataGridView com dados de uma tabela do banco e coloca em um PDF.
Estou usando o iTextSharp.
O código do botão está assim:
DateTime dataTemp = Convert.ToDateTime(dtmDataRelatorio.Value.Date);
String dataFormatada = dataTemp.ToString("yyyyMMdd");
string sql = "SELECT * FROM CONTRATOS WHERE VENCIMENTO='" + dataFormatada + "' AND STATUS='" + "Ativo" + "'"; ;
var connection = new MySqlConnection(ConnectionString);
MySqlCommand command = new MySqlCommand(sql, connection);
connection.Open();
MySqlDataAdapter data = new MySqlDataAdapter(sql, connectionString);
DataSet tabela = new DataSet();
MySqlCommandBuilder cmd = new MySqlCommandBuilder(data);
data.Fill(tabela);
dgvBaixaParcelas.DataSource = tabela.Tables[0];
Document document = new Document();
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream("c://sample.pdf", FileMode.Create));
document.Open();
iTextSharp.text.Font font5 = FontFactory.GetFont(FontFactory.HELVETICA, 5);
PdfPTable table = new PdfPTable(dgvBaixaParcelas.Columns.Count);
table.WidthPercentage = 100;
int iCol = 0;
string colname = "";
PdfPCell cell = new PdfPCell(new Phrase("Products"));
cell.Colspan = dgvBaixaParcelas.Columns.Count;
foreach (DataColumn c in dgvBaixaParcelas.Columns)
{
table.AddCell(new Phrase(c.ColumnName, font5));
}
foreach (DataRow r in dgvBaixaParcelas.Rows)
{
if (dgvBaixaParcelas.Rows.Count > 0)
{
table.AddCell(new Phrase(r[0].ToString(), font5));
table.AddCell(new Phrase(r[1].ToString(), font5));
table.AddCell(new Phrase(r[2].ToString(), font5));
table.AddCell(new Phrase(r[3].ToString(), font5));
}
}
document.Add(table);
document.Close();
Mas ele retorna o seguinte erro:
iTextSharp.text.DocumentException: 'Wrong number of columns.'