如何使用itextsharp将表单字段添加到现有pdf?

时间:2009-12-04 18:50:28

标签: itextsharp

如何使用itextsharp将表单字段添加到现有pdf中?

我有一个现有的pdf文档,我想在不创建副本和写出新文档的情况下向其中添加表单字段。

3 个答案:

答案 0 :(得分:7)

经过进一步审查,该领域的裁决被推翻。如果你将压模压平,那么结果文件中没有显示字段(因为它们缺少“外观”设置)。顺便说一句,表单展平会阻止表单字段的进一步编辑。现在我们可以为表单添加外观,但是,更简单的方法是使用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();
}

答案 1 :(得分:2)

我挣扎了一段时间,所以我想发布问题&答案

使用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();
}

答案 2 :(得分:1)

使用 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);