zoukankan      html  css  js  c++  java
  • C#使用iTextSharp给PDF添加水印

    代码:

    /// <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:WINDOWSFontsSIMFANG.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);
        }
    }
    View Code
  • 相关阅读:
    Atcoder ARC-104
    [ZJOI2019]线段树
    【XR-2】伤痕
    CF1103B Game with modulo
    [BJOI2019]删数
    AT2402 [ARC072D] Dam
    十六、JMeter实战-跨线程调用token
    十五、JMeter实战-关联-JSON提取器和边界值提取器
    十四、JMeter实战-关联获取token
    十三、JMeter实战-关联-正则表达式
  • 原文地址:https://www.cnblogs.com/s0611163/p/5944893.html
Copyright © 2011-2022 走看看