Cancellation and progress
Long calls take a CancellationToken and report progress through IProgress<PdfProgress>, so
a service can stop work nobody waits for and show how far a batch has come.
Short answer
Section titled “Short answer”Pass the request’s token to every call that takes one. In ASP.NET Core that is
HttpContext.RequestAborted; link it to a timeout of your own:
// Text of an uploaded PDF. When the client goes away, RequestAborted stops the work.app.MapPost("/text", async (HttpContext context) =>{ using var timeout = CancellationTokenSource.CreateLinkedTokenSource(context.RequestAborted); timeout.CancelAfter(TimeSpan.FromSeconds(30)); CancellationToken cancellationToken = timeout.Token;
var options = new PdfLoadOptions { Mode = PdfLoadMode.OnDemand, Limits = PdfLimits.Untrusted }; using PdfDocument doc = await PdfDocument.OpenAsync(context.Request.Body, options, cancellationToken);
var text = new StringBuilder(); foreach (PdfPage page in doc.Pages) { text.AppendLine(page.ExtractText(cancellationToken)); }
return Results.Text(text.ToString());});PdfLimits.Untrusted bounds what the file may cost on top of that, see
Resource limits.
Calls that take a token
Section titled “Calls that take a token”| Area | Calls |
|---|---|
| Opening and saving | PdfDocument.OpenAsync, Save(Stream, options, token), SaveAsync, ToArray(options, token) |
| Reading pages | PdfPage.ExtractText, GetWords, GetLetters, GetImages, PdfPageImage.Decode |
| Pages | Pages.Import, PdfDocument.Merge, MergeAsync, Split, SplitTo, SplitToAsync, ExtractPages, FlattenAnnotations, PdfAcroForm.Flatten |
| Optimizer | PdfOptimizer.Optimize, OptimizeAsync, OptimizeFileAsync |
| Signatures | PdfSigner.Sign, Verify, AddValidationData |
| HTML | HtmlConverter.ConvertToPdf, ConvertToPdfAsync, ConvertToDocument, ConvertToDocumentAsync |
The overloads without a token behave as before. Content is checked every 256 operators, the JPEG,
JPEG 2000, JBIG2 and CCITT decoders check inside an image, and saving checks before each object.
A cancelled call raises OperationCanceledException.
What a cancelled call leaves behind:
Pages.Importfrom one document leaves the target as it was. With pages from several documents, the fields and tags of the documents copied before the token fired stay in the target, tied to no page: discard the target.MergeandExtractPagesreturn nothing.Splitstops yielding parts; those already returned are yours to dispose.SplitToandSplitToAsynckeep the parts written before. When the token fires while a part is being written, that part’s stream is disposed and holds no complete file; progress reports count only complete parts.FlattenAnnotationskeeps the pages flattened before the token fired.Save,SaveAsyncandMergeAsyncleave an incomplete file in the output stream: discard it.
Some steps take no token yet: parsing the file once OpenAsync has read it, PdfInspector.Inspect
and PdfEquivalence.FindDifference. PdfLimits.Timeout bounds opening and inspection, so set it
when those run on files from users.
Merge uploads into a response
Section titled “Merge uploads into a response”MergeAsync takes the inputs as streams and reads one at a time: it reads an input to its end,
opens it on demand, copies its pages, releases it and disposes the stream before it asks for the
next. The merged pages stay in memory until they are written. With the optimizer off, the merged
file is written to the response as it is serialized. ASP.NET Core reads the uploaded form before
the handler runs and buffers files over 64 KB on disk, so the inputs do not come straight from
the network:
// Merge uploaded files into the response. ASP.NET Core reads the form first (files over 64 KB// go to disk), then MergeAsync reads one input at a time. The merged pages stay in memory// until they are written.app.MapPost("/merge", async (HttpContext context) =>{ IFormFileCollection files = (await context.Request.ReadFormAsync(context.RequestAborted)).Files; var options = new PdfMergeOptions { LoadOptions = new PdfLoadOptions { Mode = PdfLoadMode.OnDemand, Limits = PdfLimits.Untrusted }, SaveOptions = new PdfSaveOptions { Optimize = false }, // written progressively };
context.Response.ContentType = "application/pdf"; await PdfDocument.MergeAsync(files.Select(file => file.OpenReadStream()), context.Response.Body, options, progress: null, context.RequestAborted);});With the default save options the whole output is built and optimized in memory before it is
written, which proves it and makes it smaller. Choose by the size of what you merge. Pass
PdfMergeOptions.LeaveInputsOpen to keep the input streams open for your own code to dispose.
The same call merges files from disk, opening each when its turn comes:
// Merge files from disk, opening each when its turn comes and closing it once read.string[] paths = ["a.pdf", "b.pdf", "c.pdf"];await using (FileStream output = File.Create("merged-from-files.pdf")){ await PdfDocument.MergeAsync(paths.Select(File.OpenRead), output, cancel.Token);}Progress
Section titled “Progress”PdfProgress carries the items done so far and, when it is known in advance, the total. Each
call says what it counts:
| Call | Counts |
|---|---|
Merge | Pages merged, reported after each document |
MergeAsync | Inputs merged, out of their number when the inputs are a collection |
Split, SplitTo, SplitToAsync | Parts made or written, one per page |
FlattenAnnotations | Pages flattened |
// Report progress and allow cancelling a long merge.using var cancel = new CancellationTokenSource(TimeSpan.FromMinutes(2));PdfDocument[] parts = [PdfDocument.Open("a.pdf"), PdfDocument.Open("b.pdf"), PdfDocument.Open("c.pdf")];using PdfDocument merged = PdfDocument.Merge(parts, new ConsoleProgress("merged"), cancel.Token);await merged.SaveAsync("merged.pdf", cancellationToken: cancel.Token);Reports arrive on the thread doing the work, unless the IProgress<PdfProgress> given is a
Progress<T>, which posts them to the context it was created on. A handler that throws stops the
operation with its exception.
Split into streams
Section titled “Split into streams”SplitTo writes each page to a stream your code returns for it, disposing that stream before it
asks for the next, which commits zip entries, files and blob uploads one at a time:
// One file per page, each stream closed before the next page is written.using PdfDocument report = PdfDocument.Open("report.pdf");int written = report.SplitTo( page => File.Create($"report-page-{page + 1}.pdf"), progress: new ConsoleProgress("pages"), cancellationToken: cancel.Token);ExtractPages copies a range into a new document, with ranges on .NET 8 and later:
using PdfDocument source = PdfDocument.Open("report.pdf");using PdfDocument firstTwo = source.ExtractPages(0, 2);using PdfDocument lastOne = source.ExtractPages(^1..);firstTwo.Save("report-first-two.pdf");Limits
Section titled “Limits”- Parsing after
OpenAsynchas read the input,PdfInspector.InspectandPdfEquivalence.FindDifferencedo not take a token yet; usePdfLimits.Timeout. - A cancelled save or merge writes part of a file to the output stream. Write to a temporary file or buffer first when a partial response is a problem.
MergeAsyncholds a copy of every page’s objects until the output is written.
Related
Section titled “Related”- Resource limits and diagnostics
- Edit pages: merge, split and extract
- Large files: opening on demand
- API: PdfProgress, PdfMergeOptions, PdfDocument
Questions
- How do I stop PDF work when an ASP.NET Core client disconnects?
- Pass HttpContext.RequestAborted, or a token linked to it with a timeout, to OpenAsync, ExtractText, Merge, Save, the optimizer and the other calls that take one. Work stops within 256 content operators, inside image decoders, and between objects while saving.
- Can PdfNetStack merge large uploads without holding them all in memory?
- Mostly. PdfDocument.MergeAsync reads the inputs one at a time, opens each on demand, copies its pages and releases it before the next, but the merged pages stay in memory until they are written. With PdfSaveOptions.Optimize set to false, the merged file is written progressively to the output stream. In ASP.NET Core the form is read first, and files over 64 KB go to disk.