如何運用C#順序給PDF文件添加編輯域。本站提示廣大學習愛好者:(如何運用C#順序給PDF文件添加編輯域)文章只能為提供參考,不一定能成為您想要的結果。以下是如何運用C#順序給PDF文件添加編輯域正文
PDF文檔通常是不能編輯的,但有些時分需求在PDF文檔中填寫日期或簽名之類,就需求在PDF有能編輯的文本域,本文引見怎樣用C#來完成這一功用。
環境
工具:VS2015
言語:C#
操作PDF類庫:iTextSharp 5.5.10
生成的PDF預覽的工具:Skim、福昕閱讀器、Acrobat Reader
代碼完成
獲取文檔的頁數
PdfReader reader = new PdfReader(@"C:\WorkSpace\1.pdf"); int count = reader.NumberOfPages;
創立文本域
TextField fieldDate = new TextField(stamp.Writer, new iTextSharp.text.Rectangle(105, 100, 240, 125), "date"); fieldDate.BackgroundColor= BaseColor.WHITE;fieldDate.BorderWidth= 1; fieldDate.BorderColor= BaseColor.BLACK;fieldDate.BorderStyle= 4; fieldDate.FontSize = 11f;
iTextSharp.text.Rectangle(105, 100, 240, 125) 用來設置文本域的地位,四個參數辨別為:llx、lly、urx、ury:
llx 為Left ,lly 為Bottom,urx 為Right,ury 為Top
其中:Width=Right - Left Heigth = Top - Bototom
創立文本
Chunk cname = new Chunk("Date:", FontFactory.GetFont("Futura", 16f,new BaseColor(170,64,0)));
Phrase pname = new Phrase(cname);
PdfContentByte over = stamp.GetOverContent(count);
ColumnText.ShowTextAligned(over, Element.ALIGN_CENTER, pname, 400, 420, 0);
完好代碼
public static void AddTextField()
{
PdfReader reader = new PdfReader(@"C:\WorkSpace\1.pdf");
FileStream out1 = new FileStream(@"C:\WorkSpace\2.pdf", FileMode.Create, FileAccess.Write);
PdfStamper stamp = new PdfStamper(reader, out1);
//取得pdf總頁數
int count = reader.NumberOfPages;
TextField fieldDate = new TextField(stamp.Writer, new iTextSharp.text.Rectangle(105, 100, 240, 125), "date");
fieldDate.BackgroundColor = BaseColor.WHITE;
fieldDate.BorderWidth = 1;
fieldDate.BorderColor = BaseColor.BLACK;
fieldDate.BorderStyle = 4;
fieldDate.FontSize = 11f;
TextField fieldSign = new TextField(stamp.Writer, new iTextSharp.text.Rectangle(430, 100, 530, 125), "sign");
fieldSign.BackgroundColor = BaseColor.WHITE;
fieldSign.BorderWidth = 1;
fieldSign.BorderColor = BaseColor.BLACK;
fieldSign.BorderStyle = 4;
fieldSign.FontSize = 11f;
Chunk cname = new Chunk("Date:", FontFactory.GetFont("Futura", 16f,new BaseColor(170,64,0)));
Chunk ctitle = new Chunk("User Sign:", FontFactory.GetFont("Futura", 16f, new BaseColor(0, 128, 128)));
Phrase pname = new Phrase(cname);
Phrase ptitle = new Phrase(ctitle);
//PdfContentBye類,用來設置圖像和文本的相對地位
PdfContentByte over = stamp.GetOverContent(count);
ColumnText.ShowTextAligned(over, Element.ALIGN_CENTER, pname, 400, 420, 0);
ColumnText.ShowTextAligned(over, Element.ALIGN_CENTER, ptitle, 400, 350, 0);
stamp.AddAnnotation(fieldDate.GetTextField(), count);
stamp.AddAnnotation(fieldSign.GetTextField(), count);
stamp.FormFlattening = true;
stamp.Close();
}