C#使用iTextSharp給PDF添加水印


  昨天利用itextsharp、Spire配合使用為pdf文檔每頁添加水印 發現公司的框架用的.netframework3.5。用上面那個方法,.netframework最低4.0,升級公司框架的版本,導致之前寫過的代碼報錯地方比較多,所以網上找到了該方法,記錄下來,支持.netframework3.5

類庫下載:

直接下載

引入類庫

 

 引入命名空間

using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;

實現:

/// <summary>
/// 添加普通偏轉角度文字水印
/// </summary>
public static void SetWatermark(string filePath, string text)
{
    PdfReader pdfReader = null;
    PdfStamper pdfStamper = null;
    string tempPath = Path.GetDirectoryName(filePath) + Path.GetFileNameWithoutExtension(filePath) + "_temp.pdf";

    try
    {
        pdfReader = new PdfReader(filePath);
        pdfStamper = new PdfStamper(pdfReader, new FileStream(tempPath, 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.3f;
            content.SetGState(gs);
            //content.SetGrayFill(0.3f);
            //開始寫入文本
            content.BeginText();
            content.SetColorFill(BaseColor.GRAY);
            content.SetFontAndSize(font, 30);
            content.SetTextMatrix(0, 0);
            content.ShowTextAligned(Element.ALIGN_CENTER, text, width - 120, height - 120, -45);
            //content.SetColorFill(BaseColor.BLACK);
            //content.SetFontAndSize(font, 8);
            //content.ShowTextAligned(Element.ALIGN_CENTER, waterMarkName, 0, 0, 0);
            content.EndText();
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }
    finally
    {
        if (pdfStamper != null)
            pdfStamper.Close();

        if (pdfReader != null)
            pdfReader.Close();
        System.IO.File.Copy(tempPath, filePath, true);
        System.IO.File.Delete(tempPath);
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM