private void btnExportar_Click(object sender, EventArgs e)
{
string fileName = "ReporteVentas.pdf";
string titulo = "Reporte de Ventas";
string paragraph = $"Ventas realizadas desde la fecha {dtFechaDesde.Value} hasta {dtFechaHasta.Value}";
try
{
if (grillaReporte.Rows.Count > 0)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "PDF (.pdf)|.pdf";
sfd.FileName = fileName;
bool fileError = false;
if (sfd.ShowDialog() == DialogResult.OK)
{
if (File.Exists(sfd.FileName))
{
File.Delete(sfd.FileName);
}
if (!fileError)
{
PdfPTable pdfTable = new PdfPTable(grillaReporte.Columns.Count);
pdfTable.DefaultCell.Padding = 3;
pdfTable.WidthPercentage = 100;
pdfTable.HorizontalAlignment = Element.ALIGN_LEFT;
foreach (DataGridViewColumn column in grillaReporte.Columns)
{
PdfPCell cell = new PdfPCell(new Phrase(column.HeaderText));
pdfTable.AddCell(cell);
}
foreach (DataGridViewRow row in grillaReporte.Rows)
{
foreach (DataGridViewCell cell in row.Cells)
{
pdfTable.AddCell(cell.Value.ToString());
}
}
using (FileStream stream = new FileStream(sfd.FileName, FileMode.Create))
{
Document pdfDoc = new Document(PageSize.A4, 10f, 20f, 20f, 10f);
PdfWriter.GetInstance(pdfDoc, stream);
pdfDoc.Open();
//Titulo y parrafo.
iTextSharp.text.Font titleFont = FontFactory.GetFont("Arial", 26);
titleFont.IsUnderlined();
iTextSharp.text.Font regularFont = FontFactory.GetFont("Arial", 15);
Paragraph title = new Paragraph(titulo, titleFont);
title.Alignment = Element.ALIGN_CENTER;
pdfDoc.Add(title);
pdfDoc.Add(new Chunk("\n"));
Paragraph text = new Paragraph(paragraph, regularFont);
pdfDoc.Add(text);
pdfDoc.Add(new Chunk("\n"));
pdfDoc.Add(pdfTable);
pdfDoc.Close();
stream.Close();
}
MessageBox.Show("Exportacion realizada con exito.", "OK", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
else
{
throw new Exception("No hay registros para exportar.");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}