itext7 update annotation text

1.4k views Asked by At

I would like to update text content within a FreeText annotation when I copy the annotation from one PDF document to another, but for some reason the text does not update in the final PDF using the approach shown below. The annotation object updates, but the final result within the PDF does not reflect the updated content for the FreeText annotation type. Strangely, Ink type annotations do get updated with the revised content, as it shows up in the form of a sticky note looking comment overlaid on top of the Ink annotation itself.

Here's a quick snippet of the code I've used (if needed I can add more):

foreach (var anno in annots)
{
    var a = anno.GetPdfObject().CopyTo(masterPdfDoc);

    PdfAnnotation ano = PdfAnnotation.MakeAnnotation(a);
    var contents = ano.GetContents().ToString();
    ano.SetContents(new PdfString("COMMENT: " + contents));
    //ano.Put(PdfName.Contents, new PdfString("COMMENT: " + contents));

    masterDocPage.AddAnnotation(ano);
}

Would greatly appreciate any advice provided. Thanks

1

There are 1 answers

0
James Cramer On

The following code snippet copies and modifies the text content of FreeText annotations from 1 PDF (i.e. annots) and saves the modified annotations into a new PDF. A good chunk of the code is similar to the answer of this post but was updated for iText7.

foreach (var anno in annots)
{
    var a = anno.GetPdfObject().CopyTo(masterPdfDoc);
    PdfAnnotation ano = PdfAnnotation.MakeAnnotation(a);

    var apDict = ano.GetAppearanceDictionary();
    if (apDict == null)
    {
        Console.WriteLine("No appearances.");
        continue;
    }
    foreach (PdfName key in apDict.KeySet())
    {
        Console.WriteLine("Appearance: {0}", key);
        PdfStream value = apDict.GetAsStream(key);
        if (value != null)
        {
            var text = ExtractAnnotationText(value);
            Console.WriteLine("Extracted Text: {0}", text);

            if (text != "")
            {
                var valueString = Encoding.ASCII.GetString(value.GetBytes());
                value.SetData(Encoding.ASCII.GetBytes(valueString.Replace(text, "COMMENT: " + text)));
            }
        }
    }
    masterDocPage.AddAnnotation(ano);
}

public static String ExtractAnnotationText(PdfStream xObject)
{
   PdfResources resources = new PdfResources(xObject.GetAsDictionary(PdfName.Resources));
   ITextExtractionStrategy strategy = new LocationTextExtractionStrategy();

   PdfCanvasProcessor processor = new PdfCanvasProcessor(strategy);
   processor.ProcessContent(xObject.GetBytes(), resources);
   var text = strategy.GetResultantText();
   return text;
}