1. 程式人生 > >C# iTextSharp 建立PDF水印

C# iTextSharp 建立PDF水印

剛剛有人留言說需要 iTextSharp 建立PDF水印程式碼
那就貼一個以前寫好的。

   public static void SetWatermark(string inputfilepath, string outputfilepath, string waterMarkName)
    {
        PdfReader pdfReader = null;
        PdfStamper pdfStamper = null;
        try
        {
            pdfReader = new PdfReader(inputfilepath);
            pdfStamper = new PdfStamper(pdfReader, new FileStream(outputfilepath, FileMode.Create));
            int total = pdfReader.NumberOfPages + 1;
            iTextSharp.text.Rectangle psize = pdfReader.GetPageSize(1);
            float width = psize.Width;
            float height = psize.Height;
            PdfContentByte content;
            BaseFont font = BaseFont.CreateFont(@"C:\WINDOWS\Fonts\SIMFANG.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            PdfGState gs = new PdfGState();
            for (int i = 1; i < total; i++)
            {
                content = pdfStamper.GetOverContent(i);//在內容上方加水印
                //content = pdfStamper.GetUnderContent(i);//在內容下方加水印
                //透明度
                gs.FillOpacity = 0.6f;
                content.SetGState(gs);
                //content.SetGrayFill(0.3f);
                //開始寫入文字
                content.BeginText();
                content.SetColorFill(BaseColor.GRAY);
                content.SetFontAndSize(font, 50);
                content.SetTextMatrix(0, 0);
                content.ShowTextAligned(Element.ALIGN_CENTER, waterMarkName, width / 2 - 50, height / 2 - 50, 45);

                content.EndText();
            }
            for (int i = 1; i < total; i++)
            {
                /* 開始增加頁碼 */

                content = pdfStamper.GetOverContent(i);
                gs.FillOpacity = 0.8f;

                content.SetGState(gs);
                content.BeginText();
                content.SetColorFill(BaseColor.BLACK);
                content.SetFontAndSize(font, 12);
                content.ShowTextAligned(Element.ALIGN_CENTER, "第" + i.ToString() + "頁 " + "共" + (total - 1).ToString() + "頁", width / 2 - 5, 35, 0);
                content.EndText();
            }

        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {

            if (pdfStamper != null)
                pdfStamper.Close();

            if (pdfReader != null)
                pdfReader.Close();
        }
    }