iTextSharp - 从头开始​​创建新PDF时 - 如何添加表单字段?

时间:2012-03-02 21:49:56

标签: asp.net itextsharp

我正在使用iTextSharp,并在内存中创建了一个新文档(我正在组合多个PDF,然后添加一个带有数字签名的新页面。)

然而,我有一点问题。我有我的Document对象,并且所有内容都输出,但是我如何将PdfFormField添加到Document?我必须使用压模吗?这仅存在于内存中,不会保存在任何地方。

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");

我有一个签名块,我想添加到文档的末尾:

 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";

但我无法弄清楚我的生活中如何做document.add(sig),因为它需要IElement

1 个答案:

答案 0 :(得分:3)

以下是使用an example编写的iText book中的the creator of iText从Java转换而来的C#/ ASP.NET版本:

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);
}

如果您看一下Java示例,您会注意到还有签署文档的代码,这是上面的示例中故意遗漏的。在ASP.NET中签名PDF 是一项微不足道的任务。

相关问题