// Add annotation to PDF using iTextSharp
private void addTextAnnotationToPDF(string filePath, string contents, int pageNum, int x, int y, int width, int height)
{
PdfReader pdfReader = null;
PdfStamper pdfStamp = null;
try
{
using (var inStream = new FileStream(filePath, FileMode.Open))
{
pdfReader = new PdfReader(inStream);
}
using (var outStream = new FileStream(filePath, FileMode.Create))
{
pdfStamp = new PdfStamper(pdfReader, outStream, (char)0, true);
var rect = new iTextSharp.text.Rectangle((float)x, (float)y, (float)x + width, (float)y + height);
// Generating the annotation's appearance using a TextField
TextField textField = new TextField(pdfStamp.Writer, rect, null);
textField.Text = contents;
textField.FontSize = 8;
textField.TextColor = BaseColor.DARK_GRAY;
textField.BackgroundColor = new BaseColor(Color.LightGoldenrodYellow);
textField.BorderColor = new BaseColor(Color.BurlyWood);
textField.Options = TextField.MULTILINE;
textField.SetExtraMargin(2f, 2f);
textField.Alignment = Element.ALIGN_TOP | Element.ALIGN_LEFT;
PdfAppearance appearance = textField.GetAppearance();
// Create the annotation
PdfAnnotation annotation = PdfAnnotation.CreateFreeText(pdfStamp.Writer, rect, null, new PdfContentByte(null));
annotation.SetAppearance(PdfName.N, appearance);
annotation.Flags = PdfAnnotation.FLAGS_READONLY | PdfAnnotation.FLAGS_LOCKED | PdfAnnotation.FLAGS_PRINT;
annotation.Put(PdfName.NM, new PdfString(Guid.NewGuid().ToString()));
// Add annotation to PDF
pdfStamp.AddAnnotation(annotation, pageNum);
pdfStamp.Close();
}
}
catch (Exception ex)
{
throw new Exception("Could not add signature image to PDF with error: " + ex.Message);
}
}