-1

Hope someone can spot the problem. I'm saving a DataGridView to PDF, and getting an error on the GetInstance line of code below. I've verified that sfd.FileName has a valid value and stream is not null.

System.NullReferenceException: 'Object reference not set to an instance of an object.'

using (FileStream stream = new FileStream (sfd.FileName, FileMode.Create)) {

   iTextSharp.text.Document pdfDoc =  new iTextSharp.text.Document (PageSize.A4, 10f, 20f, 20f, 10f);

   PdfWriter.GetInstance (pdfDoc, stream);   // NullReferenceException on this line.
   pdfDoc.Open();
   pdfDoc.Add (pdfTable);
   pdfDoc.Close();
   stream.Close();
}

Full method code:

private void SavePDF () {

    if (grdKeywordSearch.Rows.Count > 0) {
        SaveFileDialog sfd = new SaveFileDialog();
        sfd.Filter = "PDF (*.pdf)|*.pdf";
        sfd.FileName = "Output.pdf";
        bool fileError = false;
        if (sfd.ShowDialog () == DialogResult.OK) {
            if (File.Exists (sfd.FileName)) {
                try {
                    File.Delete (sfd.FileName);
                } catch (IOException ex) {
                    fileError = true;
                    MessageBox.Show ("It wasn't possible to write the data to the disk." + ex.Message);
                }
            }
            if (!fileError) {
                try {
                    PdfPTable pdfTable = new PdfPTable (grdKeywordSearch.Columns.Count);
                    pdfTable.DefaultCell.Padding = 3;
                    pdfTable.WidthPercentage = 100;
                    pdfTable.HorizontalAlignment = Element.ALIGN_LEFT;

                    foreach (DataGridViewColumn column in grdKeywordSearch.Columns) {
                        PdfPCell cell = new PdfPCell(new Phrase(column.HeaderText));
                        pdfTable.AddCell (cell);
                    }

                    foreach (DataGridViewRow row in grdKeywordSearch.Rows) {
                        foreach (DataGridViewCell cell in row.Cells) {
                            pdfTable.AddCell (cell.Value.ToString());
                        }
                    }

                    using (FileStream stream = new FileStream (sfd.FileName, FileMode.Create)) {

                        iTextSharp.text.Document pdfDoc =  new iTextSharp.text.Document (PageSize.A4, 10f, 20f, 20f, 10f);

                        PdfWriter.GetInstance (pdfDoc, stream);
                        pdfDoc.Open();
                        pdfDoc.Add (pdfTable);
                        pdfDoc.Close();
                        stream.Close();
                    }

                    MessageBox.Show ("Data Exported Successfully.", "Info");
                } catch (Exception ex) {
                    MessageBox.Show ("Error :" + ex.Message);
                }
            }
        }
    } else {
        MessageBox.Show ("Nothing to export.", "Info");
    }

}

Stack Trace added via this code, one line before the error:

Console.WriteLine (new System.Diagnostics.StackTrace().ToString());

The thread 0x4508 has exited with code 0 (0x0). The thread 0x6078 has exited with code 0 (0x0). at Clarity.frmClarity.SavePDF() at Clarity.frmClarity.btnSavePDF_Click(Object sender, EventArgs e) at System.Windows.Forms.Control.OnClick(EventArgs e) at System.Windows.Forms.Button.OnClick(EventArgs e) at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent) at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks) at System.Windows.Forms.Control.WndProc(Message& m) at System.Windows.Forms.ButtonBase.WndProc(Message& m) at System.Windows.Forms.Button.WndProc(Message& m) at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg) at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData) at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context) at Clarity.Program.Main()

John
  • 185
  • 1
  • 3
  • 17
  • Can you share the full stack trace? – mkl Oct 01 '20 at 13:51
  • Hi, mkl. Just added to my original post. – John Oct 01 '20 at 14:44
  • You may need to give fully qualified path: iTextSharp.text.pdf.PdfWriter.GetInstance(). My guess is the compiler thinks PdfWriter is supposed to be an object that was not initialized. See here: [iTextSharp pdfWriter.GetInstance error](https://stackoverflow.com/questions/26884908/itextsharp-pdfwriter-getinstance-error) – Adam Oct 01 '20 at 15:07
  • I did that, but still get the same error. :( – John Oct 01 '20 at 16:17

2 Answers2

1

I found the solution, although I do not understanding it. You have to turn on "Just My Code" under debugging options. The error went away after I did that.

John
  • 185
  • 1
  • 3
  • 17
  • https://stackoverflow.com/questions/32048766/what-is-just-my-code I don't know much about .NET, but maybe you are running your code in Debug mode? And Visual Studio is a bit weird about that? Can you reproduce the issue in JetBrains Rider? That's an IDE that I am more familiar with. – Amedee Van Gasse Oct 01 '20 at 21:58
0

I'm using VS 2022. The ' turn on "Just My Code" ' worked for me too. In my case, it was the PdfStamper that complained:

var pdfStamper = new PdfStamper(pdfReader, new FileStream(pdfOutputFilePath, FileMode.Create));

An empty file was getting created. Also, when at the breakpoint, due the exception, in the immediate window I was able to assign new FileStream(pdfOutputFilePath, FileMode.Create) to a variable, and .Write(byte) and .Close(), so it was not a 'permissions' problem.

Also, the app worked fine when I ran the .exe from the bin folders, and also ran fine when I put similar code in LinqPad 6 & 7. I also tried running VS "as administrator", and that did not work.

It seems that the same issue was reported here (so I'll post the answer there too) iTextSharp null reference error when using PdfStamper with all PDFs and non-null stream

dr9
  • 51
  • 1
  • 7