【发布时间】:2016-11-08 08:44:10
【问题描述】:
当我将多个表格添加到 iText7 pdf 并且表格的数量超过一页的大小时,会引发以下异常。
异常:“对象引用未设置为对象的实例。” 来源:“itext.layout” StackTrace:“在 iText.Layout.Renderer.TableRenderer.Layout(LayoutContext 布局上下文) 在 iText.Layout.Renderer.RootRenderer.AddChild(IRenderer 渲染器) 在 iText.Layout.RootElement
1.Add[T2](BlockElement1 元素) 在 iText.Layout.Document.Add[T](BlockElement`1 元素) 在 iTextSharp7_Test.Controllers.PdfController.ReplicateBug(字符串 pdfFile) 在 C:\Users\me\Documents\Visual Studio 2015\Projects\App_Test\iTextSharp7_Test\Controllers\PdfController.cs:line 443"
在提供的示例中,当即将添加第 6 个表时,将引发异常。
我能够处理此问题的唯一方法是假设通过向 pdf 添加比适合一页更多的数据并在 try catch 块中添加新页面来引发异常,这是一个非常好的解决方案从长远来看,丑陋且不好。
例子:
public void ReplicateBug(string pdfFile)
{
iText.Kernel.Pdf.PdfWriter writer = null;
iText.Kernel.Pdf.PdfDocument pdf = null;
iText.Layout.Document document = null;
try
{
writer = new iText.Kernel.Pdf.PdfWriter(pdfFile);
pdf = new iText.Kernel.Pdf.PdfDocument(writer);
document = new iText.Layout.Document(pdf, iText.Kernel.Geom.PageSize.A4);
document.Add(new iText.Layout.Element.Paragraph("*** PRODUCTS ***"));
iText.Kernel.Pdf.Canvas.Draw.DashedLine dashedLine = new iText.Kernel.Pdf.Canvas.Draw.DashedLine();
document.Add(new iText.Layout.Element.LineSeparator(dashedLine));
iText.Layout.Element.Table table = null;
for (int i = 0; i < 10; ++i)
{
iText.Layout.Element.Cell cell = null;
table = new iText.Layout.Element.Table(2);
table.SetMarginTop(10);
cell = new iText.Layout.Element.Cell().Add("-- PRODUCT --");
table.AddCell(cell);
cell = new iText.Layout.Element.Cell(3, 1).Add("image");
cell.SetHorizontalAlignment(iText.Layout.Properties.HorizontalAlignment.CENTER);
cell.SetVerticalAlignment(iText.Layout.Properties.VerticalAlignment.MIDDLE);
table.AddCell(cell);
cell = new iText.Layout.Element.Cell().Add("Product text." + Environment.NewLine + "Welcome");
cell.SetHeight(75);
table.AddCell(cell);
cell = new iText.Layout.Element.Cell().Add((i + 1).ToString().PadLeft(10, '0'));
table.AddCell(cell);
try
{
document.Add(table);
document.Add(new iText.Layout.Element.LineSeparator(dashedLine)); // Default LineWidth is 1
}
catch
{
// NOTE: After adding 5 tables to the pdf an exception is thrown of the following kind.
// Exception: "Object reference not set to an instance of an object."
// Source: "itext.layout"
// StackTrace: "at iText.Layout.Renderer.TableRenderer.Layout(LayoutContext layoutContext)
// at iText.Layout.Renderer.RootRenderer.AddChild(IRenderer renderer)
// at iText.Layout.RootElement`1.Add[T2](BlockElement`1 element)
// at iText.Layout.Document.Add[T](BlockElement`1 element)
// at iTextSharp7_Test.Controllers.PdfController.ReplicateBug(String pdfFile) in C:\\Users\\me\\Documents\\Visual Studio 2015\\Projects\\App_Test\\iTextSharp7_Test\\Controllers\\PdfController.cs:line 443"
}
}
document.Close();
pdf.Close();
writer.Close();
}
catch
{
if (document != null)
{
document.Close();
}
if (pdf != null)
{
pdf.Close();
}
if (writer != null)
{
writer.Close();
}
throw;
}
}
提前致谢
【问题讨论】: