如何使用C#程序给PDF文件添加编辑域
PDF文档通常是不能编辑的,但有些时候需要在PDF文档中填写日期或签名之类,就需要在PDF有能编辑的文本域,本文介绍怎样用C#来实现这一功能。
环境
工具:VS2015
语言:C#
操作PDF类库:iTextSharp5.5.10
生成的PDF预览的工具:Skim、福昕阅读器、AcrobatReader
代码实现
获取文档的页数
PdfReaderreader=newPdfReader(@"C:\WorkSpace\1.pdf"); intcount=reader.NumberOfPages;
创建文本域
TextFieldfieldDate=newTextField(stamp.Writer,newiTextSharp.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-LeftHeigth=Top-Bototom
创建文本
Chunkcname=newChunk("Date:",FontFactory.GetFont("Futura",16f,newBaseColor(170,64,0)));
Phrasepname=newPhrase(cname);
PdfContentByteover=stamp.GetOverContent(count);
ColumnText.ShowTextAligned(over,Element.ALIGN_CENTER,pname,400,420,0);
完整代码
publicstaticvoidAddTextField()
{
PdfReaderreader=newPdfReader(@"C:\WorkSpace\1.pdf");
FileStreamout1=newFileStream(@"C:\WorkSpace\2.pdf",FileMode.Create,FileAccess.Write);
PdfStamperstamp=newPdfStamper(reader,out1);
//获得pdf总页数
intcount=reader.NumberOfPages;
TextFieldfieldDate=newTextField(stamp.Writer,newiTextSharp.text.Rectangle(105,100,240,125),"date");
fieldDate.BackgroundColor=BaseColor.WHITE;
fieldDate.BorderWidth=1;
fieldDate.BorderColor=BaseColor.BLACK;
fieldDate.BorderStyle=4;
fieldDate.FontSize=11f;
TextFieldfieldSign=newTextField(stamp.Writer,newiTextSharp.text.Rectangle(430,100,530,125),"sign");
fieldSign.BackgroundColor=BaseColor.WHITE;
fieldSign.BorderWidth=1;
fieldSign.BorderColor=BaseColor.BLACK;
fieldSign.BorderStyle=4;
fieldSign.FontSize=11f;
Chunkcname=newChunk("Date:",FontFactory.GetFont("Futura",16f,newBaseColor(170,64,0)));
Chunkctitle=newChunk("UserSign:",FontFactory.GetFont("Futura",16f,newBaseColor(0,128,128)));
Phrasepname=newPhrase(cname);
Phraseptitle=newPhrase(ctitle);
//PdfContentBye类,用来设置图像和文本的绝对位置
PdfContentByteover=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();
}
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下