From 3b318e1944c2372124aa785a631c7477f81e0357 Mon Sep 17 00:00:00 2001 From: EnraH <2443784+EnraH@users.noreply.github.com> Date: Sun, 20 Jul 2025 18:10:15 +0200 Subject: [PATCH] add option to strip annotation (#492) * add option to strip annotation * fix implementation and tests --------- Co-authored-by: arne.hansen Co-authored-by: Eliot Jones --- .../Writer/PdfDocumentBuilderTests.cs | 25 +++++++++++++++++++ .../Writer/PdfDocumentBuilder.cs | 8 +++++- 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/src/UglyToad.PdfPig.Tests/Writer/PdfDocumentBuilderTests.cs b/src/UglyToad.PdfPig.Tests/Writer/PdfDocumentBuilderTests.cs index bfa12ea4..06ba97bc 100644 --- a/src/UglyToad.PdfPig.Tests/Writer/PdfDocumentBuilderTests.cs +++ b/src/UglyToad.PdfPig.Tests/Writer/PdfDocumentBuilderTests.cs @@ -129,6 +129,31 @@ } } + [Fact] + public void CanFastAddPageAndStripAllAnnots() + { + var first = IntegrationHelpers.GetDocumentPath("outline.pdf"); + var contents = File.ReadAllBytes(first); + + byte[] results = null; + using (var existing = PdfDocument.Open(contents, ParsingOptions.LenientParsingOff)) + using (var output = new PdfDocumentBuilder()) + { + output.AddPage(existing, 1, false); + results = output.Build(); + var pg = existing.GetPage(1); + var annots = pg.ExperimentalAccess.GetAnnotations().ToList(); + Assert.NotEmpty(annots); + } + + using (var rewritten = PdfDocument.Open(results, ParsingOptions.LenientParsingOff)) + { + var pg = rewritten.GetPage(1); + var annots = pg.ExperimentalAccess.GetAnnotations().ToList(); + Assert.Empty(annots); + } + } + [Fact] public void CanReadSingleBlankPage() { diff --git a/src/UglyToad.PdfPig/Writer/PdfDocumentBuilder.cs b/src/UglyToad.PdfPig/Writer/PdfDocumentBuilder.cs index 45ef5a55..476a6351 100644 --- a/src/UglyToad.PdfPig/Writer/PdfDocumentBuilder.cs +++ b/src/UglyToad.PdfPig/Writer/PdfDocumentBuilder.cs @@ -307,8 +307,9 @@ namespace UglyToad.PdfPig.Writer /// /// Source document. /// Page to copy. + /// Flag to set whether annotation of page should be kept /// A builder for editing the page. - public PdfPageBuilder AddPage(PdfDocument document, int pageNumber) + public PdfPageBuilder AddPage(PdfDocument document, int pageNumber, bool keepAnnotations = true) { return AddPage(document, pageNumber, null); } @@ -453,6 +454,11 @@ namespace UglyToad.PdfPig.Writer if (kvp.Key == NameToken.Annots) { + if (!keepAnnotations) + { + continue; + } + var val = kvp.Value; if (kvp.Value is IndirectReferenceToken ir) {