我已按照步骤创建注释并使用 iText 5.5.9 应用编辑。这是我的代码:
using (var stamper = new PdfStamper(pdfReader, new FileStream(newFilePath, FileMode.Create)))
{
// Redact the values.
var pdfAnot1 = new PdfAnnotation(stamper.Writer, new Rectangle(165f, 685f, 320f, 702f));
pdfAnot1.Title = "First Page";
pdfAnot1.Put(PdfName.SUBTYPE, PdfName.REDACT);
pdfAnot1.Put(PdfName.IC, new PdfArray(new[] { 0f, 0f, 0f }));
pdfAnot1.Put(PdfName.OC, new PdfArray(new[] { 1f, 0f, 0f })); // red outline
stamper.AddAnnotation(pdfAnot1, 1);
for (var i = 1; i <= pdfReader.NumberOfPages; i++)
{
var pdfAnot2 = new PdfAnnotation(stamper.Writer, new Rectangle(220f, 752f, 420f, 768f));
pdfAnot2.Title = "Header";
pdfAnot2.Put(PdfName.SUBTYPE, PdfName.REDACT);
pdfAnot2.Put(PdfName.IC, new PdfArray(new[] { 0f, 0f, 0f }));
pdfAnot2.Put(PdfName.OC, new PdfArray(new[] { 1f, 0f, 0f })); // red outline
stamper.AddAnnotation(pdfAnot2, i);
}
var cleaner = new PdfCleanUpProcessor(stamper);
cleaner.CleanUp();
}
但是,我总是在 PdfCleanUpProcessor 构造中收到以下异常:
你调用的对象是空的。在 iTextSharp.xtra.iTextSharp.text.pdf.pdfcleanup.PdfCleanUpProcessor.ExtractLocationsFromRedactAnnots() 在 iTextSharp.xtra.iTextSharp.text 的 iTextSharp.xtra.iTextSharp.text.pdf.pdfcleanup.PdfCleanUpProcessor.ExtractLocationsFromRedactAnnots(Int32 页,PdfDictionary pageDict)。 pdf.pdfcleanup.PdfCleanUpProcessor..ctor(PdfStamper pdfStamper)
在 annotDict 的分配上,extractLocationsFromRedactAnnots 中似乎产生了一个空引用,因此下一行引发了异常:
/**
* Extracts locations from the redact annotations contained in the document and applied to the given page.
*/
private IList<PdfCleanUpLocation> ExtractLocationsFromRedactAnnots(int page, PdfDictionary pageDict) {
List<PdfCleanUpLocation> locations = new List<PdfCleanUpLocation>();
if (pageDict.Contains(PdfName.ANNOTS)) {
PdfArray annotsArray = pageDict.GetAsArray(PdfName.ANNOTS);
for (int i = 0; i < annotsArray.Size; ++i) {
PdfIndirectReference annotIndirRef = annotsArray.GetAsIndirectObject(i);
PdfDictionary annotDict = annotsArray.GetAsDict(i);
PdfName annotSubtype = annotDict.GetAsName(PdfName.SUBTYPE);
if (annotSubtype.Equals(PdfName.REDACT)) {
SaveRedactAnnotIndirRef(page, annotIndirRef.ToString());
locations.AddRange(ExtractLocationsFromRedactAnnot(page, i, annotDict));
}
}
}
return locations;
}
知道为什么会这样吗?一个示例 PDF 在这里。