Answer 1: Creating redaction annotations
iText is a toolbox that gives you the power to create any object you want. You are using a convenience method to create a Text annotation. That's scratching the surface.
You can use iText to create any type of annotation you want, because the PdfAnnotation
class extends the PdfDictionary
class.
This is explained in chapter 7 of my book "iText in Action - Second edition". GenericAnnotations is the example that illustrates this functionality.
If we port this example to C#, we have:
PdfAnnotation annotation = new PdfAnnotation(writer, rect);
annotation.Title = "Text annotation";
annotation.Put(PdfName.SUBTYPE, PdfName.TEXT);
annotation.Put(PdfName.OPEN, PdfBoolean.PDFFALSE);
annotation.Put(PdfName.CONTENTS,
new PdfString(string.Format("Icon: {0}", text))
);
annotation.Put(PdfName.NAME, new PdfName(text));
writer.AddAnnotation(annotation);
This is a manual way to create a text annotation. You want a Redact
annotations, so you'll need something like this:
PdfAnnotation annotation = new PdfAnnotation(writer, rect);
annotation.Put(PdfName.SUBTYPE, new PdfName("Redact"));
writer.AddAnnotation(annotation);
You can use the Put()
method to add all the other keys you need for the annotation.
Answer 2: How to "apply" a redaction annotation
The second question requires the itext-xtra.jar (an extra jar shipped with iText) and you need at least iText 5.5.4. The approach to add opaque rectangles doesn't apply redaction: the redacted content is merely covered, not removed. You can still select the text and copy/paste it. If you're not careful, you risk ending up with a so-called PDF Blackout Folly. See for instance the NSA / AT&T scandal.
Suppose that you have a file to which you added some redaction annotations: page229_redacted.pdf
We can now use this code to remove the content marked by the redaction annotations:
public void manipulatePdf(String src, String dest) throws IOException, DocumentException {
PdfReader reader = new PdfReader(src);
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
PdfCleanUpProcessor cleaner = new PdfCleanUpProcessor(stamper);
cleaner.cleanUp();
stamper.close();
reader.close();
}
This results in the following PDF: page229_apply_redacted.pdf
As you can see, the red rectangle borders are replaced by filled black rectangles. If you try to select the original text, you'll notice that is is no longer present.