Skip to content

Instantly share code, notes, and snippets.

@adamzuckerman
Created October 13, 2015 20:26
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save adamzuckerman/77290668705122b7aff6 to your computer and use it in GitHub Desktop.
Save adamzuckerman/77290668705122b7aff6 to your computer and use it in GitHub Desktop.
Using iTextSharp to create a TextField on an existing PDF
using iTextSharp.text;
using iTextSharp.text.pdf;
private static void Main(string[] args)
{
const string templateFilename = "template.pdf";
const string outputFilename = "output.pdf";
using (Stream inputPdf = new FileStream(templateFilename, FileMode.Open, FileAccess.Read, FileShare.Read))
{
using (Stream outputPdf = new FileStream(outputFilename, FileMode.Create, FileAccess.Write, FileShare.None))
{
var reader = new PdfReader(inputPdf);
var stamper = new PdfStamper(reader, outputPdf);
// Create a BaseFont representation of an internal font - Helvetica,
// using the Latin code page for Windows
var bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, false);
// This field will appear near the bottom left of the page (based on the Rectangle)
var tf = new TextField(stamper.Writer, new Rectangle(10, 10, 154, 28), "newTextField")
{
Alignment = Element.ALIGN_CENTER & Element.ALIGN_MIDDLE,
BackgroundColor = GrayColor.GRAYBLACK,
BorderColor = Color.GREEN,
BorderStyle = PdfBorderDictionary.STYLE_SOLID,
DefaultText = "This is a new text field.",
Font = bf,
FontSize = 7,
MaxCharacterLength = 25,
Options = TextField.REQUIRED | TextField.MULTILINE,
// The rotation only affects the text in the field, not the field location
Rotation = 90,
Text = "This is the assigned value."
};
// Add the TextField to the PDF on page 1
var pageNumber = 1;
stamper.AddAnnotation(tf.GetTextField(), pageNumber);
// Save the changes to file
stamper.Close();
}
}
}
@Richard-Woessner
Copy link

Thank you so much man. This helped me out a ton

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment