PDF documents are usually not editable, but sometimes you need to fill in dates or signatures in PDF documents, so you need to have an editable text field in PDF. This article introduces how to use C# to implement this function.
environment
Tools: VS2015
Language: C#
Operate PDF class library: iTextSharp 5.5.10
Tools for generating PDF previews: Skim, Foxit Reader, Acrobat Reader
Code implementation
Get the number of pages of the document
PdfReader reader = new PdfReader(@"C:\WorkSpace\"); int count = ;
Create a text field
TextField fieldDate = new TextField(, new (105, 100, 240, 125), "date"); = ;= 1; = ;= 4; = 11f;
(105, 100, 240, 125) Used to set the position of the text field, the four parameters are: llx, lly, urx, and ury:
llx is Left, lly is Bottom, urx is Right, ury is Top
Where: Width=Right - Left Heigth = Top - Bototom
Create text
Chunk cname = new Chunk("Date:", ("Futura", 16f,new BaseColor(170,64,0))); Phrase pname = new Phrase(cname); PdfContentByte over = (count); (over, Element.ALIGN_CENTER, pname, 400, 420, 0);
Complete code
public static void AddTextField() { PdfReader reader = new PdfReader(@"C:\WorkSpace\"); FileStream out1 = new FileStream(@"C:\WorkSpace\", , ); PdfStamper stamp = new PdfStamper(reader, out1); //Get the total number of pages of pdf int count = ; TextField fieldDate = new TextField(, new (105, 100, 240, 125), "date"); = ; = 1; = ; = 4; = 11f; TextField fieldSign = new TextField(, new (430, 100, 530, 125), "sign"); = ; = 1; = ; = 4; = 11f; Chunk cname = new Chunk("Date:", ("Futura", 16f,new BaseColor(170,64,0))); Chunk ctitle = new Chunk("User Sign:", ("Futura", 16f, new BaseColor(0, 128, 128))); Phrase pname = new Phrase(cname); Phrase ptitle = new Phrase(ctitle); //PdfContentBye class, used to set the absolute position of image and text PdfContentByte over = (count); (over, Element.ALIGN_CENTER, pname, 400, 420, 0); (over, Element.ALIGN_CENTER, ptitle, 400, 350, 0); ((), count); ((), count); = true; (); }