I have followed the steps to create annotations and apply redaction using iText 5.5.9. Here is my code:
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();
}
However, I always receive the following exception on PdfCleanUpProcessor construction:
Object reference not set to an instance of an object. at iTextSharp.xtra.iTextSharp.text.pdf.pdfcleanup.PdfCleanUpProcessor.ExtractLocationsFromRedactAnnots(Int32 page, PdfDictionary pageDict) at iTextSharp.xtra.iTextSharp.text.pdf.pdfcleanup.PdfCleanUpProcessor.ExtractLocationsFromRedactAnnots() at iTextSharp.xtra.iTextSharp.text.pdf.pdfcleanup.PdfCleanUpProcessor..ctor(PdfStamper pdfStamper)
It appears that there is a null reference produced in extractLocationsFromRedactAnnots on the assignment of annotDict, so the next line throws the exception:
/**
* 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;
}
Any idea why this is happening? An example PDF is here.