Подтвердить что ты не робот

Как добавить поле формы в существующий pdf с помощью itextsharp?

Как добавить поле формы в существующий pdf с помощью itextsharp?

У меня есть существующий pdf-документ, я бы хотел добавить к нему поля формы, не создавая копию и не выписывая новый документ.

4b9b3361

Ответ 1

После дальнейшего пересмотра решение на поле опрокинуто. Оказывается, если вы формируете выравнивание шаблона, поля не отображаются в результирующем документе (потому что у них нет настроек "внешнего вида" ). BTW, сглаживание формы предотвращает дальнейшие изменения поля формы. Теперь мы можем добавить внешний вид в форму, однако, более простой способ - использовать класс 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();
}

Ответ 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();
}

Ответ 3

Используя 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);