PdfArray.remove() 没有删除所有注释

PdfArray.remove() is not removing all annotations

我想删除 PDF 中的所有注释。我正在使用此代码:

void removeAnnotations(string inputPath,string outputPath)
        {
            PdfReader pdfReader = new PdfReader(inputPath);
            PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileStream(outputPath, FileMode.Create));
            PdfDictionary pageDict = pdfReader.GetPageN(1);
            PdfArray annotArray = pageDict.GetAsArray(PdfName.ANNOTS);
            for (int i = 0; i < annotArray.Size; i++)
            {
                annotArray.Remove(i);   
            }
            pdfStamper.Close();
        }

当我第一次创建 annotArray 时,它有 217 个项目。在 annotArray.Remove() 的 for 循环之后,它有 108 个项目,我仍然可以在 outputPath 生成的 PDF 上看到一些标注和线条。我不是很清楚剩下的项目有什么共同点,以及为什么 annotArray.Remove() 跳过了它们。如何删除所有注释?

免责声明:我没有使用过 itextSharp。我很好奇为什么它不应该 remove.Code 看起来不错。我用谷歌搜索并找到了您可能感兴趣的内容。希望对你有帮助。

You cannot delete the annotations "in place" with iTextSharp. You have to create a new PDF based on the original, and the way to do this is to open the original with PDFReader, use RemoveAt to get rid of the undesirable annotations in memory, then use PDFstamper or PDFcopy to make a new PDF based on what's left.

Remove Annotation from PDF

Remove Annotation using PDF Object Number

Remove hyperlinks from a PDF document (iTextSharp)

How do I remove link annotations from a PDF using iText?

事实证明删除所有注释相当容易:

void removeAnnotations(string inputPath,string outputPath)
        {
            PdfReader pdfReader = new PdfReader(inputPath);
            PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileStream(outputPath, FileMode.Create));

            pdfReader.RemoveAnnotations();
            pdfStamper.Close();
        }

假设数组中有 10 个元素:

array = [a, b, c, d, e, f, g, h, i, j]

然后像这样遍历数组:

for (int i = 0; i < array.Size; i++)
{
    array.Remove(i);   
}

然后就是这样一步步发生的:

步骤 0

删除元素 0。 结果:[b, c, d, e, f, g, h, i, j]

步骤 1

删除元素 1。 结果:[b, d, e, f, g, h, i, j]

步骤 2

删除元素 2。 结果:[b, d, f, g, h, i, j]

步骤 3

删除元素 3。 结果:[b, d, f, h, i, j]

步骤 4

删除元素 4。 结果:[b, d, f, h, j]

步骤 5

删除元素5。没有元素5,所以没有什么可以删除的。结果:[b, d, f, h, j]

第 6 步到第 9 步

删除元素6到9。没有元素6到9,所以没有什么要删除的。结果:[b, d, f, h, j]

尽管我的数组只包含 10 个元素而你的数组包含 128 个元素,但原理是相同的:由于代码中的逻辑错误,你没有删除所有注释。另一种类型的数组会抛出数组越界异常,但 PdfArray 不会这样做,因为它更能容忍数组不完整的错误 PDF。

您可以像这样修复您的代码:

int n = annotArray.Size;
for (int i = 0; i < n; i++)
{
    annotArray.Remove(0);   
}

或者,正如您自己发现的那样,您可以一次删除所有注释:

pdfReader.RemoveAnnotations();