如果一張獎狀的 PDF 檔,內容長得如上圖,會不會覺得哪裡怪怪的?沒錯,少了「框線」。
接下來想要透過 Aspose 工具,來把這張 PDF 檔加上框線。而這原理,可以簡單的想成把 PDF 檔案加上底圖。
首先,先找好一個有框的底圖。大概像下面這樣:
![]() |
| BackGround.png |
Document pdfDocument = new Document("PDF來源");
一份 PDF 檔案,可能會有很多頁(Page),所以,透過 Page 物件,可以讓我們指定要控制第幾個頁面。而這裡的頁面標示,則是從 1 開始算起。
Page pdfPage = pdfDocument.Pages[1];
ImageStamp 則是接下來的主角,他就好比我們的橡皮圖章一樣,待會會蓋在每個頁面上。若用圖層的觀點來看,就有所謂的上下之分,這時,可以利用 ImageStamp 的 Background 屬性來決定,決定這個橡皮圖章的內容是要完全蓋過原先的內容,還是只是當個背景。如果需要微調 ImageStamp 的大小,則有 Width、Height 可以設定。
ImageStamp imgStamp = new ImageStamp(strStampFullPath);
完整程式可以簡述如下:
class PdfFunction
{
public void AddBackGroundIMG(string PDFPath)
{
string setupFile = "BackGround.png";
//取得執行路徑
string strExecPath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
//取得檔案的完整路徑
string strStampFullPath = string.Format("{0}\\{1}", strExecPath, setupFile);
//設定 license
Aspose.Pdf.License license = new Aspose.Pdf.License();
license.SetLicense(string.Format("{0}\\{1}",strExecPath , "Aspose.Total.lic"));
//透過 Aspose 的 Document 物件,來取得原先的 PDF 檔案
Document pdfDocument = new Document(PDFPath);
Page pdfPage;
for (int i = 0; i < pdfDocument.Pages.Count; i++)
{
//Aspose 是從 1 開始算的
pdfPage = pdfDocument.Pages[i + 1];
//取得外部圖片並指定為 ImageStamp 格式
ImageStamp imgStamp = new ImageStamp(strStampFullPath);
//將加入的圖片指定設為背景
imgStamp.Background = true;
//設定圖片長寬
imgStamp.Width = 850;
imgStamp.Height = 600;
//將底圖加入到 PDF 頁面
pdfPage.AddStamp(imgStamp);
}
// 產出新檔案
pdfDocument.Save(string.Format("{0}\\{1}", strExecPath, "out.pdf"));
}
}
要使用時,則是如下呼叫:
class Program
{
static void Main(string[] args)
{
string setupFile = "award.pdf";
//取得執行路徑
string strExecPath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
//取得檔案的完整路徑
string strStampFullPath = string.Format("{0}\\{1}", strExecPath, setupFile);
PdfFunction oP = new PdfFunction();
oP.AddBackGroundIMG(setupFile);
}
}
最後,有框的獎狀就會像下面這樣子:
Ref:
01:how to insert a watermark image into existing .pdf



沒有留言:
張貼留言