Вывод в формате PDF С # iTextSharp - PullRequest
2 голосов
/ 11 марта 2019

Я только начинаю изучать библиотеку itextsharp C # и столкнулся с исключением. Тип этого исключения является специфическим для этой библиотеки.

Существует следующий код, который формирует документ PDF:

private static void returnPdf(IEnumerable<object> reportItemList)
{
    var suggestedFileName = "Sales_By_Payment_Type_Report" + ".pdf";
    using (var doc = new Document(PageSize.A4, 60, 60, 30, 30))
    {
        PdfWriter.GetInstance(doc, new FileStream(suggestedFileName, FileMode.Create));
        doc.Open();
        doc.NewPage(); 

        var totalList = reportItemList as IEnumerable<ReportItem>;
        if (totalList != null)
        {
          //filter by 14
          var members = typeof(ReportItem).GetMembers().Where(memb =>memb.MemberType == 
            System.Reflection.MemberTypes.Property && memb.GetCustomAttributes(false).Where(att => (att as ReportProperty)?.PropertyName != String.Empty).Count() != 0);
          var itemNumber = members.Count();
          if (itemNumber != 0)
          { 
            PdfPTable table = new PdfPTable(itemNumber);
            PdfPCell[] itemArray = new PdfPCell[itemNumber];
            for (int i = 0; i < itemArray.Length - 1; i++)
            {
              var customList = members.ElementAt(i).CustomAttributes.Where(t => t.AttributeType == typeof(ReportProperty)).FirstOrDefault()?.ConstructorArguments;
              if (customList.Count != 0) {
                itemArray[i] = new PdfPCell();
                itemArray[i].Phrase = new Phrase(customList[0].Value.ToString());
              }
            }
            PdfPRow pdfRow = new PdfPRow(itemArray);
            table.Rows.Add(pdfRow);                
            //footer
            table.Rows.Add(new PdfPRow(new PdfPCell[itemNumber]));
            try
            {                      

              **doc.Add(table);**

            }
            catch (DocumentException ex)
            {
              throw ex;

            }           

          }
        }

    }
}

В блоке try выдается исключение DocumenException от iTextSharp

enter image description here

doc, таблица не пуста Пожалуйста, помогите, спасибо

iTextSharp.text.DocumentException:  reference to an object does not indicate an object instance.
    в PdfTesting.Program.returnPdf(IEnumerable`1 reportItemList) в D:\FranPosTest\iconnect-web\PdfTesting\Program.cs:строка 70   
    в PdfTesting.Program.Main(String[] args) в D:\FranPosTest\iconnect-web\PdfTesting\Program.cs:строка 107
    в System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
    в System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
    в Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
    в System.Threading.ThreadHelper.ThreadStart_Context(Object state)
    в System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
    в System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
    в System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
    в System.Threading.ThreadHelper.ThreadStart()

1 Ответ

1 голос
/ 11 марта 2019

Вы делаете это

//footer
table.Rows.Add(new PdfPRow(new PdfPCell[itemNumber]));

т.е. вы создаете новый PdfPRow на основе нового PdfPCell массива, для которого не задано значение, поэтому все записи в этом массиве null.

Когда iText пытается расположить эту таблицу во время doc.Add(table), он, в конечном счете, пытается также расположить эту строку и наталкивается на все эти null ячейки.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...