AAS.N
AAS.N

Reputation: 313

Itext 7: Cannot remove annotations or flatten document

I've been playing around more since getting the stamping process to work for the most part. Now I am trying to delete all annotations from a PDF. I have tried it multiple ways as shown below:

public void ClearStamps()
{
    IList<PdfAnnotation> annotList = pdfDoc.GetFirstPage().GetAnnotations();
    int listCount = annotList.Count;

    for (int i = 0; i < listCount; i++)
    {
        annotList.RemoveAt(i);
    }

    pdfDoc.Close();

    if (Overwrite)
    {
        File.Delete(pdfFilePath);
        File.Move(pdfFileDest, pdfFilePath);
    }
}

OR

IList<PdfAnnotation> annotList = pdfDoc.GetFirstPage().GetAnnotations();
int listCount = annotList.Count;

for (int i = 0; i < listCount; i++)
{
    annotList[i].Remove(PdfName.Annots);
}

pdfDoc.Close();

The resulting PDFs still remain intact after the operation above.

I also tried cycling through all the PdfName objects that resemble annotations (Annot, Annots, Annotation, etc.)

Is the method I am using to acquire the annotations incorrect? That is exactly how I acquired stamp properties for my stamp operation.

Additionally, when it comes to annotation manipulation, I can't seem to find any method that resembles the Flattening bool from iText5 - the closest I can get was setting the annotation flags to LOCKED...not the most ideal way to flatten.

Upvotes: 0

Views: 2569

Answers (1)

Alexey Subach
Alexey Subach

Reputation: 12302

Removing annotations

Approach 1. Iterate over all the annotations and remove one-by-one:

private void clearAnnotations(PdfPage page) {
    Collection<PdfAnnotation> annotations = new ArrayList<>(page.getAnnotations());
    for (PdfAnnotation annotation : annotations) {
        page.removeAnnotation(annotation);
    }
}

Approach 2. More low-level manipulation: remove /Annots from page dictionary:

private void clearAnnotations(PdfPage page) {
    page.getPdfObject().remove(PdfName.Annots);
}

Call the method for every page you want to clear the annotations from, e.g.:

clearAnnotations(pdfDocument.getFirstPage());

The code is in Java, but should be very easily translated to C#.

Flatten annotations

iText5 supported only flattening of annotations (that are not related to form fields) which have appearance streams in them. The scope of that functionality was really limited. This functionality can be added to iText7 in the future, but currently it is absent.

Meanwhile, you can try to achieve the same functionality manually. The idea is to find an appearance stream in the annotation (/AP key is the starting point), then create a PdfFormXObject that would wrap that appearance stream, and then add that object to any PdfCanvas you like.

Upvotes: 4

Related Questions