Error trying to generate a pdf with DataGridView C # using iTextSharp

1

I have a problem with the code I am writing to generate a pdf with the data from a DataGridView. After I run the DGV with the MySQL query, and I give the generate button, it throws an error that says: "Object reference not set to an instance of an object" the truth is I'm guiding myself from a video on youtube. (I'm new to programming: 3)

using System;
using System.IO;
using System.Windows.Forms;
using iTextSharp.text;
using iTextSharp.text.pdf;

public void exportarPDF(DataGridView DGAusentismo, string nombreArchivo)
    {
        try
        {
            BaseFont bf = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1250, BaseFont.EMBEDDED);
            PdfPTable pdfTable = new PdfPTable(DGAusentismo.Columns.Count);
            pdfTable.DefaultCell.Padding = 3;
            pdfTable.WidthPercentage = 100;
            pdfTable.HorizontalAlignment = Element.ALIGN_CENTER;
            pdfTable.DefaultCell.BorderWidth = 1;
            iTextSharp.text.Font texto = new Font(bf, 10, iTextSharp.text.Font.NORMAL);

            //Header
            foreach (DataGridViewColumn columnas in DGAusentismo.Columns)
            {
                PdfPCell celda = new PdfPCell(new Phrase(columnas.HeaderText, texto));
                celda.BackgroundColor = new iTextSharp.text.BaseColor(240, 240, 240);
                pdfTable.AddCell(celda);
            }

            //Agregar DataRow 
            foreach (DataGridViewRow Filas in DGAusentismo.Rows)
            {
                foreach (DataGridViewCell Celdas in Filas.Cells)
                {
                    pdfTable.AddCell(new Phrase(Celdas.Value.ToString(),texto));  // El mensaje de error me dice que es esta linea
                }
            }
            var savedialog = new SaveFileDialog();
            savedialog.FileName = nombreArchivo;
            savedialog.DefaultExt = ".pdf";

            if (savedialog.ShowDialog() == DialogResult.OK)
            {
                using (FileStream stream = new FileStream(savedialog.FileName, FileMode.Create))
                {
                    Document pdf = new Document(PageSize.LEGAL, 10f, 10f, 10f, 0f);
                    PdfWriter.GetInstance(pdf, stream);
                    pdf.Open();
                    pdf.Add(pdfTable);
                    pdf.Close();
                    stream.Close();
                }
            }
        }
        catch (Exception error)
        {
            MessageBox.Show("A ocurrido un error durante la exportacion: " + error.ToString());
        }
    }

The video that I'm guiding myself on is this: Export Datagridview to PDF

Now if someone has a better guide to export the datagridview to pdf I would be very grateful if you let me know because the video is in English and I do not understand many things that it explains.

Thanks

    
asked by Andres Rodriguez FARP 06.10.2018 в 18:14
source

1 answer

-1

To export to PDF with this method it is necessary to add the reference.

Microsoft.Office.Interop.Excel

An Excel workbook is generated, in which the DataGridView is added and then exported to PDF.

private void exportaPDF(System.Windows.Forms.DataGridView dgvConsulta)
    {
        SaveFileDialog fichero = new SaveFileDialog();
        fichero.Filter = "PDF (*.pdf)|*.pdf";
        if (fichero.ShowDialog() == DialogResult.OK)
        {
            try
            {
                string temp;
                int iColumnas = 0;
                Microsoft.Office.Interop.Excel.Application xlsApp = new Microsoft.Office.Interop.Excel.Application();//creo una aplicación Excel
                xlsApp.DisplayAlerts = false;
                Worksheet xlsSheet; //creo una hoja
                Workbook xlsBook; //creo un libro
                xlsApp.Visible = false; //la aplicación no es visible
                xlsBook = xlsApp.Workbooks.Add(true);//añado el libro a la aplicación
                xlsSheet = (Worksheet)xlsBook.ActiveSheet; //activo la hoja, para el libro
                //titulo
                xlsSheet.Cells[2, 6] = "Fecha y hora";
                xlsSheet.Cells[2, 7] = DateTime.Now;
                xlsSheet.Cells[2, 3] = "Resultados de la busqueda:";
                for (int iCol = 0; iCol < dgvConsulta.Columns.Count; iCol++)
                {
                    if (dgvConsulta.Columns[iCol].Visible == true)
                    {
                        xlsSheet.Cells[4, iCol + 2] = dgvConsulta.Columns[iCol].HeaderText;
                        iColumnas++;
                    }
                }

                for (int iRow = 0; iRow < dgvConsulta.Rows.Count; iRow++)
                {
                    for (int iCol = 0; iCol < dgvConsulta.Columns.Count; iCol++)
                    {
                        if (dgvConsulta.Columns[iCol].Visible == true)
                        {
                            temp = dgvConsulta[iCol, iRow].Value.ToString();
                            xlsSheet.Cells[iRow + 5, iCol + 2] = temp;
                        }
                    }
                }
                //formato          
                xlsSheet.Columns.Font.Name = "Arial";
                xlsSheet.Columns.Font.Size = 12;
                xlsSheet.Columns.AutoFit(); //Ajusta ancho de todas las columnas
                xlsSheet.ExportAsFixedFormat(Microsoft.Office.Interop.Excel.XlFixedFormatType.xlTypePDF, fichero.FileName,
                                             Microsoft.Office.Interop.Excel.XlFixedFormatQuality.xlQualityStandard,
                                             true, true, 1, 10, false);
                //xlsApp.Visible = true;
                xlsApp.Quit();
            }
            catch (Exception e)
            { MessageBox.Show("Ha ocurrido un error durante la generacion del reporte: \n" + e.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); }
            DialogResult result = MessageBox.Show("El reporte ha sido guardado con exito\n¿Desea visualizar el reporte recien creado?",
                        "Guardado de Reportes", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
            if (result == DialogResult.Yes)
            { Process.Start(fichero.FileName); }
        }
    }
    
answered by 06.10.2018 в 21:55