pdfDocument.Save(memoryStream) Getting NullReferenceException

Error: Object reference not set to an instance of an object…Exception object : System.NullReferenceException: Object reference not set to an instance of an object.
at #=zRDUKRU55u8mAfFX2I_EEU0XGxGJ_.#=z6jnc$1k=(#=zDdmyxZq7fotIQ2JdFVApGKO2HhLC #=z5MEAOYbJiYjK)
at #=zCJJby4ltqCVgU9dGcd9YRLA=.#=zi5DASHY=(#=zDdmyxZq7fotIQ2JdFVApGKO2HhLC #=z5MEAOYbJiYjK)
at #=zvmuiC7xg8Q8YqYPTHzOI0yg=.#=zi5DASHY=(#=zDdmyxZq7fotIQ2JdFVApGKO2HhLC #=z5MEAOYbJiYjK)
at #=qyb9nUGBqrF0SUpbpvOreQWwsH0qZqbbbqtVRjaqvqoQ=.#=zLhQAAaTOl3RDiRVbrDwIclM=(Object #=zsbe4rCg=)
at #=qyb9nUGBqrF0SUpbpvOreQWwsH0qZqbbbqtVRjaqvqoQ=.#=zDB$m3K$OfGgVQX0lQ3Pz8WiW_hDtDwA4iBx8e2I=(MethodBase #=zsbe4rCg=, Boolean #=zqMXp$Dw=)
at #=qyb9nUGBqrF0SUpbpvOreQWwsH0qZqbbbqtVRjaqvqoQ=.#=zojguYfqXW5dPll1Gu707nY43kI1bp$i_70lCRbw=(#=qyb9nUGBqrF0SUpbpvOreQWwsH0qZqbbbqtVRjaqvqoQ= #=zsbe4rCg=, #=qhRkB3agCPUmfXc531hGbRT7ATONKdBNULmd6SlUHmFA= #=zqMXp$Dw=)
at #=qyb9nUGBqrF0SUpbpvOreQWwsH0qZqbbbqtVRjaqvqoQ=.#=zcxyOnYB71qfpf6cb_02$0$gtCa6A9ef2RIu5825XiOhU()
at #=qyb9nUGBqrF0SUpbpvOreQWwsH0qZqbbbqtVRjaqvqoQ=.#=zFDnjrthoOvb21q_KH$wNZfp$ubKq(Boolean #=zsbe4rCg=)
at #=qyb9nUGBqrF0SUpbpvOreQWwsH0qZqbbbqtVRjaqvqoQ=.#=zLhQAAaTOl3RDiRVbrDw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H0qZqbbbqtVRjaqvqoQ=.#=zCQDHAvNk5nA7xKo2tUTxdls=(Object[] #=zsbe4rCg=, Type[] #=zqMXp$Dw=, Type[] #=zqE13wLw=, Object[] #=z$E3GNss=)
at #=qyb9nUGBqrF0SUpbpvOreQWwsH0qZqbbbqtVRjaqvqoQ=.#=zarV02q_mxB8_cZzvb__xPkQ0KCa1Sn1rVw==(Stream #=zsbe4rCg=, String #=zqMXp$Dw=, Object[] #=zqE13wLw=)
at #=qyb9nUGBqrF0SUpbpvOreQWwsH0qZqbbbqtVRjaqvqoQ=.#=zPfUiW43F6H8ZDde7$psWd85FXtsx9fG2uA==(Stream #=zsbe4rCg=, String #=zqMXp$Dw=, Object[] #=zqE13wLw=)
at Aspose.Pdf.Document.#=zi4GC8wjiZUZd(Stream #=z4pqNpB4=, SaveOptions #=zi4O4HzyLOJ$X)
at Aspose.Pdf.Document.Save(Stream output)

@venkateswarlu123
Please attach a more complete fragment of the code used and the document used.

@sergei.shibanov

  • We are trying to replace text in particular position.
  • It is working in onprem services and local windows machine.
  • We are migrating our onprem service to GCP when we deploy our code to GCP in which we have GKE linux based instance, Its throwing above exception.
  • We using Aspose.PDF 23.9 Latest version
  • The sample pdf file here
    sample-pdf.pdf (59.0 KB)

here is the C# code in .net core 6 we using
Code Snippet:

var transformedFileInBytes = TransformDocumentUsingAspose_test(pdfStream, "Signature", "Venkateswarlu123");

private byte[] TransformDocumentUsingAspose_test(Stream stream, string searchText, string textToReplace)
        {
            byte[] transformedFileInBytes = null;
            Document pdfDocument = new Document(stream);   //Converting PDF Document Stream to Aspose.PDF.Document
            Page searchTextMatchedPage = null;				    //Aspose.PDF.Page
            var textFragmentAbsorber = new TextFragmentAbsorber(searchText); //Aspose.PDF.Text.TextFragmentAbsorber
            Position position = null;
            foreach (Page page in pdfDocument.Pages)
            {
                page.Accept(textFragmentAbsorber);
                position = textFragmentAbsorber.TextFragments?.ConvertToGenericList<TextFragment>()?.Select(x => x?.Position)?.FirstOrDefault();
                if (position == null) continue;
                searchTextMatchedPage = page;
                break;
            }
            if (position == null)
            {
                throw new KeyNotFoundException($"Document doesn't contain {searchText} text");
            }
            var xIndent = position?.XIndent ?? 20;
            var yIndent = position?.YIndent ?? 220;
            var searchTextMatchedPosition = new Position(xIndent, yIndent + 20);
            var textFragment = new TextFragment(textToReplace)
            {
                Position = searchTextMatchedPosition
            };
            textFragment.TextState.FontSize = 12;
            FontRepository.Sources.Add(new FolderFontSource(@"TimesNewRoman")); //To resolve Font Not Found exception on GCP GKE Linux instance
            var font = FontRepository.FindFont("TimesNewRoman");
            textFragment.TextState.Font = FontRepository.FindFont("TimesNewRoman");
            textFragment.TextState.BackgroundColor = Color.FromRgb(System.Drawing.Color.LightGray);
            textFragment.TextState.ForegroundColor = Color.FromRgb(System.Drawing.Color.Black);

            // Create TextBuilder object
            var textBuilder = new TextBuilder(searchTextMatchedPage);
            textBuilder.AppendText(textFragment);
            using (var memoryStream = new MemoryStream())
            {
                pdfDocument.Save(memoryStream);
                transformedFileInBytes = memoryStream.ToArray();
            }
            return transformedFileInBytes;
        }

@venkateswarlu123
please provide the code for the ConvertToGenericList method

@sergei.shibanov Here is the method implementation

public static IList<TList> ConvertToGenericList<TList>(this IEnumerable sourceList)
        {
            try
            {
                return sourceList.Cast<TList>().ToList();
            }
            catch (NullReferenceException ex)
            {
                throw ex;
            }
            catch (InvalidCastException innerException)
            {
                throw new InvalidCastException($"All source in sourceList must be of type: {typeof(TList)}", innerException);
            }
        }

@venkateswarlu123
I tried to reproduce this exception, but it worked for me.
Perhaps the reason is that the environment you are using does not have any fonts. I used the operator at the beginning of the code

FontRepository.Sources.Add(new FolderFontSource("Fonts"));

There were the following files in the Fonts folder. image.png (3.3 KB)

@sergei.shibanov Can you please confirm

  1. did you use linux machine ?
  2. we getting this issue ony when deployed to Google cloud GKE using linux base image. its working in onprem.
    are you trying the same to reproduce the issue?
    We also added this
    FontRepository.Sources.Add(new FolderFontSource("Fonts"));
    and font also getting read without any errors.

@venkateswarlu123
I don’t have GKE and I tested it in Visual Studio using docker desktop (for testing in a Linux environment). The most common problem in this case is the lack of any fonts. Unfortunately, this often throws a NullReferenceException or something else instead of indicating the absence of fonts. The stack trace you provided also indicates problems when opening the font. This feature is mentioned in How to Install Aspose.PDF for .NET|Aspose.PDF for .NET in the section Working with .NET Core DLLs in Non-Windows Environment.
When checking myself, I did
image.png (5.5 KB)
In addition, when working on Linux systems, I recommend using the Aspose.Pdf.Drawing library, which in this case is more reliable and does not require installation libgdiplus package (since it does not use libgdiplus)

Hi @sergei.shibanov
We have migrated that piece of code to another repo which is also hosted in GCP GKE
but using .net core 3.1 . There also we got Font Not Found exception, then we downloaded fonts manually to a folder and added that folder to Font Sources. After that it started working.
But this is not a permanent fix in our case. All of our code base will use .Net 6 going forward. Please get it fixed for .Net 6 deployed to GKE as soon as possible. If it is already fixed please help us to fix it.

@venkateswarlu123
For .Net 6 this should work similarly.

@sergei.shibanov but its not working, What can we do?

@venkateswarlu123
I’ll test this in a docker project and write to you tomorrow.

1 Like

@venkateswarlu123

at this link I posted a project with the code you provided under .Net 6 working in Docker Linux container.