【问题标题】:iTextSharp -- When creating a new PDF from scratch -- how do I add form fields?iTextSharp -- 从头开始​​创建新 PDF 时 -- 如何添加表单域?
【发布时间】:2012-03-02 21:49:55
【问题描述】:

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

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

例如:

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

【问题讨论】:

  • 不要MemoryStream上拨打GetBuffer(),而是拨打ToArray()。前者包括未初始化的字节,这些字节可能/将产生损坏的 PDF。
  • 谢谢。当世界上的每个示例都使用 ToArray 时,我注意到了这种差异(我的错!)。很高兴指出,以免我的坏例子毁了别人:)

标签: asp.net itextsharp


【解决方案1】:

这是从Java转换而来的C#/ASP.NET版本,使用iText book中的an examplethe 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);
}

如果您查看 Java 示例,您会注意到还有用于签署文档的代码,上面的示例特意省略了该代码。在 ASP.NET 中为 PDF 签名不是简单的任务。

【讨论】:

    猜你喜欢
    • 2016-12-18
    • 1970-01-01
    • 1970-01-01
    • 2017-03-23
    • 2021-12-05
    • 1970-01-01
    • 2013-07-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多