diff --git a/CHANGELOG.md b/CHANGELOG.md index 9600da9..d15500d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,7 +20,18 @@ against an empty feed. ## [Unreleased] -Nothing yet. +### Added + +- **Stationery: a background template per page range, with a default.** `PdfStationery` maps a template + to a `PageRange` and can name a default for the pages no assignment covers (`Assign`, + `AssignDefault`, `AssignNone`), and `PdfEditPlan.ApplyStationery(...)` records the whole plan as one + operation. The template is recorded as the underlay layer the editor already writes — a form + XObject — so the page's own content streams keep their bytes, vector graphics and selectable text + survive, and nothing is rasterized. Assignments are tried last first, a one-page template repeats + across its range, a multi-page template maps one page for one page, and a range that reaches past it + is refused. `PDF/A-1b` refuses a translucent or blended stationery. The manual's chapter 14 has the + section and `PdfDocumentEditorTests.Stationery*` has the tests, including one per acceptance + criterion of #6. ## [1.6.0] - 2026-11-14 diff --git a/docs/manual/src/14-editing.md b/docs/manual/src/14-editing.md index 43bcd00..13f9bb8 100644 --- a/docs/manual/src/14-editing.md +++ b/docs/manual/src/14-editing.md @@ -121,6 +121,31 @@ page, and `DuplicatePage` makes both copies draw the same form. layer with an opacity below `1` or a blend mode other than `Normal` rather than writing the layer opaque without saying so. The validation happens when the plan is checked, before the source is read. +### Stationery + +Stationery is the same layer applied by plan rather than one page at a time: a letterhead behind the +first page, a footer behind the rest, and a default template for everything else. `PdfStationery` +describes that mapping, and `ApplyStationery` records it in the edit plan: + +```csharp +var stationery = PdfStationery.Create() + .Assign(new PdfFileSource("letterhead.pdf"), PageRange.Single(1)) + .Assign(new PdfFileSource("footer.pdf"), PageRange.FromPage(2)) + .AssignDefault(new PdfFileSource("plain.pdf")); + +var plan = PdfEditPlan.Create().ApplyStationery(stationery); +``` + +Assignments are tried last first, so a later, narrower assignment overrides an earlier, broader one. A +page no assignment covers receives the default; `AssignNone(range)` leaves a range bare even when a +default exists. A one-page template repeats across the pages it covers, while a multi-page template +maps one page for one page, starting at the first page of the assignment; a range that reaches past the +template's last page is refused when the plan runs. + +`ApplyStationery` adds one operation, and its pages are resolved against the document state the +preceding operations leave behind: add it last when the background should cover the whole result. It is +an underlay, so it obeys the same placement, opacity, blend and `PDF/A-1b` rules as `Underlay`. + ## Document-level edits Four operations state a value of the document rather than of a page. Each replaces what the source diff --git a/docs/parity.md b/docs/parity.md index 384b933..9ed1dc4 100644 --- a/docs/parity.md +++ b/docs/parity.md @@ -29,7 +29,7 @@ No “Must” row is unowned. The owner is the story that closes it: `US1 creato | 3 | Text measurement, wrapping, alignment, leading, basic layout | PDFsharp: basic text layout. PdfPig: not a layout engine. | Must: typeface metrics, single-line and multi-line drawing, greedy wrapping, leading and horizontal/vertical alignment. | 1.2 | US1 creator | `PdfDocumentBuilderTests.Reports_the_metrics_of_a_standard_font`, `.Measures_a_standard_font_line_with_the_afm_widths`, `.Measures_an_embedded_face_with_its_own_metrics`, `.Wraps_a_paragraph_greedily_to_the_width`, `.Places_a_line_at_the_alignment_it_was_given`, `.Stretches_the_lines_of_a_justified_paragraph`, `.Steps_the_baselines_by_the_line_height`, `.Breaks_a_word_into_pieces_that_fit`, `.Refuses_a_word_that_cannot_fit`, `.Draws_the_layout_from_the_top_left_of_its_box` (twenty-two tests in `tests/SharpCorePDF.Tests/PdfDocumentBuilderTests.TextLayout.cs`) | `uv run --with fontTools python -c "from fontTools.ttLib import TTFont; ..."` reads the embedded face's `unitsPerEm`, `ascent`, `descent` and the 8001-unit advance of `Veuillez`, which is what the layout tests assert; a PyMuPDF read of a probe page shows every span one ascent below the origin it was drawn at, stepping by the 15-point leading and centred on the box; `validate-pdf.py` reports `qpdf check: no problems` | Evidenced (2026-10-23) — standard and embedded metrics, `PdfTypeface.Measure`, greedy wrapping, left/center/right/justify, leading, the four overflow policies and the `DrawTextLayout` round-trip; alignment is horizontal only, because no API in the row asks for a vertical one; documented in manual chapter 16 (`docs/manual/src/16-text-layout.md`) | | 4 | PNG, JPEG, BMP and GIF images | PDFsharp: PNG, JPEG, BMP, GIF. PdfPig: image extraction, basic creation. | Must: PNG alpha/palette/16-bit policy, JPEG pass-through with EXIF/CMYK transform, BMP and first-frame GIF, explicit refusal by name. | 1.1 PNG, the rest 1.2 | US1 creator | `PdfDocumentBuilderTests.Writes_an_rgba_png_with_a_soft_mask`, `Writes_an_rgb_png_with_a_colour_key`, `Writes_a_palette_png_with_transparency`, `Writes_a_greyscale_png_with_alpha`, `Uses_the_resolution_of_a_png_for_its_natural_size`, `Writes_one_image_object_for_a_logo_used_on_two_pages`, `Refuses_an_interlaced_png`, `Refuses_a_sixteen_bit_png`, `Writes_a_jpeg_without_re_encoding_it`, `Writes_a_cmyk_jpeg_with_the_flip_pdf_needs`, `Writes_a_greyscale_jpeg_as_one_component_image`, `Uses_the_jfif_density_of_a_jpeg_for_its_natural_size`, `Writes_a_bmp_with_its_rows_in_order`, `Turns_a_top_down_bmp_the_same_way_up`, `Reads_a_thirty_two_bit_bmp_as_opaque_colour`, `Expands_the_palette_of_a_bmp_to_rgb`, `Writes_a_gif_and_expands_its_palette`, `Puts_an_interlaced_gif_back_into_row_order`, `Turns_the_transparency_of_a_gif_into_a_soft_mask`, `Draws_only_the_first_frame_of_an_animation`, `Embeds_one_image_object_for_a_file_drawn_twice`, `Declares_the_icc_profile_a_png_states`, `Reads_the_profile_out_of_the_icc_chunk`, `Reads_a_grey_profile_as_one_component`, `Refuses_a_profile_that_does_not_describe_the_samples`, `Refuses_an_icc_chunk_that_is_not_a_profile` (T024, T032) | `uv run --with pikepdf python docs/tools/validate-pdf.py ` and PyMuPDF image placement; `python docs/tools/verify-creator.py` runs the `creator-parity` example and checks the profile it wrote against the PNG it drew, byte for byte, along with the tree, the packet, both images and a render (`measurements.md` §13) | Evidenced (2026-10-23) — the PNG matrix, `/SMask`, `pHYs`, JPEG pass-through with the CMYK `/Decode` flip, BMP row order and palette expansion, the GIF first frame with its transparency and interlacing, and the by-name refusal of every variant a reader does not read are covered by the tests above; the ICC policy is decided and implemented: an `iCCP` profile is written as an `/ICCBased` colour space with `/N` and `/Alternate`, the 3144-byte sRGB profile of `creator-parity.pdf` reads back byte for byte under pikepdf 10.17.0, PyMuPDF reports the image as `ICCBased`, and a profile that does not describe the samples is refused by name | | 5 | Page import, insert, delete, reorder, rotate, crop, resize, split, extract, append | PDFsharp: all operations. PdfPig: merge only. | Must: immutable plan, one-based page references, materialised inherited geometry, no source mutation. | 1.1 operations, external run in 1.2 (completed 2026-11-06, Unreleased) | US2 editing | `PdfDocumentEditorTests.Reorders_deletes_and_duplicates_pages`, `.Adds_rotations_to_the_rotation_a_page_already_has`, `.Geometry.Crop_is_clamped_to_the_media_box_and_reported`, `.Composition.Imports_a_page_of_another_document`, `.Composition.Appends_every_page_of_another_document`, `.Composition.Splits_the_document_into_parts_of_the_requested_size` | `python docs/tools/validate-pdf.py ` on a page moved and rotated by the editor (`qpdf check: no problems`, 2 pages, page 1 `rotate=90` and page 2 `rotate=0`), and pypdf reading the same file back: two pages, page 1 text `Page two` at `/Rotate 90`, page 2 text `Page one` — order and geometry confirmed by an independent implementation (T058, run 2026-11-06) | Evidenced (2026-11-06) — every listed operation is implemented and covered by `PdfDocumentEditorTests`, `.Composition` and `.Geometry`, and the external run T058 named is recorded: qpdf raises no problems on the edited file and pypdf reads back the moved page order and the added rotation | -| 6 | Overlay, underlay, watermark, stamp | PDFsharp: yes. PdfPig: no. | Must: wrap original content in `q`/`Q`, record overlay/underlay in the requested layer with clipping and constant alpha. | 1.2 | US2 editing | `PdfDocumentEditorTests.Draws_an_overlay_page_over_the_page_it_is_applied_to`, `Draws_an_underlay_page_before_the_page_it_is_applied_to`, `Writes_the_opacity_and_blend_mode_of_a_layer_through_a_graphics_state`, `Keeps_the_layer_on_the_page_it_was_applied_to` (T040) | `uv run --with pikepdf python docs/tools/validate-pdf.py ` and a PyMuPDF visual comparison | Met in 1.2 for the structures: a layer is a form XObject drawn from a stream of the page's own — an overlay appends that stream, an underlay prepends it, the original streams stay untouched between them inside a `q`/`Q` frame, which is also what keeps a transform a page states outside a `q` from reaching the layer, the visible area clips the layer and `ca`/`CA`/`BM` in an `ExtGState` carry the opacity and the blend mode (2026-10-24). The external `validate-pdf.py` run on the `watermark` example's output (pikepdf / qpdf, PDF 1.7, 2 pages, 6 streams decoded, `qpdf check: no problems`) confirms an independent implementation accepts the layer, and the text reader returns the stamp as text of the pages it was placed on; the PyMuPDF visual comparison has not been made | +| 6 | Overlay, underlay, watermark, stamp | PDFsharp: yes. PdfPig: no. | Must: wrap original content in `q`/`Q`, record overlay/underlay in the requested layer with clipping and constant alpha. | 1.2 | US2 editing | `PdfDocumentEditorTests.Draws_an_overlay_page_over_the_page_it_is_applied_to`, `Draws_an_underlay_page_before_the_page_it_is_applied_to`, `Writes_the_opacity_and_blend_mode_of_a_layer_through_a_graphics_state`, `Keeps_the_layer_on_the_page_it_was_applied_to` (T040) | `uv run --with pikepdf python docs/tools/validate-pdf.py ` and a PyMuPDF visual comparison | Met in 1.2 for the structures: a layer is a form XObject drawn from a stream of the page's own — an overlay appends that stream, an underlay prepends it, the original streams stay untouched between them inside a `q`/`Q` frame, which is also what keeps a transform a page states outside a `q` from reaching the layer, the visible area clips the layer and `ca`/`CA`/`BM` in an `ExtGState` carry the opacity and the blend mode (2026-10-24). The external `validate-pdf.py` run on the `watermark` example's output (pikepdf / qpdf, PDF 1.7, 2 pages, 6 streams decoded, `qpdf check: no problems`) confirms an independent implementation accepts the layer, and the text reader returns the stamp as text of the pages it was placed on; the PyMuPDF visual comparison has not been made. A stationery plan now maps templates to page ranges and to a default, expanding to the same underlay layers (`PdfStationery`, `PdfEditPlan.ApplyStationery`, 2026-11-14) | | 7 | Metadata, XMP, outlines, destinations, page labels, viewer preferences | PDFsharp: yes. PdfPig: reads metadata and bookmarks. | Must: edit information dictionary and XMP, write outlines/destinations/page labels/viewer preferences; removed destinations warn. | 1.1 metadata, the rest 1.2 | US2 editing | `PdfDocumentEditorTests.Overrides_the_metadata_it_sets_and_preserves_the_rest`, `Drops_xmp_when_metadata_overrides_the_information_dictionary`, `Keeps_xmp_when_metadata_is_not_overridden`, `Replaces_the_xmp_packet_it_is_given`, `Writes_the_bookmarks_it_is_given`, `Removes_the_outline_of_the_source_when_it_is_empty`, `Writes_the_page_labels_it_is_given`, `Writes_the_viewer_preferences_it_is_given` (T041); XMP authoring and outlines are `PdfDocumentBuilderTests.Carries_the_xmp_packet_it_was_given`, `.Writes_the_outline_it_was_given` (T034) | `uv run --with pikepdf python docs/tools/validate-pdf.py `; pypdf reads metadata and outline | Met in 1.2 for the writes: `SetMetadata`, `SetXmp`, `SetOutline`, `SetPageLabels` and `SetViewerPreferences` each replace what the source carried, a stated outline or label range that names a page the result does not have is refused, and `PdfOutline.Empty` / `PdfPageLabeling.None` remove rather than drop (2026-10-24). A bookmark of a page that a later operation deletes is still redirected to the first surviving page with a warning | | 8 | AcroForm creation, filling, flattening and appearance generation | PDFsharp: yes. PdfPig: read-only forms. | Must: text, checkbox, radio, choice and push-button fields; unique qualified names; fill, reset, read-only refusal and flatten with generated appearances. | 1.2 | US2 editing | `PdfFormEditorTests.Fills_and_reads_back_form_values`, `Fills_a_field_the_document_already_carries`, `Refuses_a_read_only_field`, `Refuses_an_unsupported_field_type`, `Flattens_a_form_without_a_form_viewer`, `Resets_the_form_to_its_default_values`, `Removes_the_xfa_form_and_says_so` (T044, T055) | `python docs/tools/validate-pdf.py` on the three files the `fill-form` example writes (`form-created.pdf`, `form-filled.pdf`, `form-flattened.pdf`): `qpdf check: no problems` for all three, page 1 carrying five annotations and a 62-byte content stream before the flatten and none with 226 bytes after it; a pypdf read-back of the same three (`person.name = Grace Hopper`, `agree = /Off`, `country = BE`, and no field at all on the flattened file); and a PyMuPDF render of the flattened page that reads `Grace Hopper` as page text (T056) | Met in 1.2 (2026-10-24): the five kinds are written with unique qualified names, a field the document already carries is filled in place — its rectangle, ancestors and widgets survive — and a name it does not carry becomes a new field of the tree the name spells; `ResetForm` restores `/DV`, `FlattenForm` draws each widget into the page content and drops the field, `/NeedAppearances` is written `false` because every widget carries the appearance the engine drew, and a read-only field, a signature field and a name that would split an existing one are refused with the name they name; an XFA packet is removed with `XfaFormRemoved` and an action on a field is copied inert with `FormFieldActionPreserved` | | 9 | Annotation creation, editing, removal and appearance streams | PDFsharp: broad annotation model. PdfPig: read-only annotations. | Must: link, text, free text, stamp, highlight, underline, strikeout, square, circle, line and ink; update/remove; appearance for every creatable kind. | 1.2 | US2 editing | `PdfAnnotationTests.Adds_a_highlight_and_reads_it_back_with_an_appearance`, `Adds_links_to_a_url_and_to_a_page`, `Updates_one_annotation_and_removes_another`, `Keeps_the_annotation_a_page_already_carried`, `Carries_an_annotation_into_a_duplicate_of_its_page`, `Writes_an_appearance_for_every_kind_that_draws_something`, `Draws_the_text_of_a_free_text_annotation_into_its_appearance`, `Drops_a_link_whose_destination_the_edit_removes`, `Clips_an_annotation_to_the_page_and_reports_it`, `Refuses_an_update_of_an_annotation_the_page_does_not_carry`, `Refuses_a_link_with_both_a_page_and_a_url`, `Refuses_a_translucent_annotation_for_pdfa_1b` (T043) | `python docs/tools/validate-pdf.py annotated.pdf` from the `annotate` example (pikepdf 10.17.0 / qpdf: `qpdf check: no problems`, PDF 1.7, 2 pages, 20 objects, page 1 `annots=6`, 6 streams decoded, 0 failed) and a PyMuPDF 2.0 render of the same file, which reports six annotations and paints the highlight quad (255, 223, 129) for `#FFE082`, the note icon (255, 211, 0), the free text in `#1F3A5F` and the stamp frame (191, 43, 31) | Met in 1.2 (2026-10-24): the ten kinds the row lists are written by `PdfAnnotations`, each with an appearance stream the engine draws unless the caller supplies one; `AddAnnotation`, `UpdateAnnotation` and `RemoveAnnotation` rebuild the page's `/Annots` without touching its content, a page the plan does not name keeps its objects, an annotation that states no identifier is named `scpdf-N`, and every refusal the contract states — unknown kind, link with both a page and a URL, missing identifier, empty geometry, opacity outside 0-1, translucency under PDF/A-1b — is made before a byte is written | diff --git a/examples/SharpCorePDF.Examples/PdfEditExamples.cs b/examples/SharpCorePDF.Examples/PdfEditExamples.cs index 06f937a..3eb329c 100644 --- a/examples/SharpCorePDF.Examples/PdfEditExamples.cs +++ b/examples/SharpCorePDF.Examples/PdfEditExamples.cs @@ -189,6 +189,68 @@ public static async Task WatermarkAsync(ExampleContext context, CancellationToke } } + /// + /// Puts a letterhead behind the first page and a footer behind the rest: stationery is a layer per + /// page range, with a default for the pages no assignment covers. + /// + /// The document to dress and the ports to edit it with. + /// A token to cancel the work. + public static async Task StationeryAsync(ExampleContext context, CancellationToken cancellationToken) + { + var heading = PdfTypeface.Standard(StandardFont.HelveticaBold); + var output = context.OutputPath("stationery.pdf"); + + // A letterhead and a footer are documents of their own, like the watermark above: the library + // draws each once and records it under every page the stationery plan assigns to it. + var letterhead = PdfDocumentBuilder.Create() + .AddPage(PdfPageSize.A4, page => page + .DrawText("Northwind Traders", 72, 780, heading, 22) + .DrawLine( + new PdfPoint(72, 772), + new PdfPoint(523, 772), + new PdfStroke(PdfPaint.Black, width: 0.75))) + .Build("letterhead.pdf"); + + var footer = PdfDocumentBuilder.Create() + .AddPage(PdfPageSize.A4, page => page + .DrawLine( + new PdfPoint(72, 60), + new PdfPoint(523, 60), + new PdfStroke(PdfPaint.Black, width: 0.5)) + .DrawText("Confidential", 72, 44, heading, 9)) + .Build("footer.pdf"); + + // One assignment per page range, plus a default for the pages neither names. Assignments are + // tried last first, so a narrower range overrides a broader one. + var stationery = PdfStationery.Create() + .Assign(letterhead, PageRange.Single(1)) + .AssignDefault(footer); + + var plan = PdfEditPlan.Create() + .ApplyStationery(stationery) + .WithOutput(options => options with + { + ModificationDate = new DateTimeOffset(2026, 1, 1, 0, 0, 0, TimeSpan.Zero), + Producer = "SharpCorePDF examples", + }); + + PdfEditResult result; + + await using (var destination = File.Create(output)) + { + result = await context.Editor.ApplyAsync( + new PdfFileSource(context.Appendix), + plan, + destination, + cancellationToken: cancellationToken); + } + + Report.Item("wrote", output); + Report.Item("operations applied", string.Join(", ", result.Operations)); + Report.Item("bytes", result.BytesWritten); + } + + /// Comments on the document without touching a byte of its content. /// The document to comment on and the ports to comment with. /// A token to cancel the work. diff --git a/examples/SharpCorePDF.Examples/Scenarios.cs b/examples/SharpCorePDF.Examples/Scenarios.cs index 36ae79e..6308925 100644 --- a/examples/SharpCorePDF.Examples/Scenarios.cs +++ b/examples/SharpCorePDF.Examples/Scenarios.cs @@ -20,6 +20,7 @@ internal static class Scenarios new("draw-shapes", "draw lines, paths, a clipping region and a transformed group on a page that did not exist", DrawingExamples.DrawShapesAsync), new("edit-pages", "edit a document that exists: insert, rotate, delete and crop in one pass", PdfEditExamples.EditPagesAsync), new("watermark", "stamp a watermark written from nothing over every page of a document", PdfEditExamples.WatermarkAsync), + new("stationery", "put a letterhead behind the first page and a footer behind the rest", PdfEditExamples.StationeryAsync), new("annotate", "comment on a document without touching its content: highlights, notes, a stamp and links", PdfEditExamples.AnnotateAsync), new("fill-form", "write a form, fill it by name, and flatten it so a reader without forms still shows the values", PdfEditExamples.FillFormAsync), new("no-container", "use the packages without a dependency injection container", SourceExamples.WithoutContainerAsync), diff --git a/src/SharpCorePDF.Domain/Aggregates/PdfEditPlan.cs b/src/SharpCorePDF.Domain/Aggregates/PdfEditPlan.cs index b741d2c..669b33e 100644 --- a/src/SharpCorePDF.Domain/Aggregates/PdfEditPlan.cs +++ b/src/SharpCorePDF.Domain/Aggregates/PdfEditPlan.cs @@ -262,6 +262,24 @@ public PdfEditPlan Underlay( string? password = null) => AddOverlay(underlay, pageNumber, options, PdfOverlayLayer.Under, password); + /// + /// Records stationery templates under the pages of this document: one template per assigned page + /// range, plus a default for the pages no assignment covers. + /// + /// The templates and the pages they cover. + /// The new plan. + /// is . + /// + /// The pages are resolved against the document state the preceding operations leave behind, so a + /// caller who wants a background under the whole result adds this operation last. A one-page + /// template repeats across the pages it covers; a multi-page template maps one page for one page. + /// + public PdfEditPlan ApplyStationery(PdfStationery stationery) + { + ArgumentNullException.ThrowIfNull(stationery); + return Add(new PdfStationeryOperation(stationery)); + } + /// Replaces the XMP metadata packet of the document. /// The packet as UTF-8 XML; it must be well formed. /// The new plan. @@ -440,6 +458,13 @@ public IReadOnlyList Validate() $"operation {index}: a layer with an opacity below 1 or a blend mode other than Normal cannot be written for PDF/A-1b, which has no transparency."); } + if (operations[index] is PdfStationeryOperation { Stationery: { } stationery } + && UsesTransparency(stationery)) + { + errors.Add( + $"operation {index}: a stationery layer with an opacity below 1 or a blend mode other than Normal cannot be written for PDF/A-1b, which has no transparency."); + } + if (operations[index] is PdfAddAnnotationOperation { Annotation.Opacity: < 1d } || operations[index] is PdfUpdateAnnotationOperation { Annotation.Opacity: < 1d }) { @@ -748,6 +773,18 @@ private static IEnumerable ValidateOperation(PdfEditOperation operation, break; + case PdfStationeryOperation stationery when stationery.Stationery is null: + yield return $"operation {index}: the stationery to apply is null."; + break; + + case PdfStationeryOperation stationery: + foreach (var problem in stationery.Stationery.Validate()) + { + yield return $"operation {index}: {problem}"; + } + + break; + case PdfSetXmpOperation xmp: if (xmp.Xmp.IsEmpty) { @@ -911,4 +948,26 @@ private static IEnumerable ValidateRange(PageRange pages, int index) yield return $"operation {index}: page range '{pages}' ends before it starts."; } } + + /// Determines whether a stationery layer states a transparency the PDF/A-1b profile forbids. + /// The stationery to check. + /// when a template is translucent or blended. + private static bool UsesTransparency(PdfStationery stationery) + { + foreach (var assignment in stationery.Assignments) + { + if (assignment.Options is null || StatesTransparency(assignment.Options)) + { + return true; + } + } + + return stationery.Default?.Options is null || StatesTransparency(stationery.Default.Options); + } + + /// Determines whether one set of overlay options states a transparency. + /// The options to check. + /// when the opacity is below 1 or the blend mode is not normal. + private static bool StatesTransparency(PdfOverlayOptions options) => + options.Opacity < 1d || options.BlendMode != PdfOverlayBlendMode.Normal; } diff --git a/src/SharpCorePDF.Domain/PublicAPI.Unshipped.txt b/src/SharpCorePDF.Domain/PublicAPI.Unshipped.txt index 7dc5c58..f6c36c5 100644 --- a/src/SharpCorePDF.Domain/PublicAPI.Unshipped.txt +++ b/src/SharpCorePDF.Domain/PublicAPI.Unshipped.txt @@ -1 +1,53 @@ #nullable enable +override sealed SharpCorePDF.Domain.ValueObjects.PdfStationeryOperation.Equals(SharpCorePDF.Domain.ValueObjects.PdfEditOperation? other) -> bool +override SharpCorePDF.Domain.ValueObjects.PdfStationery.Equals(object? obj) -> bool +override SharpCorePDF.Domain.ValueObjects.PdfStationery.GetHashCode() -> int +override SharpCorePDF.Domain.ValueObjects.PdfStationery.ToString() -> string! +override SharpCorePDF.Domain.ValueObjects.PdfStationeryAssignment.Equals(object? obj) -> bool +override SharpCorePDF.Domain.ValueObjects.PdfStationeryAssignment.GetHashCode() -> int +override SharpCorePDF.Domain.ValueObjects.PdfStationeryAssignment.ToString() -> string! +override SharpCorePDF.Domain.ValueObjects.PdfStationeryOperation.$() -> SharpCorePDF.Domain.ValueObjects.PdfStationeryOperation! +override SharpCorePDF.Domain.ValueObjects.PdfStationeryOperation.Equals(object? obj) -> bool +override SharpCorePDF.Domain.ValueObjects.PdfStationeryOperation.GetHashCode() -> int +override SharpCorePDF.Domain.ValueObjects.PdfStationeryOperation.Kind.get -> SharpCorePDF.Domain.ValueObjects.PdfEditOperationKind +override SharpCorePDF.Domain.ValueObjects.PdfStationeryOperation.ToString() -> string! +SharpCorePDF.Domain.Aggregates.PdfEditPlan.ApplyStationery(SharpCorePDF.Domain.ValueObjects.PdfStationery! stationery) -> SharpCorePDF.Domain.Aggregates.PdfEditPlan! +SharpCorePDF.Domain.ValueObjects.PdfEditOperationKind.ApplyStationery = 25 -> SharpCorePDF.Domain.ValueObjects.PdfEditOperationKind +SharpCorePDF.Domain.ValueObjects.PdfStationery +SharpCorePDF.Domain.ValueObjects.PdfStationery.$() -> SharpCorePDF.Domain.ValueObjects.PdfStationery! +SharpCorePDF.Domain.ValueObjects.PdfStationery.Assign(SharpCorePDF.Domain.Ports.IPdfContentSource! source, SharpCorePDF.Domain.ValueObjects.PageRange pages, SharpCorePDF.Domain.ValueObjects.PdfOverlayOptions? options = null, string? password = null) -> SharpCorePDF.Domain.ValueObjects.PdfStationery! +SharpCorePDF.Domain.ValueObjects.PdfStationery.AssignDefault(SharpCorePDF.Domain.Ports.IPdfContentSource! source, SharpCorePDF.Domain.ValueObjects.PdfOverlayOptions? options = null, string? password = null) -> SharpCorePDF.Domain.ValueObjects.PdfStationery! +SharpCorePDF.Domain.ValueObjects.PdfStationery.Assignments.get -> System.Collections.Immutable.ImmutableArray +SharpCorePDF.Domain.ValueObjects.PdfStationery.Assignments.init -> void +SharpCorePDF.Domain.ValueObjects.PdfStationery.AssignNone(SharpCorePDF.Domain.ValueObjects.PageRange pages) -> SharpCorePDF.Domain.ValueObjects.PdfStationery! +SharpCorePDF.Domain.ValueObjects.PdfStationery.Default.get -> SharpCorePDF.Domain.ValueObjects.PdfStationeryAssignment? +SharpCorePDF.Domain.ValueObjects.PdfStationery.Default.init -> void +SharpCorePDF.Domain.ValueObjects.PdfStationery.Equals(SharpCorePDF.Domain.ValueObjects.PdfStationery? other) -> bool +SharpCorePDF.Domain.ValueObjects.PdfStationery.PdfStationery() -> void +SharpCorePDF.Domain.ValueObjects.PdfStationery.ResolveForPage(int pageNumber) -> SharpCorePDF.Domain.ValueObjects.PdfStationeryAssignment? +SharpCorePDF.Domain.ValueObjects.PdfStationery.Validate() -> System.Collections.Generic.IReadOnlyList! +SharpCorePDF.Domain.ValueObjects.PdfStationeryAssignment +SharpCorePDF.Domain.ValueObjects.PdfStationeryAssignment.$() -> SharpCorePDF.Domain.ValueObjects.PdfStationeryAssignment! +SharpCorePDF.Domain.ValueObjects.PdfStationeryAssignment.Equals(SharpCorePDF.Domain.ValueObjects.PdfStationeryAssignment? other) -> bool +SharpCorePDF.Domain.ValueObjects.PdfStationeryAssignment.Options.get -> SharpCorePDF.Domain.ValueObjects.PdfOverlayOptions! +SharpCorePDF.Domain.ValueObjects.PdfStationeryAssignment.Options.init -> void +SharpCorePDF.Domain.ValueObjects.PdfStationeryAssignment.Pages.get -> SharpCorePDF.Domain.ValueObjects.PageRange +SharpCorePDF.Domain.ValueObjects.PdfStationeryAssignment.Pages.init -> void +SharpCorePDF.Domain.ValueObjects.PdfStationeryAssignment.Password.get -> string? +SharpCorePDF.Domain.ValueObjects.PdfStationeryAssignment.Password.init -> void +SharpCorePDF.Domain.ValueObjects.PdfStationeryAssignment.PdfStationeryAssignment() -> void +SharpCorePDF.Domain.ValueObjects.PdfStationeryAssignment.Source.get -> SharpCorePDF.Domain.Ports.IPdfContentSource? +SharpCorePDF.Domain.ValueObjects.PdfStationeryAssignment.Source.init -> void +SharpCorePDF.Domain.ValueObjects.PdfStationeryOperation +SharpCorePDF.Domain.ValueObjects.PdfStationeryOperation.Deconstruct(out SharpCorePDF.Domain.ValueObjects.PdfStationery! Stationery) -> void +SharpCorePDF.Domain.ValueObjects.PdfStationeryOperation.Equals(SharpCorePDF.Domain.ValueObjects.PdfStationeryOperation? other) -> bool +SharpCorePDF.Domain.ValueObjects.PdfStationeryOperation.PdfStationeryOperation(SharpCorePDF.Domain.ValueObjects.PdfStationery! Stationery) -> void +SharpCorePDF.Domain.ValueObjects.PdfStationeryOperation.Stationery.get -> SharpCorePDF.Domain.ValueObjects.PdfStationery! +SharpCorePDF.Domain.ValueObjects.PdfStationeryOperation.Stationery.init -> void +static SharpCorePDF.Domain.ValueObjects.PdfStationery.Create() -> SharpCorePDF.Domain.ValueObjects.PdfStationery! +static SharpCorePDF.Domain.ValueObjects.PdfStationery.operator !=(SharpCorePDF.Domain.ValueObjects.PdfStationery? left, SharpCorePDF.Domain.ValueObjects.PdfStationery? right) -> bool +static SharpCorePDF.Domain.ValueObjects.PdfStationery.operator ==(SharpCorePDF.Domain.ValueObjects.PdfStationery? left, SharpCorePDF.Domain.ValueObjects.PdfStationery? right) -> bool +static SharpCorePDF.Domain.ValueObjects.PdfStationeryAssignment.operator !=(SharpCorePDF.Domain.ValueObjects.PdfStationeryAssignment? left, SharpCorePDF.Domain.ValueObjects.PdfStationeryAssignment? right) -> bool +static SharpCorePDF.Domain.ValueObjects.PdfStationeryAssignment.operator ==(SharpCorePDF.Domain.ValueObjects.PdfStationeryAssignment? left, SharpCorePDF.Domain.ValueObjects.PdfStationeryAssignment? right) -> bool +static SharpCorePDF.Domain.ValueObjects.PdfStationeryOperation.operator !=(SharpCorePDF.Domain.ValueObjects.PdfStationeryOperation? left, SharpCorePDF.Domain.ValueObjects.PdfStationeryOperation? right) -> bool +static SharpCorePDF.Domain.ValueObjects.PdfStationeryOperation.operator ==(SharpCorePDF.Domain.ValueObjects.PdfStationeryOperation? left, SharpCorePDF.Domain.ValueObjects.PdfStationeryOperation? right) -> bool diff --git a/src/SharpCorePDF.Domain/ValueObjects/PdfEditOperation.cs b/src/SharpCorePDF.Domain/ValueObjects/PdfEditOperation.cs index 2efeb84..4950ac5 100644 --- a/src/SharpCorePDF.Domain/ValueObjects/PdfEditOperation.cs +++ b/src/SharpCorePDF.Domain/ValueObjects/PdfEditOperation.cs @@ -79,6 +79,9 @@ public enum PdfEditOperationKind /// The form is drawn into the pages and removed, so the document keeps no form. FlattenForm, + + /// Stationery templates are recorded under the pages of the document. + ApplyStationery, } /// Determines whether a page of another document is recorded under or over a page of this one. @@ -330,6 +333,36 @@ public override string ToString() => string.Create( $"record '{Overlay?.DisplayName}' {(Layer == PdfOverlayLayer.Under ? "under" : "over")} page {PageNumber} at opacity {Options?.Opacity ?? 1.0:0.##}"); } +/// +/// Records stationery templates under the pages of the document, each covering the pages it names and +/// a default covering the rest. +/// +/// The templates and the pages they cover. +/// +/// +/// The templates are recorded as underlay layers, exactly like with a +/// layer of , so the content streams of every page keep their bytes +/// and the resources of a template never collide with the resources of the page. +/// +/// +/// The operation resolves its pages against the document state the preceding operations leave behind, +/// which means it applies to the pages that exist at its position in the plan. A caller who wants a +/// background under the whole result adds it last. +/// +/// +public sealed record PdfStationeryOperation(PdfStationery Stationery) : PdfEditOperation +{ + /// + public override PdfEditOperationKind Kind => PdfEditOperationKind.ApplyStationery; + + /// Formats the operation for diagnostics. + /// The number of assignments and whether a default exists. + public override string ToString() => string.Create( + System.Globalization.CultureInfo.InvariantCulture, + $"apply stationery: {Stationery?.ToString() ?? "(null)"}"); +} + + /// Replaces the XMP metadata packet of the document. /// The packet, as UTF-8 XML; it must be well formed. /// diff --git a/src/SharpCorePDF.Domain/ValueObjects/PdfStationery.cs b/src/SharpCorePDF.Domain/ValueObjects/PdfStationery.cs new file mode 100644 index 0000000..72abfcf --- /dev/null +++ b/src/SharpCorePDF.Domain/ValueObjects/PdfStationery.cs @@ -0,0 +1,248 @@ +using System.Collections.Immutable; +using System.Globalization; +using SharpCorePDF.Domain.Ports; + +namespace SharpCorePDF.Domain.ValueObjects; + +/// +/// One stationery template and the pages it covers: the background a page is drawn over, and how that +/// background is placed on it. +/// +/// +/// A stationery template is a page of another document, recorded under the pages of the one being +/// edited. A says the pages are left without stationery, +/// which is how a caller excludes a page from a default template. +/// +public sealed record PdfStationeryAssignment +{ + /// + /// Gets the stationery document, or to leave the pages without stationery. + /// + public IPdfContentSource? Source { get; init; } + + /// Gets the one-based pages the template is recorded under. + public PageRange Pages { get; init; } = PageRange.All; + + /// Gets how the stationery page is placed and composited. + public PdfOverlayOptions Options { get; init; } = PdfOverlayOptions.Default; + + /// Gets the user or owner password of , when it is encrypted. + public string? Password { get; init; } +} + +/// +/// The stationery plan of an edit: an ordered set of templates, each covering a page range, plus a +/// default template for the pages no assignment covers. +/// +/// +/// +/// This is the aggregate behind : it describes +/// which background goes behind which page, and the editor expands it into the underlay layers it +/// already records. A plan is immutable, so it can be built once, shared and applied to several +/// documents: +/// +/// +/// var stationery = PdfStationery.Create() +/// .Assign(new PdfFileSource("letterhead.pdf"), PageRange.Single(1)) +/// .AssignDefault(new PdfFileSource("footer.pdf")); +/// +/// var plan = PdfEditPlan.Create().ApplyStationery(stationery); +/// +/// +/// Assignments are tried last first, so a later, narrower assignment overrides an earlier, broader +/// one. A page no assignment covers receives ; a page whose resolved assignment +/// has no source is left alone. +/// +/// +/// A one-page stationery document repeats across the pages it covers. A multi-page document maps one +/// page for one page, starting at the first page of the assignment, and a range that reaches past its +/// last page is refused when the plan is executed. +/// +/// +public sealed record PdfStationery +{ + /// Gets the templates in the order they were added. + public ImmutableArray Assignments { get; init; } = []; + + /// Gets the template recorded under every page an assignment does not cover. + public PdfStationeryAssignment? Default { get; init; } + + /// Creates stationery with no assignments and no default. + /// The new stationery. + public static PdfStationery Create() => new(); + + /// Records under the pages of . + /// The stationery document; a one-page document repeats across the range. + /// The one-based pages the template covers. + /// How the template is placed and composited; defaults to . + /// The user or owner password of , when it is encrypted. + /// The new stationery. + /// is . + public PdfStationery Assign( + IPdfContentSource source, + PageRange pages, + PdfOverlayOptions? options = null, + string? password = null) + { + ArgumentNullException.ThrowIfNull(source); + + return this with + { + Assignments = Assignments.Add(new PdfStationeryAssignment + { + Source = source, + Pages = pages, + Options = options ?? PdfOverlayOptions.Default, + Password = password, + }), + }; + } + + /// Records under every page an assignment does not cover. + /// The default stationery document; a one-page document repeats across the pages. + /// How the template is placed and composited; defaults to . + /// The user or owner password of , when it is encrypted. + /// The new stationery. + /// is . + public PdfStationery AssignDefault( + IPdfContentSource source, + PdfOverlayOptions? options = null, + string? password = null) + { + ArgumentNullException.ThrowIfNull(source); + + return this with + { + Default = new PdfStationeryAssignment + { + Source = source, + Pages = PageRange.All, + Options = options ?? PdfOverlayOptions.Default, + Password = password, + }, + }; + } + + /// Leaves the pages of without stationery. + /// The one-based pages that receive no template, even when a default exists. + /// The new stationery. + public PdfStationery AssignNone(PageRange pages) => + this with + { + Assignments = Assignments.Add(new PdfStationeryAssignment + { + Source = null, + Pages = pages, + Options = PdfOverlayOptions.Default, + }), + }; + + /// Resolves the template that covers . + /// The one-based page number. + /// + /// The last assignment that covers the page, the default when no assignment does, or + /// when neither exists. An assignment with no source means the page is left + /// without stationery, so callers should check . + /// + public PdfStationeryAssignment? ResolveForPage(int pageNumber) + { + for (var index = Assignments.Length - 1; index >= 0; index--) + { + var assignment = Assignments[index]; + + if (assignment.Pages.Contains(pageNumber)) + { + return assignment; + } + } + + return Default; + } + + /// Checks every invariant that can be verified without reading the stationery documents. + /// Every problem found, or an empty list when the stationery is usable. + public IReadOnlyList Validate() + { + var errors = new List(); + + if (Assignments.Length == 0 && Default is null) + { + errors.Add("the stationery has neither a page assignment nor a default template."); + } + + for (var index = 0; index < Assignments.Length; index++) + { + var assignment = Assignments[index]; + + if (assignment.Pages.From < 1) + { + errors.Add( + string.Create( + CultureInfo.InvariantCulture, + $"stationery assignment {index}: page range '{assignment.Pages}' does not start at a one-based page.")); + } + else if (!assignment.Pages.IsOpenEnded && assignment.Pages.To < assignment.Pages.From) + { + errors.Add( + string.Create( + CultureInfo.InvariantCulture, + $"stationery assignment {index}: page range '{assignment.Pages}' ends before it starts.")); + } + + if (assignment.Options is not { } options) + { + errors.Add($"stationery assignment {index}: the options are null."); + continue; + } + + foreach (var problem in options.Validate()) + { + errors.Add($"stationery assignment {index}: {problem}"); + } + } + + if (Default is { } fallback) + { + if (fallback.Options is not { } options) + { + errors.Add("the default stationery: the options are null."); + } + else + { + foreach (var problem in options.Validate()) + { + errors.Add($"the default stationery: {problem}"); + } + } + } + + return errors; + } + + /// Determines whether two stationery plans describe the same backgrounds. + /// The stationery to compare with. + /// when the assignments and the default are identical. + public bool Equals(PdfStationery? other) => + other is not null && Assignments.SequenceEqual(other.Assignments) && Default == other.Default; + + /// Returns a hash code over the assignments and the default. + /// The hash code. + public override int GetHashCode() + { + var hash = new HashCode(); + + foreach (var assignment in Assignments) + { + hash.Add(assignment); + } + + hash.Add(Default); + return hash.ToHashCode(); + } + + /// Formats the stationery for diagnostics. + /// The number of assignments and whether a default exists. + public override string ToString() => string.Create( + CultureInfo.InvariantCulture, + $"{Assignments.Length} stationery assignment(s){(Default is null ? string.Empty : " with a default")}"); +} diff --git a/src/SharpCorePDF.Infrastructure/PdfEditEngine.Pages.cs b/src/SharpCorePDF.Infrastructure/PdfEditEngine.Pages.cs index c0b44c0..1fa27f2 100644 --- a/src/SharpCorePDF.Infrastructure/PdfEditEngine.Pages.cs +++ b/src/SharpCorePDF.Infrastructure/PdfEditEngine.Pages.cs @@ -172,6 +172,10 @@ private static List BuildLayout( break; } + case PdfStationeryOperation stationery: + ApplyStationery(sources, layout, stationery.Stationery, index, document.SourceName); + break; + case PdfAddAnnotationOperation add: ApplyAnnotation( layout, @@ -896,6 +900,78 @@ private static void AddContentItems( destination.Add(new PdfReference(number, 0)); } + /// Records the stationery template of every page the plan covers. + /// The documents of the edit. + /// The pages of the edit, in output order. + /// The templates and the pages they cover. + /// The position of the operation, used in error messages. + /// The display name of the document being edited, used in error messages. + /// + /// A stationery document has fewer pages than the range it covers needs. + /// + private static void ApplyStationery( + EditSources sources, + List layout, + PdfStationery stationery, + int index, + string documentName) + { + for (var pageNumber = 1; pageNumber <= layout.Count; pageNumber++) + { + if (stationery.ResolveForPage(pageNumber) is not { Source: { } source } assignment) + { + // An assignment with no source, or no default at all, leaves the page as it is. + continue; + } + + var reader = sources.SourceOf(source); + + layout[pageNumber - 1].Overlays.Add( + new OverlayLayer( + reader, + ResolveStationeryPage(reader, assignment, pageNumber, index, documentName), + assignment.Options, + PdfOverlayLayer.Under)); + } + } + + /// Picks the stationery page recorded under one page of the edited document. + /// The stationery document. + /// The assignment that covers the page. + /// The one-based page of the edited document. + /// The position of the operation, used in error messages. + /// The display name of the document being edited, used in error messages. + /// The stationery page. + /// + /// The stationery document has fewer pages than the range it covers needs. + /// + private static SourcePage ResolveStationeryPage( + PdfFileReader reader, + PdfStationeryAssignment assignment, + int pageNumber, + int index, + string documentName) + { + // A one-page template repeats across the pages it covers; a multi-page one maps page for page, + // starting at the first page of its assignment. + if (reader.Pages.Count == 1) + { + return reader.Pages[0]; + } + + var offset = pageNumber - assignment.Pages.From; + + if (offset < 0 || offset >= reader.Pages.Count) + { + throw new PdfEditPlanValidationException( + string.Create( + CultureInfo.InvariantCulture, + $"operation {index}: the stationery document '{reader.SourceName}' has {reader.Pages.Count} page(s), which cannot cover page {pageNumber} of '{documentName}'.")); + } + + return reader.Pages[offset]; + } + /// One page of the edited document while its layout is being resolved. private sealed class EditedPage(PdfFileReader reader, SourcePage source, PdfRectangle mediaBox) { diff --git a/src/SharpCorePDF.Infrastructure/PdfEditEngine.Sources.cs b/src/SharpCorePDF.Infrastructure/PdfEditEngine.Sources.cs index 31368ac..77ca7b6 100644 --- a/src/SharpCorePDF.Infrastructure/PdfEditEngine.Sources.cs +++ b/src/SharpCorePDF.Infrastructure/PdfEditEngine.Sources.cs @@ -29,10 +29,43 @@ private async Task OpenSourcesAsync( // Operations are records, so two operations that name the same source compare equal; the map // is keyed by identity to keep every operation pointing at the document it actually opened. var documents = new Dictionary(ReferenceEqualityComparer.Instance); + + // A stationery operation names several documents at once, so its sources are keyed by the source + // itself. The same source is opened once even when several assignments name it. + var stationery = new Dictionary(ReferenceEqualityComparer.Instance); var readers = new List { document }; foreach (var operation in plan.Operations) { + cancellationToken.ThrowIfCancellationRequested(); + + if (operation is PdfStationeryOperation { Stationery: { } templates }) + { + foreach (var assignment in templates.Assignments) + { + await OpenStationeryAsync( + assignment.Source, + assignment.Password, + stationery, + readers, + warnings, + cancellationToken).ConfigureAwait(false); + } + + if (templates.Default is { } fallback) + { + await OpenStationeryAsync( + fallback.Source, + fallback.Password, + stationery, + readers, + warnings, + cancellationToken).ConfigureAwait(false); + } + + continue; + } + var (content, password, onePage) = operation switch { PdfImportPageOperation import => (import.Source, import.Password, false), @@ -47,44 +80,89 @@ private async Task OpenSourcesAsync( continue; } - cancellationToken.ThrowIfCancellationRequested(); + documents[operation] = await ReadSourceAsync(content, password, onePage, warnings, cancellationToken) + .ConfigureAwait(false); + readers.Add(documents[operation]); + } - var displayName = content.DisplayName; + return new EditSources(document, readers, documents, stationery); + } - await using var stream = await content.OpenReadAsync(cancellationToken).ConfigureAwait(false); - var bytes = await PdfByteReader - .ReadAllAsync(stream, options.MaxSourceBytes, displayName, cancellationToken) - .ConfigureAwait(false); + /// Opens one stationery document, unless an earlier assignment already opened it. + /// The stationery document, or for a page left bare. + /// The password of the document, when it is encrypted. + /// The documents opened for stationery so far, by source. + /// The documents of the edit, which the reader is appended to. + /// The list that receives the remarks of the document that was read. + /// A token to cancel the edit. + private async Task OpenStationeryAsync( + IPdfContentSource? content, + string? password, + Dictionary stationery, + List readers, + List warnings, + CancellationToken cancellationToken) + { + if (content is null || stationery.ContainsKey(content)) + { + return; + } - var reader = new PdfFileReader(bytes, displayName, options, password); + var reader = await ReadSourceAsync(content, password, onePage: false, warnings, cancellationToken) + .ConfigureAwait(false); - if (reader.IsEncrypted && reader.Security is null) - { - throw new PdfEncryptionException(displayName, reader.RequiresPassword); - } + stationery[content] = reader; + readers.Add(reader); + } - if (reader.Pages.Count == 0) - { - throw new PdfEditPlanValidationException( - $"'{displayName}' has no pages, so no page can be copied from it."); - } + /// Reads one document into a reader the edit can copy objects from. + /// The document to read. + /// The password of the document, when it is encrypted. + /// Whether the document must hold exactly one page. + /// The list that receives the remarks of the document that was read. + /// A token to cancel the edit. + /// The reader of the document. + /// The document is encrypted and could not be opened. + /// The document has no page, or must hold one and does not. + private async Task ReadSourceAsync( + IPdfContentSource content, + string? password, + bool onePage, + List warnings, + CancellationToken cancellationToken) + { + var displayName = content.DisplayName; - if (onePage && reader.Pages.Count != 1) - { - throw new PdfEditPlanValidationException( - $"the page to insert must come from a one-page document, but '{displayName}' has {reader.Pages.Count} page(s)."); - } + await using var stream = await content.OpenReadAsync(cancellationToken).ConfigureAwait(false); + var bytes = await PdfByteReader + .ReadAllAsync(stream, options.MaxSourceBytes, displayName, cancellationToken) + .ConfigureAwait(false); - documents[operation] = reader; - readers.Add(reader); + var reader = new PdfFileReader(bytes, displayName, options, password); - foreach (var warning in reader.Warnings.Where(warning => !warnings.Contains(warning))) - { - warnings.Add(warning); - } + if (reader.IsEncrypted && reader.Security is null) + { + throw new PdfEncryptionException(displayName, reader.RequiresPassword); } - return new EditSources(document, readers, documents); + if (reader.Pages.Count == 0) + { + throw new PdfEditPlanValidationException( + $"'{displayName}' has no pages, so no page can be copied from it."); + } + + if (onePage && reader.Pages.Count != 1) + { + throw new PdfEditPlanValidationException( + $"the page to insert must come from a one-page document, but '{displayName}' has {reader.Pages.Count} page(s)."); + } + + foreach (var warning in reader.Warnings.Where(warning => !warnings.Contains(warning))) + { + warnings.Add(warning); + } + + return reader; } } @@ -97,19 +175,23 @@ internal sealed class EditSources private readonly IReadOnlyList readers; private readonly Dictionary copiers = []; private readonly Dictionary documents; + private readonly Dictionary stationery; /// Initializes a new instance of the class. /// The document being edited. /// Every document of the edit, first. /// The document each importing operation reads from. + /// The document each stationery source names. public EditSources( PdfFileReader document, IReadOnlyList readers, - Dictionary documents) + Dictionary documents, + Dictionary stationery) { Document = document; this.readers = readers; this.documents = documents; + this.stationery = stationery; } /// Gets the document being edited. @@ -127,6 +209,11 @@ public EditSources( /// The document that operation copies pages from. public PdfFileReader SourceOf(PdfEditOperation operation) => documents[operation]; + /// Finds the document a stationery assignment reads from. + /// The stationery source. + /// The document that source names. + public PdfFileReader SourceOf(IPdfContentSource content) => stationery[content]; + /// Finds the copier that writes the objects of a document into the result. /// One of the documents of the edit. /// The copier of that document. diff --git a/tests/SharpCorePDF.Tests/PdfDocumentEditorTests.Stationery.cs b/tests/SharpCorePDF.Tests/PdfDocumentEditorTests.Stationery.cs new file mode 100644 index 0000000..a2666f6 --- /dev/null +++ b/tests/SharpCorePDF.Tests/PdfDocumentEditorTests.Stationery.cs @@ -0,0 +1,251 @@ +using SharpCorePDF.Domain.Aggregates; +using SharpCorePDF.Domain.Exceptions; +using SharpCorePDF.Domain.ValueObjects; +using SharpCorePDF.Infrastructure; +using SharpCorePDF.Infrastructure.Sources; + +namespace SharpCorePDF.Tests; + +/// +/// Tests of stationery: a background template per page range, a default for the pages no assignment +/// covers, and the underlay order the contract states. +/// +public sealed partial class PdfDocumentEditorTests +{ + /// Builds a one-page template that draws . + /// The text the template page draws. + /// The template as a source. + private static PdfByteArraySource Template(string text) => new(Stamped(text), $"{text}.pdf"); + + /// Builds a two-page template whose pages draw two different phrases. + /// The text of the first template page. + /// The text of the second template page. + /// The template as a source. + private static PdfByteArraySource TwoPageTemplate(string first, string second) => + new( + PdfDocumentBuilder.Create() + .AddPage(PdfPageSize.A5, page => page.DrawText(first, 72, 300, Helvetica, 24)) + .AddPage(PdfPageSize.A5, page => page.DrawText(second, 72, 300, Helvetica, 24)) + .ToArray(), + "two-page-stationery.pdf"); + + /// A default template fills the pages no assignment covers. + [Fact] + public async Task Applies_assignments_and_a_default_to_the_pages_they_cover() + { + var stationery = PdfStationery.Create() + .Assign(Template("footer"), PageRange.FromTo(2, 3)) + .AssignDefault(Template("letterhead")); + + var edited = await Editor.ApplyToArrayAsync( + new PdfByteArraySource(ThreePages(), "three-pages.pdf"), + PdfEditPlan.Create().ApplyStationery(stationery), + cancellationToken: Token); + + var texts = await TextsAsync(edited, 3); + + Assert.Contains("letterhead", Compact(texts[0]), StringComparison.Ordinal); + Assert.DoesNotContain("footer", Compact(texts[0]), StringComparison.Ordinal); + Assert.Contains("footer", Compact(texts[1]), StringComparison.Ordinal); + Assert.Contains("footer", Compact(texts[2]), StringComparison.Ordinal); + } + + /// A later, narrower assignment overrides an earlier, broader one. + [Fact] + public async Task A_specific_assignment_overrides_a_broader_one() + { + var stationery = PdfStationery.Create() + .Assign(Template("letterhead"), PageRange.All) + .Assign(Template("footer"), PageRange.Single(2)); + + var edited = await Editor.ApplyToArrayAsync( + new PdfByteArraySource(ThreePages(), "three-pages.pdf"), + PdfEditPlan.Create().ApplyStationery(stationery), + cancellationToken: Token); + + var texts = await TextsAsync(edited, 3); + + Assert.Contains("letterhead", Compact(texts[0]), StringComparison.Ordinal); + Assert.Contains("footer", Compact(texts[1]), StringComparison.Ordinal); + Assert.DoesNotContain("letterhead", Compact(texts[1]), StringComparison.Ordinal); + Assert.Contains("letterhead", Compact(texts[2]), StringComparison.Ordinal); + } + + /// A page assigned no template keeps what it had, even when a default exists. + [Fact] + public async Task AssignNone_leaves_a_page_without_stationery() + { + var stationery = PdfStationery.Create() + .AssignNone(PageRange.Single(2)) + .AssignDefault(Template("letterhead")); + + var edited = await Editor.ApplyToArrayAsync( + new PdfByteArraySource(ThreePages(), "three-pages.pdf"), + PdfEditPlan.Create().ApplyStationery(stationery), + cancellationToken: Token); + + var texts = await TextsAsync(edited, 3); + + Assert.Contains("letterhead", Compact(texts[0]), StringComparison.Ordinal); + Assert.DoesNotContain("letterhead", Compact(texts[1]), StringComparison.Ordinal); + Assert.Contains("letterhead", Compact(texts[2]), StringComparison.Ordinal); + } + + /// A multi-page template maps one page for one page, starting at the range's first page. + [Fact] + public async Task Maps_a_multi_page_template_one_page_for_one_page() + { + var edited = await Editor.ApplyToArrayAsync( + new PdfByteArraySource(ThreePages(), "three-pages.pdf"), + PdfEditPlan.Create().ApplyStationery( + PdfStationery.Create().Assign(TwoPageTemplate("first", "second"), PageRange.FromTo(2, 3))), + cancellationToken: Token); + + var texts = await TextsAsync(edited, 3); + + Assert.Contains("first", Compact(texts[1]), StringComparison.Ordinal); + Assert.DoesNotContain("second", Compact(texts[1]), StringComparison.Ordinal); + Assert.Contains("second", Compact(texts[2]), StringComparison.Ordinal); + Assert.DoesNotContain("first", Compact(texts[0]), StringComparison.Ordinal); + } + + /// A template with fewer pages than its range needs is refused when the plan runs. + [Fact] + public async Task Refuses_a_template_that_cannot_cover_its_range() + { + var error = await Assert.ThrowsAsync(() => + Editor.ApplyToArrayAsync( + new PdfByteArraySource(ThreePages(), "three-pages.pdf"), + PdfEditPlan.Create().ApplyStationery( + PdfStationery.Create().Assign(TwoPageTemplate("first", "second"), PageRange.FromTo(1, 3))), + cancellationToken: Token)); + + Assert.Contains("cannot cover page 3", error.Message, StringComparison.Ordinal); + } + + /// The stationery is the first stream of the page, and the page's own streams follow it. + [Fact] + public async Task Draws_stationery_before_the_page_it_covers() + { + var edited = await Editor.ApplyToArrayAsync( + new PdfByteArraySource(ThreePages(), "three-pages.pdf"), + PdfEditPlan.Create().ApplyStationery( + PdfStationery.Create().AssignDefault(Template("letterhead"))), + cancellationToken: Token); + + var reader = Read(edited); + var contents = reader.ResolveArray(reader.Pages[1].Dictionary.Get("Contents"))!; + + Assert.True(contents.Count >= 2); + Assert.Contains(" Do", OperatorsOf(reader, contents.Items[0]), StringComparison.Ordinal); + Assert.DoesNotContain(" Do", OperatorsOf(reader, contents.Items[^1]), StringComparison.Ordinal); + } + + /// Stationery without an assignment or a default is refused before a document is read. + [Fact] + public void Refuses_stationery_without_a_template() + { + var plan = PdfEditPlan.Create().ApplyStationery(PdfStationery.Create()); + + Assert.Contains( + plan.Validate(), + error => error.Contains("neither a page assignment", StringComparison.Ordinal)); + Assert.Throws(() => plan.EnsureValid()); + } + + /// PDF/A-1b has no transparency, so a translucent stationery is refused. + [Fact] + public void Refuses_translucent_stationery_for_pdf_a_1b() + { + var plan = PdfEditPlan + .Create(PdfEditOutputOptions.Default with { PdfAProfile = PdfAProfile.PdfA1B }) + .ApplyStationery( + PdfStationery.Create().AssignDefault( + Template("letterhead"), + new PdfOverlayOptions { Opacity = 0.5 })); + + Assert.Contains(plan.Validate(), error => error.Contains("no transparency", StringComparison.Ordinal)); + } + + /// A blend mode other than Normal is refused for PDF/A-1b as well. + [Fact] + public void Refuses_a_blended_stationery_for_pdf_a_1b() + { + var plan = PdfEditPlan + .Create(PdfEditOutputOptions.Default with { PdfAProfile = PdfAProfile.PdfA1B }) + .ApplyStationery( + PdfStationery.Create().AssignDefault( + Template("letterhead"), + new PdfOverlayOptions { BlendMode = PdfOverlayBlendMode.Multiply })); + + Assert.Contains(plan.Validate(), error => error.Contains("no transparency", StringComparison.Ordinal)); + } + + /// A later assignment wins, and AssignNone resolves to an assignment with no template. + [Fact] + public void Resolves_the_last_assignment_that_covers_a_page() + { + var stationery = PdfStationery.Create() + .Assign(Template("letterhead"), PageRange.All) + .Assign(Template("footer"), PageRange.FromTo(2, 3)) + .AssignNone(PageRange.Single(3)); + + Assert.Equal("letterhead.pdf", stationery.ResolveForPage(1)?.Source?.DisplayName); + Assert.Equal("footer.pdf", stationery.ResolveForPage(2)?.Source?.DisplayName); + Assert.NotNull(stationery.ResolveForPage(3)); + Assert.Null(stationery.ResolveForPage(3)!.Source); + } + + /// A template is required: a null one is refused, whether it is assigned or made the default. + [Fact] + public void Refuses_a_null_template() + { + Assert.Throws(() => PdfStationery.Create().Assign(null!, PageRange.All)); + Assert.Throws(() => PdfStationery.Create().AssignDefault(null!)); + } + + /// The options a caller supplies are the options the assignment records. + [Fact] + public void Retains_the_supplied_options() + { + var options = new PdfOverlayOptions { Opacity = 0.25, BlendMode = PdfOverlayBlendMode.Multiply }; + var stationery = PdfStationery.Create().Assign(Template("footer"), PageRange.All, options, "secret"); + + Assert.Same(options, stationery.Assignments[0].Options); + Assert.Equal("secret", stationery.Assignments[0].Password); + } + + /// Two plans built from the same templates compare equal, and a default changes the comparison. + [Fact] + public void Stationery_is_a_value() + { + var template = Template("footer"); + var fallback = Template("letterhead"); + var options = new PdfOverlayOptions { Opacity = 0.25 }; + + var first = PdfStationery.Create().Assign(template, PageRange.All, options); + var second = PdfStationery.Create().Assign(template, PageRange.All, options); + var otherRange = PdfStationery.Create().Assign(template, PageRange.Single(1), options); + var withDefault = first.AssignDefault(fallback); + + Assert.Equal(first, second); + Assert.NotEqual(first, otherRange); + Assert.NotEqual(first, withDefault); + + // The hash names the same inputs as the comparison: the assignments and the default. + Assert.Equal(first.GetHashCode(), second.GetHashCode()); + Assert.NotEqual(first.GetHashCode(), otherRange.GetHashCode()); + Assert.NotEqual(first.GetHashCode(), withDefault.GetHashCode()); + } + + /// The diagnostic text says how many assignments exist and whether a default does. + [Fact] + public void Describes_itself() + { + var withoutDefault = PdfStationery.Create().Assign(Template("footer"), PageRange.All); + var withDefault = withoutDefault.AssignDefault(Template("letterhead")); + + Assert.Equal("1 stationery assignment(s)", withoutDefault.ToString()); + Assert.Equal("1 stationery assignment(s) with a default", withDefault.ToString()); + } +} diff --git a/tests/SharpCorePDF.Tests/PdfDocumentEditorTests.StationeryAcceptance.cs b/tests/SharpCorePDF.Tests/PdfDocumentEditorTests.StationeryAcceptance.cs new file mode 100644 index 0000000..731335b --- /dev/null +++ b/tests/SharpCorePDF.Tests/PdfDocumentEditorTests.StationeryAcceptance.cs @@ -0,0 +1,199 @@ +using System.Text; +using SharpCorePDF.Domain.Aggregates; +using SharpCorePDF.Domain.ValueObjects; +using SharpCorePDF.Infrastructure; +using SharpCorePDF.Infrastructure.Pdf; +using SharpCorePDF.Infrastructure.Sources; + +namespace SharpCorePDF.Tests; + +/// +/// One test per acceptance criterion of issue #6, so the checklist can be read against a named +/// assertion rather than inferred from the behaviour tests. +/// +public sealed partial class PdfDocumentEditorTests +{ + /// Reads the XObjects a page's resources name, resolving each through the reader. + /// The document to read. + /// The zero-based index of the page. + /// The XObject streams, in resource order. + private static List XObjectsOf(PdfFileReader reader, int pageIndex) + { + var resources = reader.ResolveDictionary(reader.Pages[pageIndex].Dictionary.Get("Resources")); + + if (resources is null || reader.ResolveDictionary(resources.Get("XObject")) is not { } xobjects) + { + return []; + } + + return xobjects.Entries + .Select(entry => reader.Resolve(entry.Value)) + .OfType() + .ToList(); + } + + /// Criterion 1: different stationery PDFs apply to selected pages and page ranges. + [Fact] + public async Task Acceptance_criterion_1_applies_different_stationery_to_pages_and_ranges() + { + var stationery = PdfStationery.Create() + .Assign(Template("letterhead"), PageRange.Single(1)) + .Assign(Template("footer"), PageRange.FromTo(2, 3)); + + var edited = await Editor.ApplyToArrayAsync( + new PdfByteArraySource(ThreePages(), "three-pages.pdf"), + PdfEditPlan.Create().ApplyStationery(stationery), + cancellationToken: Token); + + var texts = await TextsAsync(edited, 3); + + Assert.Contains("letterhead", Compact(texts[0]), StringComparison.Ordinal); + Assert.DoesNotContain("footer", Compact(texts[0]), StringComparison.Ordinal); + Assert.Contains("footer", Compact(texts[1]), StringComparison.Ordinal); + Assert.Contains("footer", Compact(texts[2]), StringComparison.Ordinal); + } + + /// Criterion 2: the default stationery covers every page without an assignment. + [Fact] + public async Task Acceptance_criterion_2_applies_default_stationery_to_the_remaining_pages() + { + var stationery = PdfStationery.Create() + .Assign(Template("letterhead"), PageRange.Single(1)) + .AssignDefault(Template("footer")); + + var edited = await Editor.ApplyToArrayAsync( + new PdfByteArraySource(ThreePages(), "three-pages.pdf"), + PdfEditPlan.Create().ApplyStationery(stationery), + cancellationToken: Token); + + var texts = await TextsAsync(edited, 3); + + Assert.Contains("letterhead", Compact(texts[0]), StringComparison.Ordinal); + Assert.DoesNotContain("footer", Compact(texts[0]), StringComparison.Ordinal); + Assert.Contains("footer", Compact(texts[1]), StringComparison.Ordinal); + Assert.Contains("footer", Compact(texts[2]), StringComparison.Ordinal); + } + + /// Criterion 3: a multi-page content PDF is supported. + [Fact] + public async Task Acceptance_criterion_3_supports_a_multi_page_content_pdf() + { + var edited = await Editor.ApplyToArrayAsync( + new PdfByteArraySource(ThreePages(), "three-pages.pdf"), + PdfEditPlan.Create().ApplyStationery( + PdfStationery.Create().AssignDefault(Template("letterhead"))), + cancellationToken: Token); + + var info = await InspectAsync(edited); + var texts = await TextsAsync(edited, 3); + + Assert.Equal(3, info.PageCount); + Assert.Contains("one", texts[0], StringComparison.Ordinal); + Assert.Contains("two", texts[1], StringComparison.Ordinal); + Assert.Contains("three", texts[2], StringComparison.Ordinal); + } + + /// Criterion 4: page dimensions and the position of the content are preserved. + [Fact] + public async Task Acceptance_criterion_4_preserves_page_dimensions_and_content_positioning() + { + var source = ThreePages(); + var before = await InspectAsync(source); + + var edited = await Editor.ApplyToArrayAsync( + new PdfByteArraySource(source, "three-pages.pdf"), + PdfEditPlan.Create().ApplyStationery( + PdfStationery.Create().AssignDefault(Template("letterhead"))), + cancellationToken: Token); + + var after = await InspectAsync(edited); + + Assert.Equal(before.PageCount, after.PageCount); + + // The three content pages are A5, A4 and Letter; stationery must not resize any of them. + for (var page = 0; page < before.PageCount; page++) + { + Assert.Equal(before.Pages[page].Size, after.Pages[page].Size); + } + + // The content is untouched, byte for byte, so every letter keeps its baseline. The template's + // text is 24 points and the content's is 12, which is how the two are told apart. + for (var page = 1; page <= before.PageCount; page++) + { + var expected = await BaselinesAsync(source, page, letter => letter.FontSize <= 20); + var actual = await BaselinesAsync(edited, page, letter => letter.FontSize <= 20); + + Assert.NotEmpty(expected); + Assert.Equal(expected, actual); + } + } + + /// Criterion 5: vector graphics and selectable text are preserved. + [Fact] + public async Task Acceptance_criterion_5_preserves_vector_graphics_and_selectable_text() + { + var template = PdfDocumentBuilder.Create() + .AddPage(PdfPageSize.A4, page => page + .DrawLine( + new PdfPoint(72, 72), + new PdfPoint(523, 72), + new PdfStroke(PdfPaint.Black, width: 0.5)) + .DrawText("letterhead", 72, 120, Helvetica, 18)) + .Build("letterhead.pdf"); + + var edited = await Editor.ApplyToArrayAsync( + new PdfByteArraySource(ThreePages(), "three-pages.pdf"), + PdfEditPlan.Create().ApplyStationery( + PdfStationery.Create().AssignDefault(template)), + cancellationToken: Token); + + // Both the content and the template are still selectable text. + var texts = await TextsAsync(edited, 3); + + Assert.Contains("letterhead", Compact(texts[0]), StringComparison.Ordinal); + Assert.Contains("one", Compact(texts[0]), StringComparison.Ordinal); + + // The template is a form XObject whose stream still holds the path and the text operators: + // it was copied, not rasterized. + var reader = Read(edited); + var form = XObjectsOf(reader, 0) + .Single(xobject => xobject.Dictionary.GetName("Subtype") == "Form"); + var operators = Encoding.ASCII.GetString(PdfFilters.Decode(form, reader.SourceName)); + + Assert.Contains(" m", operators, StringComparison.Ordinal); + Assert.Contains(" l", operators, StringComparison.Ordinal); + Assert.True( + operators.Contains("Tj", StringComparison.Ordinal) || operators.Contains("TJ", StringComparison.Ordinal), + "the template's text operators are missing from its form XObject."); + } + + /// Criterion 6: the result is a valid PDF whose content was not rasterized. + [Fact] + public async Task Acceptance_criterion_6_produces_a_valid_pdf_without_rasterization() + { + var edited = await Editor.ApplyToArrayAsync( + new PdfByteArraySource(ThreePages(), "three-pages.pdf"), + PdfEditPlan.Create().ApplyStationery( + PdfStationery.Create().AssignDefault(Template("letterhead"))), + cancellationToken: Token); + + // Reading the whole document back proves the cross-reference table and every object it names. + var reader = Read(edited); + var info = await InspectAsync(edited); + + Assert.Equal(3, reader.Pages.Count); + Assert.Equal(3, info.PageCount); + + for (var page = 0; page < reader.Pages.Count; page++) + { + var xobjects = XObjectsOf(reader, page); + + // The background is drawn from a form XObject, which is vector content. + Assert.Contains(xobjects, xobject => xobject.Dictionary.GetName("Subtype") == "Form"); + + // Neither the content nor the template carries an image, so an image XObject would be the + // fingerprint of rasterizing them together. There is none. + Assert.DoesNotContain(xobjects, xobject => xobject.Dictionary.GetName("Subtype") == "Image"); + } + } +}