Set a budget for draw calls, glyphs (drawn characters), and decoding filters.
dotnet add package RecursiveAI.OnePdfRequires .NET 10 (net10.0); .NET 9 and earlier aren’t supported.
using OnePdf; // demo values; start from // PdfLimits.Default in production var limits = PdfLimits.Default with { MaxDrawCallsPerPage = 16, MaxGlyphsPerPage = 4, MaxFilterChainLength = 2 }; var opts = new PdfOpenOptions { Limits = limits }; // hello.pdf is in the zip. using var doc = PdfDocument.Open("hello.pdf", opts); var text = doc.Pages[0].ExtractText(); bool failed = doc.Diagnostics.Any( d => d.Severity == PdfSeverity.Error); Console.WriteLine(failed ? "Discarded page text." : $"Accepted {text.Glyphs.Count} glyphs.");
The example 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.
Put hello.pdf (one rectangle and the text Hello PDF) in your working directory. With that file, the snippet sets a deliberately small glyph budget and prints:
Discarded page text.The full program
The sample draws one rectangle and writes nine glyphs, counting the space. Its content stream uses two filters: ASCII85 to store the compressed bytes as text and Flate for compression. The program checks each budget separately against the same file:
using OnePdf; Check("Glyph budget", PdfLimits.Default with { MaxGlyphsPerPage = 4 }); Check("Draw budget", PdfLimits.Default with { MaxDrawCallsPerPage = 1 }); Check("Filter budget", PdfLimits.Default with { MaxFilterChainLength = 1 }); Check("Defaults", PdfLimits.Default); static void Check( string label, PdfLimits limits) { try { var options = new PdfOpenOptions { Limits = limits }; using var doc = PdfDocument.Open( "hello.pdf", options); var page = doc.Pages[0]; var streams = page.ContentStreams; foreach (var stream in streams) _ = stream.GetDecodedBytes(); var text = page.ExtractText(); var errors = doc.Diagnostics; var failed = errors.Any(d => d.Severity == PdfSeverity.Error ); if (failed) { Print("discarded page text"); return; } int count = text.Glyphs.Count; Print($"{count} glyphs accepted"); } catch (PdfLimitException) { Print("rejected by a PDF limit"); } void Print(string result) => Console.WriteLine( $"{label}: {result}"); }
Glyph budget: discarded page text Draw budget: discarded page text Filter budget: rejected by a PDF limit Defaults: 9 glyphs accepted
If a page hits a draw or glyph limit, you can still get partial text with an error diagnostic; if a stream exceeds the filter-chain limit, a direct GetDecodedBytes() call throws PdfLimitException.
These bounds govern PDF reading and interpretation; they aren’t a sandbox or a guarantee that a file is safe.
Variations
Keep the other defaults and tighten only the glyph limit
Replace the limits declaration in the snippet with:
var limits = PdfLimits.Default with { MaxGlyphsPerPage = 4 };Related recipes
The short answer
Start with PdfLimits.Default, change the budgets that match your workload, and pass the result in PdfOpenOptions.Limits. Check for errors after the operation that uses the page, not just after opening the file. The sample discards extracted text when there’s an error rather than passing partial results downstream as if they were complete.
How can I safely open a suspicious PDF?
Keep parser limits enabled for uploads and documents from outside your application. PdfLimits puts bounds on work such as following objects and decoding streams. A separate upload byte limit controls the size of the file you accept; it doesn’t measure how much work a page will take to interpret. In a service, set application-level resource limits separately and avoid relying on a parser setting as the only boundary.
Reading the PDF and interpreting a page are separate steps. Opening a document successfully doesn’t tell you that a later page will stay within your budgets. Apply your policy at the point you use the result: for extraction, check after extracting the page; if you explicitly decode a stream, handle PdfLimitException there. A limit breach means that operation didn’t finish under your policy, not necessarily that the original PDF was malformed.
How do I set resource limits when opening a PDF in C#?
Choose limits by what your application consumes:
MaxDrawCallsPerPagecounts calls to the device that receives drawing commands, including paths, clips, glyph runs, images, and shadings. The default is 2²¹ calls per page.MaxGlyphsPerPagecounts glyphs before they are built, including glyphs inside form content and annotations. The default is 2¹⁹ per page.MaxFilterChainLengthcounts decoding stages listed in one stream’s filter array. The default is 32. It’s not a byte limit;MaxDecodedStreamBytesis a separate setting.
The four-glyph budget in the example is for seeing the failure on an ordinary page, not a production setting. Start with the defaults, test on the kinds of documents you actually accept, and decide how to report rejected pages. When a page stops, earlier drawing operations or glyphs may remain available. Don’t treat them as complete if you need a faithful preview or an exact extraction.