我想从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
}
}
}
但是notificationObject不是字典,所以我找不到要删除的链接
您说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();
}