# Cancellation and progress

> Stop long PDF work in .NET services with cancellation tokens, report progress, and merge uploads into an ASP.NET Core response one input at a time.

Available since 1.3, which is not on NuGet yet.

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

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:

```csharp
// 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](https://www.jadev-corp.com/concepts/resource-limits/).

## 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.Import` from 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. `Merge` and `ExtractPages` return nothing.
- `Split` stops yielding parts; those already returned are yours to dispose.
- `SplitTo` and `SplitToAsync` keep 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.
- `FlattenAnnotations` keeps the pages flattened before the token fired.
- `Save`, `SaveAsync` and `MergeAsync` leave 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

`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:

```csharp
// 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:

```csharp
// 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

`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 |

```csharp
// 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

`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:

```csharp
// 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:

```csharp
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

- Parsing after `OpenAsync` has read the input, `PdfInspector.Inspect` and
  `PdfEquivalence.FindDifference` do not take a token yet; use `PdfLimits.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.
- `MergeAsync` holds a copy of every page's objects until the output is written.

## Related

- [Resource limits and diagnostics](https://www.jadev-corp.com/concepts/resource-limits/)
- [Edit pages](https://www.jadev-corp.com/guides/edit-pages/): merge, split and extract
- [Large files](https://www.jadev-corp.com/guides/large-files/): opening on demand
- API: [PdfProgress](https://www.jadev-corp.com/api/pdfnetstack/pdfprogress/), [PdfMergeOptions](https://www.jadev-corp.com/api/pdfnetstack/pdfmergeoptions/), [PdfDocument](https://www.jadev-corp.com/api/pdfnetstack/pdfdocument/)

## 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.

Source: https://www.jadev-corp.com/pdfnetstack/guides/cancellation-and-progress/
