Remove links from pdf using itextsharp .net

, ,

I’m trying to remove all links from a PDF file using the code below:

static void RemoveLinks(PdfReader reader, int sourcePage)
{
    PdfDictionary sourcePageDict = reader.GetPageNRelease(sourcePage);
    PdfArray annotations = sourcePageDict.GetAsArray(PdfName.ANNOTS);
    if (annotations != null && annotations.Size > 0)
    {
        foreach (var item in annotations)
        {
            var annotationObject = PdfReader.GetPdfObject(item);

            if (!annotationObject.IsDictionary())
                continue;
            PdfDictionary annotation = (PdfDictionary) annotationObject;
            if (!PdfName.LINK.Equals(annotation.GetAsName(PdfName.SUBTYPE)))
                continue;

            //To do remove annotation
        }
    }
}

I’m running into an issue where annotationObject is not a dictionary, preventing me from finding the links to remove.

Change the line var annotationObject = PdfReader.GetPdfObject(item); to var annotationObject = reader.GetPdfObject(item); to ensure that you are using the same PdfReader instance throughout the code.