Aspose.Pdf.Page.Layers getter throws NullReferenceException when I attempt to access it first time without having Layers object initialized. This is not very intuitive (I expect it would return null value instead) and complicates business logic of my code that uses this API. Also, apparently this same issue causes an exception when I attempt to save a document that has some pages with layers, and some pages without layers. I am using Windows 10 OS and Aspose.PDF for .NET 21.10.1 (latest at the time of writing). Here is my code snippet:
using System;
using System.Collections.Generic;
using Aspose.Pdf;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
var document = new Document();
var page = document.Pages.Add();
try
{
if (page.Layers == null)
{
// Do something, for example: page.Layers = new List<Layer>();
}
}
catch (NullReferenceException)
{
Console.WriteLine("Issue #1: why this exception? Checking Layers getter return value for null should be possible.");
}
var page2 = document.Pages.Add();
page2.Layers = new List<Layer>();
// Now some pages have layers, and some don't. This causes a second issue:
try
{
document.Save("get_layers_support.pdf");
}
catch (Exception e)
{
Console.WriteLine("Issue #2: why this exception? Saving a document should be possible.");
Console.WriteLine(e.StackTrace);
// A workaround is to assign 'new List<Layer>()' to layers in all pages that throw NullReferenceException
// on Layers getter, but this is not nice.
}
}
}
}
Here is the output of the above code snippet:
Issue #1: why this exception? Checking Layers getter return value for null should be possible.
Issue #2: why this exception? Saving a document should be possible.
at Aspose.Pdf.Page.get_Layers()
at Aspose.Pdf.Document.#=zcnoUeF8=()
at Aspose.Pdf.Document.#=z9mRpoUfSiIRh(Stream #=z8qPhCAQ=, SaveOptions #=znQ1_uSMlhiaM)
at Aspose.Pdf.Document.#=zuBW_ByWvJriT(String #=z8GuEkvTcxVz1)
at Aspose.Pdf.Document.Save(String outputFileName)
at ConsoleApp.Program.Main(String[] args)
Here is the code snippet attached:
Aspose_PDF_get_Layers_issue.zip (4.5 KB)
Can this be helped somehow? The expectation is that page.Layers returns null if the page does not have Layers property initialized (so that it can be assigned e.g. ‘new List()’), and also, that the Save() operation does not throw an exception like in the above use case.