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

标签 c# pdf itext

我想从 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() 跳过。如何删除所有注释?

最佳答案

假设一个数组中有 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。 结果:[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();

关于c# - PdfArray.remove() 没有删除所有注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36727326/

相关文章:

c# - 如何在 SQLite 中存储 boolean 值

c# - iTextSharp - PDF - 调整文档大小以容纳大图像

java - iText 与 anchor 有问题(可点击但没有任何反应)

java - Layer2 中的签名外观字体颜色(itext 7)

c# - 将对象作为对象数组传递

c# - 如何连接 ReadOnlyCollection<string> 和 IList<string>

c# - HttpContext.Current.User.Identity.Name 使用 IIS Express 但不是 Visual Studio Development Server 为空

pdf - iTextSharp : Convert PdfObject to PdfStream

php - 用于在 mPDF 中定位嵌套 div 的 CSS 替代方案

c# - iTextPdf 如何分页