System.NullReferenceException during Find and replace

Hi,

We use Aspose PDF for .Net “TextFragmentAbsorber” to replace texts in PDF (mailmerge)
It is working as expected in local.

Our code is hosted in Azure kubernetes,
We do mailmerge on a particular template for all employees, at that time we see the same template is being replaced correctly but sometimes Aspose throws null exception during text replacement.

Below is the log

BadRequest: {“ClassName”:“System.NullReferenceException”,“Message”:“Object reference not set to an instance of an object.”,“Data”:null,“InnerException”:null,“HelpURL”:null,“StackTraceString”:" at #=zl5NplOm6n11lygSVEhnZ4y73l28MTstVDg==.#=zox8OcPwf5Eqy(Page #=z0fsEDUg=, Rectangle #=zaAv6WcPYx_38nTF0pA==, Rectangle& #=zMlmSm4o0Ocm6)\n at #=zl5NplOm6n11lygSVEhnZ4y73l28MTstVDg==.#=zWBipjk7uPpce(TextFragment #=zowM730DgbTaW, Double #=zQY3rsd6b5ExUyZDSLw==)\n at #=zl5NplOm6n11lygSVEhnZ4y73l28MTstVDg==…ctor(TextFragment #=zGsaClO8=, Double #=zQY3rsd6b5ExUyZDSLw==)\n at Aspose.Pdf.Text.TextFragment.#=ztN13La7PQE2SfoN5wQ==(Double #=zLqAru00X3neZ)\n at Aspose.Pdf.Text.TextFragment.set_Text(String value)\n at Hrx.DocGen.Infrastructure.Services.PDFReportBuilderService.ReplaceFragmentFromDict(String parameter, Document document, IDictionary2 templateValues) in /home/vsts/work/1/s/src/Hrx.DocGen.Infrastructure/Services/PDFReportBuilderService.cs:line 94\n at Hrx.DocGen.Infrastructure.Services.PDFReportBuilderService.FindAndReplaceDocumentData(DocumentGenerationModel generationModel, Document document, CancellationToken cancellationToken) in /home/vsts/work/1/s/src/Hrx.DocGen.Infrastructure/Services/PDFReportBuilderService.cs:line 216\n at Hrx.DocGen.Infrastructure.Services.PDFReportBuilderService.BuildReport(DocumentGenerationModel generationModel, CancellationToken cancellationToken) in /home/vsts/work/1/s/src/Hrx.DocGen.Infrastructure/Services/PDFReportBuilderService.cs:line 50\n at Hrx.DocGen.Infrastructure.Services.DocumentMergeService.MergeDocumentAsync(String consumer, String gcc, String lcc, Int32 documentId, DocumentMergeParameters model, CancellationToken cancellationToken, String language) in /home/vsts/work/1/s/src/Hrx.DocGen.Infrastructure/Services/DocumentMergeService.cs:line 127\n at Hrx.DocGen.WebApi.Controllers.DocumentsController.MergeDocument(String consumer, String gcc, String lcc, Int32 documentId, String language, ExternalDocumentMergeRequest request, CancellationToken cancellationToken) in /home/vsts/work/1/s/src/Hrx.DocGen.WebApi/Controllers/DocumentsController.cs:line 119\n at lambda_method367(Closure, Object)\n at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.AwaitableObjectResultExecutor.Execute(ActionContext actionContext, IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)\n at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g__Logged|12_1(ControllerActionInvoker invoker)\n at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)\n at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)\n at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)\n at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g__Awaited|13_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)\n at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|25_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)\n at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)\n at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)\n at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|20_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)\n at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Logged|17_1(ResourceInvoker invoker)\n at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Logged|17_1(ResourceInvoker invoker)\n at Microsoft.AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask|7_0(Endpoint endpoint, Task requestTask, ILogger logger)\n at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)\n at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)\n at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)\n at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)\n at Nga.Toolbox.AspNetCore.Middlewares.PingMiddleware`1.Invoke(HttpContext httpContext)\n at Hrx.DocGen.WebApi.Middleware.ExceptionsHandlingMiddleware.Invoke(HttpContext httpContext) in /home/vsts/work/1/s/src/Hrx.DocGen.WebApi/Infrastructure/Middleware/ExceptionsHandlingMiddleware.cs:line 32",“RemoteStackTraceString”:null,“RemoteStackIndex”:0,“ExceptionMethod”:null,“HResult”:-2147467261,“Source”:“Aspose.PDF”,“WatsonBuckets”:null}

Below is the source code

 private static void ReplaceFragmentFromDict(List<string> lstTextToReplace)
 {
        IDictionary<string, object> templateValues = new Dictionary<string, object> {  { "PERSONNAME", "Jagan" } , { "EMPID", "999888" }  };

         Aspose.Pdf.Document doc = new Aspose.Pdf.Document("C:/Jagan/My Project/MailMergePdf/MailMergePdf/MergeTemplate1.pdf");

        foreach (string parameter in lstTextToReplace)
        {
            TextFragmentAbsorber tfa = new TextFragmentAbsorber(s);
            doc.Pages.Accept(tfa);
            textFragmentAbsorber.TextReplaceOptions.ReplaceAdjustmentAction = TextReplaceOptions.ReplaceAdjustment.WholeWordsHyphenation;

            foreach (TextFragment textFragment in tfa.TextFragments) // line 94
            {
                textFragment.Text = Convert.ToString(templateValues.FirstOrDefault(x => x.Key.Equals(parameter, StringComparison.InvariantCultureIgnoreCase)).Value);
            }
        }

        doc.Save(Assembly.GetExecutingAssembly().Location + "ForumTemplate.pdf");
    }

We are unable to replicate this issue in local
So, can you please throw some light on this error, is it a data issue or can it be handled through C# code

@mjjagan

You are getting a System.NullReferenceException when the line

textFragment.Text = …;

is executed inside the TextFragmentAbsorber loop while running the mail‑merge in Azure Kubernetes.

Possible causes and steps to try

  1. Upgrade Aspose.PDF for .NET – using a newer version (e.g., 22.3 or later) often resolves this kind of exception [2][6].

  2. Ensure required fonts are available on the Kubernetes nodes (install the fonts used in the PDF template or copy them into the container and register the folder with FontRepository). Missing fonts can trigger the same NullReferenceException [2][6].

  3. Check the replacement value before assigning it to the fragment, e.g.:

    var value = templateValues.FirstOrDefault(
                  x => x.Key.Equals(parameter, StringComparison.InvariantCultureIgnoreCase)).Value;
    
    if (value != null)
        textFragment.Text = Convert.ToString(value);
    

    This prevents a null being written to the fragment, which can also cause the exception.

After applying these changes, run the job again. If the problem persists, please provide a minimal reproducible sample (PDF, code, exact Aspose.PDF version) so we can investigate further.

We currently use Aspose PDF 25.0.2 version - we will upgrade it
We already installed the needed fonts through docker
We will also add the null checking condition before replacement.

In any case below is the template being failed for few data
EAFORM_2023.pdf (683.0 KB)

@mjjagan

You are seeing a System.NullReferenceException when the line

textFragment.Text = …;

executes inside the TextFragmentAbsorber loop while the mail‑merge runs in Azure Kubernetes.

What to try

  1. Guard the replacement value – the dictionary lookup may return null. Assign the text only when a non‑null value is present:

    var value = templateValues
                .FirstOrDefault(x => x.Key.Equals(parameter,
                                  StringComparison.InvariantCultureIgnoreCase))
                .Value;
    
    if (value != null)
        textFragment.Text = Convert.ToString(value);
    

    This prevents the NullReferenceException that can occur when a null is written to the fragment [1].

  2. Ensure required fonts are available – missing fonts in the container can also trigger the same exception. Install the fonts used by the PDF template on the Docker image and register the folder, e.g.:

    FontRepository.RegisterDirectory("/usr/share/fonts");
    
  3. Consider upgrading Aspose.PDF for .NET – newer releases include many bug‑fixes, and moving to a later version may resolve intermittent NullReferenceException issues.

  4. Similar cases have been reported for other Aspose.PDF APIs (e.g., Document.Save() and Document.OptimizeResources()), indicating that certain versions may contain internal defects [7][8].

If the exception persists after applying the null‑check, confirming font availability, and upgrading, please attach a minimal reproducible sample (the PDF file that fails, the exact code snippet, and the Aspose.PDF version) so we can investigate further in this thread.