欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

如何使用C#程序给PDF文件添加编辑域

程序员文章站 2022-03-14 18:08:43
pdf文档通常是不能编辑的,但有些时候需要在pdf文档中填写日期或签名之类,就需要在pdf有能编辑的文本域,本文介绍怎样用c#来实现这一功能。 环境 工具:vs2015...

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();
}