zoukankan      html  css  js  c++  java
  • 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: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);
        }
    }
  • 相关阅读:
    Golang error 的突围
    深度解密Go语言之 scheduler
    深度解密Go语言之channel
    如何打造一份优雅的简历?
    Go 程序是怎样跑起来的
    曹大谈内存重排
    从零开始使用 Webpack 搭建 Vue 开发环境
    纯样式无脚本无图片自定义单/复选框
    从零开始使用 Webpack 搭建 Vue3 开发环境
    JS遍历对象的几种方法
  • 原文地址:https://www.cnblogs.com/chenyanbin/p/11769534.html
Copyright © 2011-2022 走看看