IText iTextSharp

利用iTextSharp在PDF中添加浮水印及頁碼

蔡雅勤 2018/12/26 15:48:46
8661

利用iTextSharp在PDF中添加浮水印及頁碼


簡介

簡單介紹iTextSharp元件,且透過簡單的操作實例,了解 iTextSharp如何在既有的PDF檔案中,添加浮水印及頁碼。

作者

蔡雅勤


前言

有時候需要在PDF文檔中填寫下載日期資料或增加頁碼之類的需求,或是有時基於個資問題,需要在既有的PDF文檔印上人員名稱或浮水印,我們可以利用iTextSharp來進行操作。

 

建置環境準備

本範例建立於以下版本的環境:

● Visual Studio 2013

●iTextSharp 5.5.13

 

iTextSharp概述

本函式庫原名是iText,主要是支援Java程式語言。之後針對Microsoft .NET C Sharp做了一個版本,也就是我們今天要介紹的iTextSharp。針對PDF檔案的製作與修改,支援的功能如下:

  1. CreateAutomateConvertSignEncrypt
  2. Read
Extract
  3. Update
StampFill outSplit/MergeConvertSignEncrypt

 

實作說明

 1.準備一份PDF檔案及浮水印圖片

PDF檔案如下:

浮水印圖片如下:  

 

2.使用NuGet管理套件安裝iTextSharp

 

 

3.NuGet安裝成功後,可以在參考裡看到iTextSharp

 

4.開始撰寫相關程式碼 

利用上傳檔案的方法,傳入檔案名稱及路徑後,再進行讀取檔案,新增浮水印及頁碼的處理。

主要添加浮水印及頁碼程式請參考如下:

public string UP0010(string FileName,  string ReadPath)
    {
        try
        {          
            string UpFileName;
            //上傳
            UpFileName = FileName;
            string NewUpath = Server.MapPath(@"~\UPLOAD\" + UpFileName);
            PdfReader reader = new PdfReader(ReadPath);
            FileStream out1 = new FileStream(NewUpath, FileMode.Create, FileAccess.Write);
            PdfStamper stamp = new PdfStamper(reader, out1);
            int count1 = reader.NumberOfPages;

            PdfGState pdfgstate = new PdfGState()
            {
                FillOpacity = 0.5f,
                StrokeOpacity = 0.5f
            };

            for (int i = 1; i <= count1; i++)
            {
                Rectangle pagesize = reader.GetPageSizeWithRotation(i); //每頁的Size
                //頁尾的文本
                Chunk ctitle = new Chunk("Page-" + i.ToString().Trim(), FontFactory.GetFont("Futura", 12f, new BaseColor(0, 0, 0)));
                Phrase ptitle = new Phrase(ctitle);
                //浮水印
                string imageUrl = HttpContext.Current.Server.MapPath(@"~/File/logo.png"); //Logo
                Image img = iTextSharp.text.Image.GetInstance(imageUrl);
                img.ScalePercent(20f);  //縮放比例
                img.RotationDegrees = 10; //旋轉角度
                img.SetAbsolutePosition(10, pagesize.Height-40); //設定圖片每頁的絕對位置

                //PdfContentByte類,用設置圖像像和文本的絕對位置
                PdfContentByte over = stamp.GetOverContent(i);
                ColumnText.ShowTextAligned(over, Element.ALIGN_LEFT, ptitle, pagesize.Width / 2, 10, 0); //設定頁尾的絕對位置
                over.SetGState(pdfgstate); //寫入入設定的透明度
                over.AddImage(img); //圖片印上去
            }
            stamp.FormFlattening = true;
            stamp.Close();

            reader.Close();
            out1.Close();
            reader = null;
            stamp = null;
            out1 = null;

            return "上傳成功";
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message.ToString());
        }
    }

 

執行結果如下:

打開PDF文檔可以看到結果文檔上面左邊新增了浮水印,頁尾新增了頁碼。

 

蔡雅勤