通过itextsharp .net从pdf删除链接

时间:2020-01-01 08:00:25

标签: c# pdf itext

我想从pdf文件中删除所有链接。我正在使用下面的代码来检测注释:

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
        }
    }
}

但是注解对象不是字典,所以我找不到要删除的链接

enter image description here

1 个答案:

答案 0 :(得分:0)

您说annotationObject不是字典。它应该是。 屏幕快照显示annotations是一个间接引用数组,这是预期的。使用GetPdfObject,您可以解决对直接对象的间接引用,在这种情况下,直接对象是字典。

如果您正在处理的PDF文件具有一个Annots数组,其中包含不引用注释字典的间接引用,则从技术上讲,它是无效的PDF。如果您可以共享它将会很有用。

要删除链接,您只需删除所有链接注释:

static void RemoveLinks(PdfReader reader, int sourcePage, Stream output)
{
    // PdfStamper to alter the file
    PdfStamper stamper = new PdfStamper(reader, output);
    PdfDictionary sourcePageDict = reader.GetPageNRelease(sourcePage);
    PdfArray annotations = sourcePageDict.GetAsArray(PdfName.ANNOTS);
    // Annotations to keep
    PdfArray newannots = new PdfArray();
    if (annotations != null && annotations.Size > 0)
    {
        foreach (PdfObject item in annotations)
        {
            PdfObject annotationObject = PdfReader.GetPdfObject(item);

            if (!annotationObject.IsDictionary())
                continue;
            PdfDictionary annotation = (PdfDictionary)annotationObject;
            if (!PdfName.LINK.Equals(annotation.GetAsName(PdfName.SUBTYPE)))
                // Keep annotation when it's not a link annotation
                newannots.Add(item);
        }
        // Replace annots array for this page
        sourcePageDict.Put(PdfName.ANNOTS, newannots);
    }
    stamper.Close();
}
相关问题