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
13 changes: 12 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
25 changes: 25 additions & 0 deletions docs/manual/src/14-editing.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion docs/parity.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <output.pdf>` 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 <output.pdf>` 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 <output.pdf>` 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 <output.pdf>` 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 <output.pdf>`; 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 |
Expand Down
62 changes: 62 additions & 0 deletions examples/SharpCorePDF.Examples/PdfEditExamples.cs
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,68 @@ public static async Task WatermarkAsync(ExampleContext context, CancellationToke
}
}

/// <summary>
/// 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.
/// </summary>
/// <param name="context">The document to dress and the ports to edit it with.</param>
/// <param name="cancellationToken">A token to cancel the work.</param>
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);
}


/// <summary>Comments on the document without touching a byte of its content.</summary>
/// <param name="context">The document to comment on and the ports to comment with.</param>
/// <param name="cancellationToken">A token to cancel the work.</param>
Expand Down
Loading
Loading