如何使用C#在PDF文件添加图片印章

时间:2021-11-05 14:51:52

文档中添加印章可以起一定的作用,比如,防止文件随意被使用,或者确保文档内容的安全性和权威性。c#添加图片印章其实也有很多实现方法,这里我使用的是免费的第三方软件free spire.pdf,向大家阐述如何以编程的方式在pdf文件中添加图片印章。

具体步骤如下:

在此之前,我们需要添加dll文件作为引用。添加引用 → 浏览 → spire.xls folder → bin → .net 2.0/3.5/4.0/4.5/4.0 clientprofile → spire.xls.dll.

第一步:首先新建一个pdf文档对象并加载要添加印章的文档。

?
1
2
pdfdocument doc = new pdfdocument();
doc.loadfromfile(@"e:\visual studio\sample\template7\sample.pdf");

第二步:获取文档的第一页。

?
1
pdfpagebase page = doc.pages[0];

第三步:新建一个pdfrubberstampannotation对象,指定其注释的范围和大小。

?
1
pdfrubberstampannotation lostamp = new pdfrubberstampannotation(new rectanglef(new pointf(-5,-5), new sizef(60, 60)));

第四步:实例化一个pdfappearance对象。  

?
1
pdfappearance loapprearance = new pdfappearance(lostamp);

第五步:加载用作印章的图片。

?
1
pdfimage image = pdfimage.fromfile(@"c:\users\administrator\pictures\sample.jpg");

第六步:新建一个pdf模板,并在模板里绘制图片。

?
1
2
3
4
pdftemplate template = new pdftemplate(160, 160);
template.graphics.drawimage(image, 0, 0);
loapprearance.normal = template;
lostamp.appearance = loapprearance;

第7步:在pdf文档添加印章。

?
1
page.annotationswidget.add(lostamp);

第八步:保存文档。

?
1
2
string output = "imagestamp.pdf";
doc.savetofile(output);

运行前的pdf文档:

如何使用C#在PDF文件添加图片印章

运行后的pdf文档:

如何使用C#在PDF文件添加图片印章

全部代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
using system;
using system.drawing;
using system.windows.forms;
using spire.pdf;
using spire.pdf.annotations;
using spire.pdf.annotations.appearance;
using spire.pdf.graphics;
 
namespace addanimagestamptoapdf_file
{
  public partial class form1 : form
  {
    public form1()
    {
      initializecomponent();
    }
 
    private void button1_click(object sender, eventargs e)
    {
      pdfdocument doc = new pdfdocument();
      doc.loadfromfile(@"e:\visual studio\sample\template7\sample.pdf");
 
      pdfpagebase page = doc.pages[0];
      
      pdfrubberstampannotation lostamp = new pdfrubberstampannotation(new rectanglef(new pointf(-5, -5), new sizef(60, 60)));
      pdfappearance loapprearance = new pdfappearance(lostamp);
      pdfimage image = pdfimage.fromfile(@"c:\users\administrator\pictures\sample.jpg");
 
      pdftemplate template = new pdftemplate(160, 160);
      template.graphics.drawimage(image, 0,0);
      loapprearance.normal = template;
      lostamp.appearance = loapprearance;
        
      page.annotationswidget.add(lostamp);
 
      string output = "imagestamp.pdf";
      doc.savetofile(output);
  
    }
  }
}

通过此组件,我们除了可以快速地在pdf文件中添加图片印章,还可以在pdf文件中添加图片和文字水印以及添加图片背景,可以参考一下,也许对你有帮助。谢谢浏览。