如何使用 itextsharp 向现有 pdf 添加表单域?
我有一个现有的 pdf 文档,我想在不创建副本和写出新文档的情况下向其中添加表单域。
经过进一步审查,该领域的裁决被推翻。事实证明,如果您将压模压平,则字段不会显示在结果文档上(因为它们缺少“外观”设置)。顺便说一句,表单展平可防止进一步编辑表单字段。现在我们可以为表单添加外观,但是,更简单的方法是使用 TextField 类,而不必担心显式设置“外观”对象。
public void ABetterWayToAddFormFieldToExistingPDF( )
{
PdfReader reader = new PdfReader(@"c:\existing.pdf");
FileStream out = new FileStream(@"C:\existingPlusFields.pdf", FileMode.Create, FileAccess.Write);
PdfStamper stamp = new PdfStamper(reader, out);
TextField field = new TextField(stamp.Writer, new iTextSharp.text.Rectangle(40, 500, 360, 530), "some_text");
// add the field here, the second param is the page you want it on
stamp.AddAnnotation(field.GetTextField(), 1);
stamp.FormFlattening = true; // lock fields and prevent further edits.
stamp.Close();
}
我为此苦苦挣扎了一段时间,所以我想我会发布问题和答案
使用 PdfStamper itext 类是关键。(我想这确实会复制,但它比使用 itext PdfCopy 类要干净得多)。
public void AddFormFieldToExistingPDF( )
{
PdfReader reader = new PdfReader(@"c:\existing.pdf");
FileStream out = new FileStream(@"C:\existingPlusFields.pdf", FileMode.Create, FileAccess.Write);
PdfStamper stamp = new PdfStamper(reader, out);
PdfFormField field = PdfFormField.CreateTextField(stamp.Writer, false, false, 50);
// set a field w/some position and size
field.SetWidget(new iTextSharp.text.Rectangle(40, 500, 360, 530),
PdfAnnotation.HIGHLIGHT_INVERT);
field.SetFieldFlags(PdfAnnotation.FLAGS_PRINT);
field.FieldName = "some_field";
// add the field here, the second param is the page you want it on
stamp.AddAnnotation(field, 1);
stamp.Close();
}
使用pdfStamper你可以完成它。
PdfStamper Stamper= new PdfStamper(new PdfReader(sourcefile), File.Create(NewOutputFile));
TextField moreText = new TextField(Stamper.Writer,
new iTextSharp.text.Rectangle(20, 20, 590, 780), "moreText");
moreText.Visibility = TextField.VISIBLE_BUT_DOES_NOT_PRINT;
moreText.Text = "Use this space for any additional information";
moreText.Options = (TextField.MULTILINE);
PdfFormField Fieldtxt = moreText.GetTextField();
Stamper.AddAnnotation(Fieldtxt, n);