---
title: "Detect a PDF shading function limit in C#"
url: https://recursiveai.org/onepdf/cookbook/detect-pdf-shading-function-limit/
description: "Detect when a PDF shading function exceeds its operation budget in C#. Sample a gradient and check OnePDF’s flag before using the returned color."
version: "1.26.1"
---

# Detect a PDF shading function limit in C#

**OnePDF** is a free, open-source PDF library for .NET from Recursive AI. MIT or Apache-2.0, no native dependencies.

[NuGet](https://www.nuget.org/packages/RecursiveAI.OnePdf) · [GitHub](https://github.com/recursive-ai-oss/onepdf-csharp) · [Docs](https://recursiveai.org/onepdf/docs/) · [Download example (.zip)](https://recursiveai.org/onepdf/cookbook/detect-pdf-shading-function-limit/detect-pdf-shading-function-limit.zip)

Some PDF gradients compute their colors with a small program (a Type 4 function), which OnePDF stops if it exceeds its operation budget so that evaluation can’t run indefinitely; it then sets `FunctionLimitExceeded` because the color is unreliable.

```shell
dotnet add package RecursiveAI.OnePdf
```

Requires [.NET 10](https://dotnet.microsoft.com/download/dotnet/10.0) (net10.0); .NET 9 and earlier aren’t supported.

```csharp
using OnePdf;

// gradient.pdf is in the zip.
var limits = PdfLimits.Default with
    { MaxType4Operations = 1 };
var opts = new PdfOpenOptions
    { Limits = limits };
using var doc = PdfDocument.Open(
    "gradient.pdf", opts);
doc.Pages[0].Interpret(new Probe());

sealed class Probe : PdfDevice
{
    public override void PaintShading(
        PdfShading shading,
        in PdfGraphicsState state)
    {
        var n =
            shading.ColorComponentCount;
        var color = new double[n];
        shading.EvaluateAt(50, 50, color);
        if (shading.FunctionLimitExceeded)
            Console.WriteLine(
                "Unreliable color.");
    }
}
```

[The example](https://recursiveai.org/onepdf/cookbook/detect-pdf-shading-function-limit/detect-pdf-shading-function-limit.zip) is the full program below: unzip it and `dotnet run`. To run only the code above, paste it into Program.cs of a new `dotnet new console` project and `dotnet run`.

Copy `gradient.pdf` from the zip into your working directory before running the snippet, or change the filename in the code to your own PDF. With the sample, it prints:

```text
Unreliable color.
```

## The full program

`gradient.pdf` is a one-page gray gradient. Its Type 4 calculator function is `{ dup dup }`: it duplicates the input twice to give red, green, and blue the same value. The example samples the gradient at `(50, 50)` with a one-operation budget and then opens the same file again with the default budget.

```csharp
using OnePdf;

Check(PdfLimits.Default with
    { MaxType4Operations = 1 });
Check(PdfLimits.Default);

static void Check(PdfLimits limits)
{
    var options = new PdfOpenOptions
        { Limits = limits };
    using var doc = PdfDocument.Open(
        "gradient.pdf", options);
    var probe = new ShadingProbe();
    doc.Pages[0].Interpret(probe);

    var diagnostics = doc.Diagnostics;
    foreach (var diagnostic in diagnostics)
        Console.WriteLine(
            $"{diagnostic.Severity}: " +
            diagnostic.Message);
}

sealed class ShadingProbe : PdfDevice
{
    public override void PaintShading(
        PdfShading shading,
        in PdfGraphicsState state)
    {
        var count =
            shading.ColorComponentCount;
        var color = new double[count];
        bool sampled = shading.EvaluateAt(
            50, 50, color);
        var message =
            shading.FunctionLimitExceeded
            ? "Discarded unreliable shading " +
              "color."
            : sampled
                ? "Sampled shading color."
                : "No color at this point.";
        Console.WriteLine(message);
    }
}
```

```text
Discarded unreliable shading color.
Warning: A shading function ran past the limit of 1 operations and was stopped; its colours are not reliable.
Sampled shading color.
```

Once a shading function runs past the budget, “its colour is not reliable”; discard the affected color or report that the render is incomplete.

## Variations

### Treat the diagnostic as an error

For a workflow that rejects bad shading instead of allowing a preview, open the sample with strict mode and the same small budget. The sample evaluation throws `PdfException` in this mode.

```csharp
using OnePdf;

// Probe is the device class from the snippet at the top.
var limits = PdfLimits.Default with
{
    MaxType4Operations = 1
};
using var doc = PdfDocument.Open("gradient.pdf",
    new PdfOpenOptions { Limits = limits, Strict = true });
try
{
    doc.Pages[0].Interpret(new Probe());
}
catch (PdfException)
{
    Console.WriteLine("Rejected the shading.");
}
```

## Related recipes

- [Set resource limits for untrusted PDFs](https://recursiveai.org/onepdf/cookbook/limit-resource-use-when-reading-untrusted-pdf/)
- [Repair a damaged PDF](https://recursiveai.org/onepdf/cookbook/repair-damaged-pdf/)

## The short answer

In a `PdfDevice` that samples shadings, check `PdfShading.FunctionLimitExceeded` **after** evaluating the color and before you use it. If the flag is set, the calculator function was stopped and the shading’s colors aren’t reliable. The PDF can open and the device can receive the shading without a warning until something evaluates it.

## What is a shading function in a PDF?

A shading describes how color varies across a region of a PDF page. In this sample, the gradient goes along a straight line: each position along that line has an input value, and a function maps that value to a color. The sample uses a Type 4 function, called a PostScript calculator function, to copy one value into three color components. Since red, green, and blue are equal, you see shades of gray rather than a colored gradient.

Not every shading uses a Type 4 function. The flag answers a narrower question: did a Type 4 function in this shading run past its configured budget? It doesn’t check arbitrary defects in a page or tell you whether other drawing operations completed.

## How do I tell if a PDF shading function exceeded its limit in C#?

`MaxType4Operations` applies to one function evaluation, not the whole page or file. OnePDF’s [default is 100,000 operations](https://recursiveai.org/onepdf/docs/repair/#limits-checked-while-interpreting-a-page). The example lowers it to one so a routine two-operator function triggers the flag.

Check the flag on the `PdfShading` your device received. It stays set on that object once an evaluation hits the limit. Don’t use the boolean returned by `EvaluateAt` as a substitute: it indicates whether there is a color sample at that point, not whether the calculator function finished within budget. The full program checks both before reporting a usable sample.

In normal mode OnePDF records one warning per affected shading. With strict mode it reports an error and throws during evaluation. Use the warning and flag to identify a partial preview, or strict mode if the output must be rejected rather than shown with missing colors. A shading flag isn’t a report on other operations that use Type 4 functions, such as tint transforms; use the document diagnostics to see those warnings too.
