文档中添加印章可以起一定的作用,比如,防止文件随意被使用,或者确保文档内容的安全性和权威性。C# 添加图片印章其实也有很多实现方法,这里我使用的是免费的第三方软件,向大家阐述如何以编程的方式在 PDF 文件中添加图片印章。
具体步骤如下:
在此之前,我们需要添加 dll 文件作为引用。添加引用 → 浏览 → Spire.XLS folder → Bin → .NET 2.0/3.5/4.0/4.5/4.0 ClientProfile → Spire.XLS.dll.
第一步:首先新建一个 PDF 文档对象并加载要添加印章的文档.
- PdfDocument doc = new PdfDocument();
- doc.LoadFromFile(@"E:\Visual Studio\Sample\template7\sample.pdf");
第二步:获取文档的第一页.
- PdfPageBase page = doc.Pages[0];
第三步:新建一个 PdfRubberStampAnnotation 对象,指定其注释的范围和大小。
- PdfRubberStampAnnotation loStamp = new PdfRubberStampAnnotation(new RectangleF(new PointF( - 5, -5), new SizeF(60, 60)));
第四步:实例化一个 PdfAppearance 对象。
- PdfAppearance loApprearance = new PdfAppearance(loStamp);
第五步:加载用作印章的图片
- PdfImage image = PdfImage.FromFile(@"C:\Users\Administrator\Pictures\sample.jpg");
第六步:新建一个 PDF 模板,并在模板里绘制图片
- PdfTemplate template = new PdfTemplate(160, 160);
- template.Graphics.DrawImage(image, 0, 0);
- loApprearance.Normal = template;
- loStamp.Appearance = loApprearance;
第 7 步:在 PDF 文档添加印章
- page.AnnotationsWidget.Add(loStamp);
第八步:保存文档
- string output = "ImageStamp.pdf";
- doc.SaveToFile(output);
运行前的 pdf 文档:
运行后的 pdf 文档:
全部代码:
View Code
- 1 using System;
- 2 using System.Drawing;
- 3 using System.Windows.Forms;
- 4 using Spire.Pdf;
- 5 using Spire.Pdf.Annotations;
- 6 using Spire.Pdf.Annotations.Appearance;
- 7 using Spire.Pdf.Graphics;
- 8 9 namespace addanimagestamptoaPDF_file 10 {
- 11 public partial class Form1: Form 12 {
- 13 public Form1() 14 {
- 15 InitializeComponent();
- 16
- }
- 17 18 private void button1_Click(object sender, EventArgs e) 19 {
- 20 PdfDocument doc = new PdfDocument();
- 21 doc.LoadFromFile(@"E:\Visual Studio\Sample\template7\sample.pdf");
- 22 23 PdfPageBase page = doc.Pages[0];
- 24 25 PdfRubberStampAnnotation loStamp = new PdfRubberStampAnnotation(new RectangleF(new PointF( - 5, -5), new SizeF(60, 60)));
- 26 PdfAppearance loApprearance = new PdfAppearance(loStamp);
- 27 PdfImage image = PdfImage.FromFile(@"C:\Users\Administrator\Pictures\sample.jpg");
- 28 29 PdfTemplate template = new PdfTemplate(160, 160);
- 30 template.Graphics.DrawImage(image, 0, 0);
- 31 loApprearance.Normal = template;
- 32 loStamp.Appearance = loApprearance;
- 33 34 page.AnnotationsWidget.Add(loStamp);
- 35 36 string output = "ImageStamp.pdf";
- 37 doc.SaveToFile(output);
- 38 39
- }
- 40
- }
- 41
- }
通过此组件,我们除了可以快速地在 PDF 文件中添加图片印章,还可以在 PDF 文件中以及,可以参考一下,也许对你有帮助。谢谢浏览。
来源: http://www.cnblogs.com/Yesi/p/6141635.html