Programmatically Insert Editable Textbox in PDF

Textbox is one type of form fields in PDF, which allows users to enter data into PDF without any editing software. It is commonly used in a document to obtain information of the readers. This article presents how to insert editable textbox in a PDF programmatically using free PDF API in C#.

This PDF library provides a class of PdfTextBoxField, initialize a new object of the class and set it properties like Bounds, BounderWidth, then you can add the textbox to PDF document by Form.Fields.Add() method.

Using the code

//Create a new object of PdfDoument, insert a page
PdfDocument doc = new PdfDocument();
PdfPageBase page = doc.Pages.Add(PdfPageSize.A4, new PdfMargins());
//Set font, brush
PdfFont font = new PdfFont(PdfFontFamily.TimesRoman, 12f, PdfFontStyle.Bold);
PdfBrush brush = PdfBrushes.Black;
float x = 50;
float y = 50;
float tempX = 0;
//Draw sting in Pdf
string text = "Phone Number: ";
page.Canvas.DrawString(text, font, brush, x, y);
//Insert textbox
tempX = font.MeasureString(text).Width + x + 15;
PdfTextBoxField textbox = new PdfTextBoxField(page, "TextBox");
textbox.Bounds = new RectangleF(tempX, y, 100, 15);
textbox.BorderWidth = 0.75f;
textbox.BorderStyle = PdfBorderStyle.Solid;doc.Form.Fields.Add(textbox);
//Add a tooltip to textbox
doc.Form.Fields["TextBox"].ToolTip = "Please insert a valid phone Number";
doc.SaveToFile("sample.pdf", FileFormat.PDF); 




Author: janewdaisy

.NET Program Beginner. Share methods about how to use C#/VB.NET to export data, operate Word, Excel, PDF and other useful skills.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s