Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,14 @@ against an empty feed.

## [Unreleased]

Nothing yet.
### Added

- **One call reports the whole picture.** `IPdfDiagnoser.DiagnoseAsync` returns a `PdfDiagnosticsReport` —
the document, its fonts, its signatures, an optional PDF/A pre-flight and the merged, de-duplicated
warnings — assembled from the use cases the library already exposes, so it cannot disagree with them.
The report is read-only and never returns stream contents; a document that stays closed is reported
with `IsReadable`/`RequiresPassword` instead of throwing. `tools/SharpCorePDF.Diagnostics` prints it as
text or JSON, with `--profile` for the archival pre-flight and `--json` for the whole report.

## [1.7.0] - 2026-11-14

Expand Down
10 changes: 8 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,12 @@ await merger.MergeToFileAsync(plan, @"C:\reports\combined.pdf");
select it. A standard font that relies on the one the reader already has is reported as carrying no
program rather than as a defect, and a resource that does not resolve is a `FontUnreadable` warning
beside the fonts that were read. Chapter 26 has the whole answer.
* **One call can describe the whole file.** `IPdfDiagnoser.DiagnoseAsync` returns a
`PdfDiagnosticsReport` — the document, its fonts, its signatures, an optional PDF/A pre-flight and the
merged, de-duplicated warnings — assembled from the same use cases the rest of the library uses, so it
cannot disagree with them. The report is read-only and never returns stream contents; a document that
stays closed is reported with `IsReadable`/`RequiresPassword` instead of throwing. The
`tools/SharpCorePDF.Diagnostics` console prints it as text or JSON.
* **A cover page can be written from nothing and merged in front.** `PdfDocumentBuilder` adds pages of
a chosen size, draws lines of text with one of the twelve standard fonts or a TrueType program you
supply, and places PNG, JPEG, BMP and GIF images at fixed positions — a top-left origin, `y`
Expand Down Expand Up @@ -345,8 +351,8 @@ nuget.org.
| Package | Contents |
| --- | --- |
| [`SharpCorePDF`](https://www.nuget.org/packages/SharpCorePDF) | The one to install. Carries no assembly of its own: its only content is a dependency on the four below, so `dotnet add package SharpCorePDF` is the whole install. |
| [`SharpCorePDF.Domain`](https://www.nuget.org/packages/SharpCorePDF.Domain) | The `MergePlan` aggregate, the `PdfSource` entity, value objects (`PageSelection`, `PageRange`, `PdfMetadata`, `PdfVersion`, `PdfPageSize`, `PageRotation`, `PdfColor`, `StandardFont`, the policies), the read models (document and page info, `PdfReadResult<T>`, image, mask, annotation, destination, form field, widget, bookmark, embedded file, text block, word, glyph, page detail and XMP) and the ports (`IPdfMerger`, `IPdfInspector`, `IPdfContentReader`, `IPdfContentSource`). No I/O, no third-party code. |
| [`SharpCorePDF.Application`](https://www.nuget.org/packages/SharpCorePDF.Application) | The use cases: `PdfMergerService` (validate, open, inspect, resolve selections, hand over to the engine, release every stream), `PdfInspectorService` and `PdfContentReaderService` (resolve the source, open it once, call the engine's page-content port), plus the extension methods callers use (`PdfMergerExtensions`, `PdfContentReaderExtensions`). |
| [`SharpCorePDF.Domain`](https://www.nuget.org/packages/SharpCorePDF.Domain) | The `MergePlan` aggregate, the `PdfSource` entity, value objects (`PageSelection`, `PageRange`, `PdfMetadata`, `PdfVersion`, `PdfPageSize`, `PageRotation`, `PdfColor`, `StandardFont`, the policies), the read models (document and page info, `PdfReadResult<T>`, image, mask, annotation, destination, form field, widget, bookmark, embedded file, text block, word, glyph, page detail and XMP) and the ports (`IPdfMerger`, `IPdfInspector`, `IPdfContentReader`, `IPdfDiagnoser`, `IPdfContentSource`). No I/O, no third-party code. |
| [`SharpCorePDF.Application`](https://www.nuget.org/packages/SharpCorePDF.Application) | The use cases: `PdfMergerService` (validate, open, inspect, resolve selections, hand over to the engine, release every stream), `PdfInspectorService`, `PdfContentReaderService` and `PdfDiagnoserService` (resolve the source, open it once, call the engine's page-content port), plus the extension methods callers use (`PdfMergerExtensions`, `PdfContentReaderExtensions`). |
| [`SharpCorePDF.Infrastructure`](https://www.nuget.org/packages/SharpCorePDF.Infrastructure) | The engine: the object model, the lexer, the object parser, the filter decoders, cross-reference tables, cross-reference streams, object streams, the page tree walk, the object copier, `PdfMergeEngine`, `PdfDocumentReader`, `PdfPageContentReader` (one partial file per capability, with `PdfTextCollector` for the glyphs), the content scanner, the writer, the content sources, and the authoring path (`PdfDocumentBuilder`, `PdfPageCanvas`, `PdfTypeface`, with the TrueType subset writer and the PNG reader). |
| [`SharpCorePDF.DependencyInjection`](https://www.nuget.org/packages/SharpCorePDF.DependencyInjection) | `AddSharpCorePDF()` registration. |

Expand Down
1 change: 1 addition & 0 deletions SharpCorePDF.slnx
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
<Project Path="tests/SharpCorePDF.Tests/SharpCorePDF.Tests.csproj" />
</Folder>
<Folder Name="/tools/">
<Project Path="tools/SharpCorePDF.Diagnostics/SharpCorePDF.Diagnostics.csproj" />
<Project Path="tools/SharpCorePDF.Manual/SharpCorePDF.Manual.csproj" />
<Project Path="tools/SharpCorePDF.Measure/SharpCorePDF.Measure.csproj" />
</Folder>
Expand Down
4 changes: 2 additions & 2 deletions docs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ long-form reference for the API.

## The manual

- **[Read or download the manual as a PDF](SharpCorePDF-Manual-1.7.0.pdf)** — 124 pages, A4, with a
- **[Read or download the manual as a PDF](SharpCorePDF-Manual-1.7.0.pdf)** — 125 pages, A4, with a
linked contents page and PDF bookmarks.
- **Read the chapters as Markdown** in [`manual/src`](manual/src). Each file is one chapter, and the
file-name order is the chapter order. This edition describes `1.7.0`. Chapters 16 to 19 were written
Expand All @@ -31,7 +31,7 @@ long-form reference for the API.
| [5. Page Selection](manual/src/05-page-selection.md) | The one-based selection notation, building selections in code, and preflighting a range. |
| [6. Output Options](manual/src/06-output-options.md) | Target version, primary source, metadata policies and overrides, outlines, page labels and reproducible output. |
| [7. Encryption and Permissions](manual/src/07-encryption-permissions.md) | Algorithms, passwords, permission bits, encrypted sources, and what encryption does to reproducibility. |
| [8. Inspection](manual/src/08-inspection.md) | The document model, what inspection reports, the content reader (images, text, annotations, form, bookmarks, attachments, XMP and the inline budget), encrypted and damaged documents, and preflight. |
| [8. Inspection](manual/src/08-inspection.md) | The document model, what inspection reports, the content reader (images, text, annotations, form, bookmarks, attachments, XMP and the inline budget), encrypted and damaged documents, preflight and the one-call diagnostics report. |
| [9. Errors, Exceptions and Warnings](manual/src/09-error-handling.md) | The exception family, what throws when, writing files safely, and warnings versus errors. |
| [10. Dependency Injection](manual/src/10-dependency-injection.md) | `AddSharpCorePDF`, engine options, configuration binding, logging and testing with the container. |
| [11. Architecture](manual/src/11-architecture.md) | The layers, the life of a merge, immutability, the memory model, extension points and concurrency. |
Expand Down
Binary file modified docs/SharpCorePDF-Manual-1.7.0.pdf
Binary file not shown.
42 changes: 42 additions & 0 deletions docs/manual/src/08-inspection.md
Original file line number Diff line number Diff line change
Expand Up @@ -408,3 +408,45 @@ gives you a place to interject a message, a prompt or a policy decision. It does
safer in the sense of catching every error: a file can change between inspection and merge, and the
merger validates again. The gain is a better conversation with the user, not a substitute for handling
`PdfException` (Chapter 9).

## One-call diagnostics

When the question is not one fact but the whole picture — what is this file, which fonts does it need,
is it signed, would it archive — `IPdfDiagnoser` answers it in one call instead of four:

```csharp
var report = await diagnoser.DiagnoseAsync(
new PdfFileSource("statement.pdf"),
password: null,
archivalProfile: PdfAProfile.PdfA2B);

Console.WriteLine(report.Document.PageCount);
Console.WriteLine(report.Fonts.Count);
Console.WriteLine(report.Signatures.Count);
Console.WriteLine(report.Archival?.IsWritten);

foreach (var warning in report.Warnings)
{
logger.LogWarning("{Kind}: {Message}", warning.Kind, warning.Message);
}
```

The report is assembled from the same use cases the rest of this chapter describes — inspection, the
font inspector (Chapter 26), the signature validator (Chapter 23) and the archival writer's pre-flight
(Chapter 24) — so it cannot disagree with them. It is read-only and redaction-explicit: it names sources
and describes structure, and it never returns stream contents, which is what makes it safe to log or
attach to a support ticket.

`Archival` is `null` unless a profile is named; when it is present, `IsWritten` says whether the writer
would write the document and `UnsatisfiedRequirements` names every reason it would not. A document that
is encrypted and stays closed is reported, not thrown: `Document.IsReadable` and
`Document.RequiresPassword` answer what stands in the way, and the other reads are skipped. `Warnings`
is the merged list, de-duplicated by kind and message, and `HasFindings` is the one-line answer.

The `tools/SharpCorePDF.Diagnostics` console prints the same report as text or JSON, which is what makes
it useful in a support conversation:

```powershell
dotnet run --project .\tools\SharpCorePDF.Diagnostics -- statement.pdf --profile 2b
dotnet run --project .\tools\SharpCorePDF.Diagnostics -- statement.pdf --json
```
29 changes: 29 additions & 0 deletions docs/mutation-testing.md
Original file line number Diff line number Diff line change
Expand Up @@ -751,4 +751,33 @@ What survived, read one by one:
promise an engine that the stream is at its start. A comment beside the branch now says exactly that, so the
survivor is explained in the code rather than only in this record.

## 1.7.0 — the diagnostics service (2026-11-14)

Scoped run over `Services/PdfDiagnoserService.cs` after the one-call report was added:

| File | Score | Killed | Survived | No coverage | Compile errors | Mutants |
| --- | --- | --- | --- | --- | --- | --- |
| `Services/PdfDiagnoserService.cs` | 42.86% | 6 | 8 | 0 | 10 | 24 |

The first run scored 21.43% and named two real gaps, both now closed: no test passed an undefined
`PdfAProfile`, and no test asserted a warning the font read makes but inspection does not
(`FontDescriptorMissing`). `Refuses_an_undefined_profile` and
`Reports_a_font_warning_the_inspection_did_not_make` close them, and `Reads_a_closed_document_once`
counts the source's opens so the early return for a document that stays closed is a behaviour rather
than an optimisation.

What survived, read one by one:

- **The four `ConfigureAwait(false)` arguments** (mutated to `true`): equivalent, for the same reason the
merge and font records state.
- **The `ArgumentOutOfRangeException` message string**: no test asserts a refusal's wording, which is not
a contract.
- **`ArgumentNullException.ThrowIfNull(source)`**: redundant with the guard in each of the four use cases
the diagnoser calls; removing it changes which layer throws, not the exception the caller sees.
- **The two warning-merge statements** (`Add(document.Warnings)` and the archival block): the damaged
fixture reports `CrossReferenceRebuilt` through the font read as well, and the authored archival page
produces no warning of its own, so the current fixtures cannot tell the merge from the omission. A
document with an inspection-only warning and an archival removal is the fixture that would close them,
and it is the next thing to add if this service's suite is extended.


6 changes: 4 additions & 2 deletions specs/005-roadmap-intake/plan.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,10 @@ mutation record. P3 measured the 100 MB read path (`--large` in `tools/SharpCore
`docs/measurements.md` §10), wrote [`docs/adr/0004-buffer-model.md`](../../docs/adr/0004-buffer-model.md) —
which **rejects `System.IO.Pipelines` and the `ReadOnlySequence<byte>` seam for 1.x** — and implemented the
option it recommended: a merge and an edit now read each source once, measured at **2.04× → 1.04×** input on
a 100 MB document with identical output. `P4` (one-call diagnostics) is still waiting for the remainder of the
roadmap text, and `P5` (PDF/A beyond the current claim) for a decision.
a 100 MB document with identical output. `P4` (one-call diagnostics) is implemented in `[Unreleased]`
(2026-11-14): `IPdfDiagnoser`, `PdfDiagnoserService` and the `tools/SharpCorePDF.Diagnostics` console; the
remainder of the roadmap text would only add fields to the report. `P5` (PDF/A beyond the current claim) is
still waiting for a decision.

**Baseline**: this was written against the **working tree**, not the last commit. That tree carries the
pending `[Unreleased]` change (configuration binding without reflection, the AOT smoke app) and three new
Expand Down
3 changes: 3 additions & 0 deletions src/SharpCorePDF.Application/PublicAPI.Unshipped.txt
Original file line number Diff line number Diff line change
@@ -1 +1,4 @@
#nullable enable
SharpCorePDF.Application.Services.PdfDiagnoserService
SharpCorePDF.Application.Services.PdfDiagnoserService.DiagnoseAsync(SharpCorePDF.Domain.Ports.IPdfContentSource! source, string? password = null, SharpCorePDF.Domain.ValueObjects.PdfAProfile? archivalProfile = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<SharpCorePDF.Domain.ReadModels.PdfDiagnosticsReport!>!
SharpCorePDF.Application.Services.PdfDiagnoserService.PdfDiagnoserService(SharpCorePDF.Domain.Ports.IPdfInspector! inspector, SharpCorePDF.Domain.Ports.IPdfFontInspector! fonts, SharpCorePDF.Domain.Ports.IPdfSignatureValidator! signatures, SharpCorePDF.Domain.Ports.IPdfAWriter! archival) -> void
124 changes: 124 additions & 0 deletions src/SharpCorePDF.Application/Services/PdfDiagnoserService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
using SharpCorePDF.Domain.Ports;
using SharpCorePDF.Domain.ReadModels;
using SharpCorePDF.Domain.ValueObjects;

namespace SharpCorePDF.Application.Services;

/// <summary>
/// The use case behind <see cref="IPdfDiagnoser"/>: it asks each existing use case in turn, merges their
/// warnings and returns one report.
/// </summary>
/// <remarks>
/// <para>
/// The report is composed rather than computed: inspection answers the structure, the font inspector the
/// fonts, the signature validator the signatures, and the archival writer — when a profile is named — the
/// requirements the writer would refuse. Because each of those is the one the rest of the library uses,
/// the report cannot drift from the behaviour it describes.
/// </para>
/// <para>
/// A document that stays closed is reported with <see cref="PdfDocumentInfo.IsReadable"/> and
/// <see cref="PdfDocumentInfo.RequiresPassword"/> instead of an exception; the other reads are skipped,
/// because they would fail on the same document. The class is stateless and thread safe.
/// </para>
/// </remarks>
public sealed class PdfDiagnoserService : IPdfDiagnoser
{
private readonly IPdfInspector inspector;
private readonly IPdfFontInspector fonts;
private readonly IPdfSignatureValidator signatures;
private readonly IPdfAWriter archival;

/// <summary>Initializes a new instance of the <see cref="PdfDiagnoserService"/> class.</summary>
/// <param name="inspector">The use case that describes the document.</param>
/// <param name="fonts">The use case that reads the fonts.</param>
/// <param name="signatures">The use case that checks the signatures.</param>
/// <param name="archival">The use case whose pre-flight answers the archival question.</param>
/// <exception cref="ArgumentNullException">An argument is <see langword="null"/>.</exception>
public PdfDiagnoserService(
IPdfInspector inspector,
IPdfFontInspector fonts,
IPdfSignatureValidator signatures,
IPdfAWriter archival)
{
this.inspector = inspector ?? throw new ArgumentNullException(nameof(inspector));
this.fonts = fonts ?? throw new ArgumentNullException(nameof(fonts));
this.signatures = signatures ?? throw new ArgumentNullException(nameof(signatures));
this.archival = archival ?? throw new ArgumentNullException(nameof(archival));
}

/// <inheritdoc />
public async Task<PdfDiagnosticsReport> DiagnoseAsync(
IPdfContentSource source,
string? password = null,
PdfAProfile? archivalProfile = null,
CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(source);

if (archivalProfile is { } profile && !Enum.IsDefined(profile))
{
throw new ArgumentOutOfRangeException(
nameof(archivalProfile),
archivalProfile,
"The PDF/A profile is not one the engine writes.");
}

var document = await inspector
.InspectAsync(source, password, cancellationToken)
.ConfigureAwait(false);

// The other reads would throw on a document that stays closed. The inspector has already said
// what stands in the way, so the answer is returned instead of an exception.
if (!document.IsReadable)
{
return new PdfDiagnosticsReport
{
Document = document,
Warnings = [.. document.Warnings],
};
}

var fontResult = await fonts
.ReadFontsAsync(source, password, cancellationToken)
.ConfigureAwait(false);

var signatureResult = await signatures
.ValidateAsync(source, trust: null, password, cancellationToken)
.ConfigureAwait(false);

PdfAConversionResult? archivalResult = null;

if (archivalProfile is { } archivalProfileValue)
{
// The writer's own pre-flight, with a destination that discards: a report is read-only, and
// the result says what would be refused without a document being kept.
archivalResult = await archival
.ConvertAsync(source, Stream.Null, archivalProfileValue, options: null, password, cancellationToken)
.ConfigureAwait(false);
}

var warnings = new List<PdfWarning>();
Add(warnings, document.Warnings);
Add(warnings, fontResult.Warnings);

if (archivalResult is { } archivalWarnings)
{
Add(warnings, archivalWarnings.Warnings);
}

return new PdfDiagnosticsReport
{
Document = document,
Fonts = fontResult.Items,
Signatures = signatureResult,
Archival = archivalResult,
Warnings = warnings,
};
}

/// <summary>Adds the warnings that are not already in the report, in the order they arrive.</summary>
/// <param name="destination">The merged list.</param>
/// <param name="warnings">The warnings of one sub-read.</param>
private static void Add(List<PdfWarning> destination, IEnumerable<PdfWarning> warnings) =>
destination.AddRange(warnings.Where(warning => !destination.Contains(warning)));
}
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,7 @@ private static IServiceCollection AddSharpCorePDFCore(this IServiceCollection se
services.TryAddSingleton<IPdfSigner, PdfSignerService>();
services.TryAddSingleton<IPdfSignatureValidator, PdfSignatureValidatorService>();
services.TryAddSingleton<IPdfAWriter, PdfAWriterService>();
services.TryAddSingleton<IPdfDiagnoser, PdfDiagnoserService>();

return services;
}
Expand Down
Loading
Loading