`
lexinquan
  • 浏览: 47187 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

Dotnet水印之1:PDF文档加水印图片

阅读更多
添加引用:
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;

/// <summary> 
///  PDF加水印 
/// </summary> 
/// <param name="inputfilepath">源PDF文件</param> 
/// <param name="outputfilepath">加水印后PDF文件 </param> 
/// <param name="ModelPicName">水印文件路径</param> 
/// <param name="top">离顶部距离</param> 
/// <param name="left">离左边距离,如果为负,则为离右边距离</param> 
/// <param name="strMsg">返回信息</param> 
/// <returns>返回</returns> 
public static bool PDFWatermark(string inputfilepath, string outputfilepath, string ModelPicName,float top,float left,ref string strMsg)      
{ 
    FileStream outputStream = null; 
    PdfReader pdfReade = null;
    PdfStamper pdfStamper = null;
    try           
    {         
        //string pass = "zf01"; 
  
        //byte[] passbyteArray = Encoding.ASCII.GetBytes(pass); 
  
        pdfReader= new PdfReader(inputfilepath);    
         
        int numberOfPages = pdfReader.NumberOfPages;      
   
        iTextSharp.text.Rectangle psize = pdfReader.GetPageSize(1);    
       
        float width = psize.Width;          
  
        float height = psize.Height;     
     
        //读取PDF文档 
        outputStream = new FileStream(outputfilepath, FileMode.OpenOrCreate);                 
  
        pdfStamper = new PdfStamper(pdfReader, outputStream);     
      
        PdfContentByte waterMarkContent;              
  
        iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(ModelPicName);                                 
  
        image.GrayFill=20; 
        //水印的位置 
        //image.SetAbsolutePosition((width - image.Width), (height-image.Height));    
        if (left<0) 
        { 
            left=width - image.Width+left; 
        } 
         
        image.SetAbsolutePosition(left,(height-image.Height)-top); 
         
     
        //每一页加水印,也可以设置某一页加水印 
        //for (int i = 1; i <= numberOfPages; i++)              
        //{                    
        waterMarkContent = pdfStamper.GetUnderContent(1);   
  
        waterMarkContent.AddImage(image);        
        //}     
        strMsg="success";
  
    }            
    catch (Exception ex)   
    { 
        strMsg= ex.Message.Trim(); 
        return false;
    }    
    finally 
    { 
  
        if (outputStream!=null) 
            outputStream.Close();

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

        return true; 
    }  
}  
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics