Add text field to PDF

Manipulate PDF, PDF forms, Shapes
4/13/2011

Downloads

Code sample that shows how to add a text field to an existing PDF document.

Add text field to an existing PDF document

This code sample illustrates how you can add TextFields to your PDF. Do take note that you need to add a Widget to your document; in MVC terms the textfield is the model and the Widget is the view.

Document document = new Document();
Page page = new Page( PageSize.Letter );
document.Pages.Add( page );

TextField textField = new TextField( "text1" );
textField.Value = "Hello!";
document.Fields.Add( textField );

Widget widget = new Widget( 200, 400, 200, 50 );
widget.FontSize = 0; // auto-size
widget.TextColor = RgbColor.Red;
widget.BorderColor = RgbColor.Black;
widget.BorderStyle = BorderStyle.Solid;
widget.BorderWidth = 2;
textField.Widgets.Add( widget );
page.Widgets.Add( widget );
         
using ( FileStream file = new FileStream("addtextfield.pdf", FileMode.Create, FileAccess.Write))
{
    document.Write( file );
}
Dim document As New Document()
Dim page As New Page(PageSize.Letter)
document.Pages.Add(page)

Dim textField As New TextField("text1")
textField.Value = "Hello!"
document.Fields.Add(textField)

Dim widget As New Widget(200, 400, 200, 50)
widget.FontSize = 0
' auto-size
widget.TextColor = RgbColor.Red
widget.BorderColor = RgbColor.Black
widget.BorderStyle = BorderStyle.Solid
widget.BorderWidth = 2
textField.Widgets.Add(widget)
page.Widgets.Add(widget)

Using file As New FileStream("addtextfield.pdf", FileMode.Create, FileAccess.Write)
    document.Write(file)
End Using