文檔中添加印章可以起一定的作用,比如,防止檔案随意被使用,或者確定文檔内容的安全性和權威性。C#添加圖檔印章其實也有很多實作方法,這裡我使用的是免費的第三方軟體 Free Spire.PDF for .NET
,向大家闡述如何以程式設計的方式在PDF檔案中添加圖檔印章。
具體步驟如下:
在此之前,我們需要添加dll檔案作為引用。添加引用 → 浏覽 → Spire.PDF folder → Bin → .NET 2.0/3.5/4.0/4.5/4.0 ClientProfile → Spire.Pdf.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文檔:
![](https://img.laitimes.com/img/_0nNw4CM6IyYiwiM6ICdiwiIn5GcugjYklDO2EDZ3EjZ5cjY0EmZ1IWZ0gTYjZjZzQzYyQjYfdWbp9CXt92Yu4GZjlGbh5SZslmZxl3Lc9CX6MHc0RHaiojIsJye.png)
運作後的pdf文檔:
全部代碼:
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 }
View Code
通過此元件,我們除了可以快速地在PDF檔案中添加圖檔印章,還可以在PDF檔案中
添加圖檔和文字水印以及
添加圖檔背景,可以參考一下,也許對你有幫助。謝謝浏覽。