PDF OptimizeResources() throws System.NullReferenceException

Hi,

I’m investigating an error where a PDF document is created and we call the OptimizeResources() method which is throwing System.NullReferenceException:

System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.NullReferenceException: Object reference not set to an instance of an object.
   at Aspose.Pdf.Annotations.AppearanceDictionary.get_Keys()
   at Aspose.Pdf.Page.#=zGDyUiziuwWsKPybL1Q==(Dictionary`2 #=zIVKdkQI=, #=zASXAsxoUvkkbTNSl1LHKIl65jurzxhYN8g== #=zM$QV2FjNdUPa)
   at Aspose.Pdf.Page.#=z0$JF27wPjEgV(Dictionary`2 #=zIVKdkQI=, #=zASXAsxoUvkkbTNSl1LHKIl65jurzxhYN8g== #=zM$QV2FjNdUPa)
   at #=z0knCxwf13jeps5Ty9ohJGz8h3JId.#=zGHvEvAQ=(OptimizationOptions #=zKaEAcMg=)
   at Aspose.Pdf.Document.#=ztHzev6EAfINW()
   at Aspose.Pdf.Document.OptimizeResources()

Our code before making this call:

using (var document = new Document(readStream))
            {
                var options = new HtmlSaveOptions(HtmlDocumentType.Html5, true)
                {
                    RasterImagesSavingMode = HtmlSaveOptions.RasterImagesSavingModes.AsEmbeddedPartsOfPngPageBackground,
                    PartsEmbeddingMode = HtmlSaveOptions.PartsEmbeddingModes.EmbedAllIntoHtml,
                    LettersPositioningMethod = HtmlSaveOptions.LettersPositioningMethods.UseEmUnitsAndCompensationOfRoundingErrorsInCss,
                    CompressSvgGraphicsIfAny = true,
                    CustomHtmlSavingStrategy = htmlSavingInfo =>
                    {
                        htmlSavingInfo.ContentStream.CopyTo(writeStream);
                    },
                };

            foreach (Page page in document.Pages)
            {
                var imageIndex = 1;
                foreach (XImage image in page.Resources.Images)
                {
                    using (var imageStream = new MemoryStream())
                    {
                        image.Save(imageStream, System.Drawing.Imaging.ImageFormat.Jpeg);
                        page.Resources.Images.Replace(imageIndex, imageStream, 20);
                        imageIndex++;
                    }
                }
            }

            document.Optimize();
            document.OptimizeResources();

Please advice how we can address this, many thanks

1 Like

@EmaryB,

Thanks for adding the code snippet. Can you please add the document that is producing the error?

Hi Carlos,

Sorry, I can’t get hold of it as it’s a customer document. I’ve tried a few variations of PDFs with annotations but have not been able to recreate yet.