Yablargo
Yablargo

Reputation: 3596

iTextSharp -- When creating a new PDF from scratch -- how do I add form fields?

I am using iTextSharp, and have a new document being created in memory (I am combining multiple PDFs, then adding a new page with a digital signature on it.)

I have a bit of a problem however. I have my Document object, and everything outputs, but how the heck do I add a PdfFormField to a Document? Do I have to use the stamper? This exists only in memory and is not saved anywhere.

e.g:

Document document = new Document();
MemoryStream output = new MemoryStream();

try
{
    PdfWriter writer = PdfWriter.GetInstance(document, output);

    document.Open();
    PdfContentByte content = writer.DirectContent;

    // .... content adds a bunch of pages in
}
finally
{
    document.Close();
}

return File(output.GetBuffer(), "application/pdf",
            "MRF-" + receipt.OrderNumber + ".pdf");

I have a signature block as such that I want to add to the end of the document:

 PdfFormField sig = PdfFormField.CreateSignature(writer);
 sig.SetWidget(new iTextSharp.text.Rectangle(100, 100, 250, 150), null);
 sig.Flags = PdfAnnotation.FLAGS_PRINT;
 sig.Put(PdfName.DA, new PdfString("/Helv 0 Tf 0 g"));
 sig.FieldName = "Signature1";

But I can't figure out for the life of me how to do something like document.add(sig) as it needs an IElement.

Upvotes: 3

Views: 2734

Answers (1)

goTo-devNull
goTo-devNull

Reputation: 9372

Here's is the C#/ASP.NET version converted from Java, using an example from the iText book written by the creator of iText:

Response.ContentType = "application/pdf";
Response.AddHeader(
  "Content-Disposition", "attachment; filename=signatureTest.pdf"
);        
using (Document document = new Document()) {
  PdfWriter writer = PdfWriter.GetInstance(document, Response.OutputStream);
  document.Open();
  document.Add(new Paragraph("A paragraph"));
  PdfFormField sig = PdfFormField.CreateSignature(writer);
  sig.SetWidget(new Rectangle(100, 100, 250, 150), null);
  sig.FieldName = "testSignature";
  sig.Flags = PdfAnnotation.FLAGS_PRINT;
  sig.SetPage();
  sig.MKBorderColor = BaseColor.BLACK;
  sig.MKBackgroundColor = BaseColor.WHITE;
  PdfAppearance appearance = PdfAppearance.CreateAppearance(writer, 72, 48);
  appearance.Rectangle(0.5f, 0.5f, 71.5f, 47.5f);
  appearance.Stroke();
  sig.SetAppearance(
    PdfAnnotation.APPEARANCE_NORMAL, appearance
  );
  writer.AddAnnotation(sig);
}

If you take a look at the Java example you'll notice there is also code to sign the document, which is purposely left out of the example above. Signing PDF in ASP.NET is not a trivial task.

Upvotes: 3

Related Questions