C#中pdf生成图片文字水印类的实现实例

这篇文章主要介绍了C#实现的pdf生成图片文字水印类,结合完整实例形式分析了C#针对pdf文件的创建、添加文字、水印等相关操作技巧,需要的朋友可以参考下

本文实例讲述了C#实现的pdf生成图片文字水印类。分享给大家供大家参考,具体如下:


public class PDFSetWaterMark
{
    /// <summary>
    /// 创建一个显示指定图片的pdf
    /// </summary>
    /// <param name=picPdfPath></param>
    /// <param name=picPath></param>
    /// <returns></returns>
    public static bool CreatePDFByPic(string picPdfPath, string picPath)
    {
      //新建一个文档
      Document doc = new Document();
      try
      {
        //建立一个书写器(Writer)与document对象关联
        PdfWriter.GetInstance(doc, new FileStream(picPdfPath, FileMode.Create, FileAccess.ReadWrite));
        //打开一个文档
        doc.Open();
        //向文档中添加内容
        Image img = Image.GetInstance(picPath);
        //img.SetAbsolutePosition();
        doc.Add(img);
        return true;
      }
      catch (Exception ex)
      {
        return false;
        throw ex;
      }
      finally
      {
        if (doc != null)
        {
          doc.Close();
        }
      }
    }
    /// <summary>
    /// 加图片水印
    /// </summary>
    /// <param name=inputfilepath></param>
    /// <param name=outputfilepath></param>
    /// <param name=ModelPicName></param>
    /// <param name=top></param>
    /// <param name=left></param>
    /// <returns></returns>
    public static bool PDFWatermark(string inputfilepath, string outputfilepath, string ModelPicName, float top, float left)
    {
      //throw new NotImplementedException();
      PdfReader pdfReader = null;
      PdfStamper pdfStamper = null;
      try
      {
        pdfReader = new PdfReader(inputfilepath);
        int numberOfPages = pdfReader.NumberOfPages;
        iTextSharp.text.Rectangle psize = pdfReader.GetPageSize(1);
        float width = psize.Width;
        float height = psize.Height;
        pdfStamper = new PdfStamper(pdfReader, new FileStream(outputfilepath, FileMode.Create));
        PdfContentByte waterMarkContent;
        iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(ModelPicName);
        image.GrayFill = 20;//透明度,灰色填充
        //image.Rotation//旋转
        //image.RotationDegrees//旋转角度
        //水印的位置
        if (left < 0)
        {
          left = width / 2 - image.Width + left;
        }
        //image.SetAbsolutePosition(left, (height - image.Height) - top);
        image.SetAbsolutePosition(left, (height / 2 - image.Height) - top);
        //每一页加水印,也可以设置某一页加水印
        for (int i = 1; i <= numberOfPages; i++)
        {
          //waterMarkContent = pdfStamper.GetUnderContent(i);//内容下层加水印
          waterMarkContent = pdfStamper.GetOverContent(i);//内容上层加水印
          waterMarkContent.AddImage(image);
        }
        //strMsg = success;
        return true;
      }
      catch (Exception ex)
      {
        throw ex;
      }
      finally
      {
        if (pdfStamper != null)
          pdfStamper.Close();
        if (pdfReader != null)
          pdfReader.Close();
      }
    }
    /// <summary>
    /// 添加普通偏转角度文字水印
    /// </summary>
    /// <param name=inputfilepath></param>
    /// <param name=outputfilepath></param>
    /// <param name=waterMarkName></param>
    /// <param name=permission></param>
    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.3f;
          content.SetGState(gs);
          //content.SetGrayFill(0.3f);
          //开始写入文本
          content.BeginText();
          content.SetColorFill(BaseColor.LIGHT_GRAY);
          content.SetFontAndSize(font, 100);
          content.SetTextMatrix(0, 0);
          content.ShowTextAligned(Element.ALIGN_CENTER, waterMarkName, width / 2 - 50, height / 2 - 50, 55);
          //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();
      }
    }
    /// <summary>
    /// 添加倾斜水印
    /// </summary>
    /// <param name=inputfilepath></param>
    /// <param name=outputfilepath></param>
    /// <param name=waterMarkName></param>
    /// <param name=userPassWord></param>
    /// <param name=ownerPassWord></param>
    /// <param name=permission></param>
    public static void setWatermark(string inputfilepath, string outputfilepath, string waterMarkName, string userPassWord, string ownerPassWord, int permission)
    {
      PdfReader pdfReader = null;
      PdfStamper pdfStamper = null;
      try
      {
        pdfReader = new PdfReader(inputfilepath);
        pdfStamper = new PdfStamper(pdfReader, new FileStream(outputfilepath, FileMode.Create));
        // 设置密码
        //pdfStamper.SetEncryption(false,userPassWord, ownerPassWord, permission);
        int total = pdfReader.NumberOfPages + 1;
        PdfContentByte content;
        BaseFont font = BaseFont.CreateFont(@C:\WINDOWS\Fonts\SIMFANG.TTF, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        PdfGState gs = new PdfGState();
        gs.FillOpacity = 0.2f;//透明度
        int j = waterMarkName.Length;
        char c;
        int rise = 0;
        for (int i = 1; i < total; i++)
        {
          rise = 500;
          content = pdfStamper.GetOverContent(i);//在内容上方加水印
          //content = pdfStamper.GetUnderContent(i);//在内容下方加水印
          content.BeginText();
          content.SetColorFill(BaseColor.DARK_GRAY);
          content.SetFontAndSize(font, 50);
          // 设置水印文字字体倾斜 开始
          if (j >= 15)
          {
            content.SetTextMatrix(200, 120);
            for (int k = 0; k < j; k++)
            {
              content.SetTextRise(rise);
              c = waterMarkName[k];
              content.ShowText(c + );
              rise -= 20;
            }
          }
          else
          {
            content.SetTextMatrix(180, 100);
            for (int k = 0; k < j; k++)
            {
              content.SetTextRise(rise);
              c = waterMarkName[k];
              content.ShowText(c + );
              rise -= 18;
            }
          }
          // 字体设置结束
          content.EndText();
          // 画一个圆
          //content.Ellipse(250, 450, 350, 550);
          //content.SetLineWidth(1f);
          //content.Stroke();
        }
      }
      catch (Exception ex)
      {
        throw ex;
      }
      finally
      {
        if (pdfStamper != null)
          pdfStamper.Close();
        if (pdfReader != null)
          pdfReader.Close();
      }
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


1:最直白的循环遍历方法,可以分为遍历key--value键值对以及所有的key两种表现形式2:用Linq的方式去查询(当然了这里要添加对应的命名空间 using System.Linq)如下为一个十分简单的代码示例:private void GetDicKeyByValue(){ Dicti...
private void ClearTextBox(){ foreach (var control in pnlDetail.Controls) { if (!(control is TextBox)) continue; var txtBox = (TextBox)control; txtBox.
原文叫看《墨攻》理解IOC概念 2006年多部贺岁大片以让人应接不暇的频率纷至沓来,其中张之亮的《墨攻》算是比较出彩的一部,讲述了战国时期墨家人革离帮助梁 国反抗赵国侵略的个人英雄主义故事,恢宏壮阔,浑雄凝重的历史场面相当震撼。其中有一个场景:当刘德华所饰的墨者革离到达梁国都城 下,城上梁国守军问:
System.Data.ConstraintException: Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints.
Request.Form value was detected from the client在使用ASP.NET MVC3 开发系统的用了百度的UEditor编辑器提交表单时遇到检测到有潜在危险的 Request.Form,我百度一下,试了网上的方法,都没用。要在Web.config增加&lt;h
右击文件夹-&gt;安全选项卡-&gt;添加-&gt;高级-&gt;立即查找Windows Server 2003:请您在目录添加IIS来宾帐号(IUSR_Hostname)的只读权限,以及Network Service组的读写修改权限。Windows Server 2000:请您在目录添加IIS来
&lt;compilationdebug=&quot;true&quot;&gt;&lt;buildProviders&gt;&lt;addextension=&quot;.html&quot;type=&quot;System.Web.Compilation.PageBuildProvider&q
在ASP.NET MVC 中 Spring.NET 配置注入的时候,下面这方式是可行的。&lt;spring&gt; &lt;context&gt; &lt;resource uri=&quot;config://spring/objects&quot; /&gt; &lt;/context&gt;
Stopwatch stopwatch = new Stopwatch();stopwatch.Start();。。。。。中间代码。。。&#x9;stopwatch.Stop();&#x9;long result = stopwatch.ElapsedMilliseconds;sqlBulkCopy.Close()
问题描述 在asp.net mvc 下配置ueditor图片上传时总是提示:缺少十六进制字符错误(IE下提示),起初还以为是我上传的图片名称中有中文字符所致,后来我又上传了英文字符名字的图片发现还是一样的错误提示:◆无赖之下只好到火狐下看错误的详情:◆第二个错误我无法解决,先看第一个,输入地址显示错
已经安装net2.0 和3.5 ,但IIS里面却只有1.1开始→运行→CMDC:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe -i按回车键后便会开始自动安装,安装完重启一下IIS在IIS中ASP.NET选项卡便可以看到。注
根据传进来不同的值,调用不同的方法View Code protected void btn_SwitchClick(object sender, EventArgs e){ string result = &quot;&quot;; switch (ddlMethod.SelectedValue)
整理两个 在C#中,用正则表达式 获取网页源代码标签的属性或值的方法 :1、获取标签中的值: CSDN 结果:CSDN/// /// 获取字符中指定标签的值 /// /// 字符串 /// 标签 /// 值 public static string GetTitleContent(string st
/// &lt;summary&gt;/// 集合装换DataTable/// &lt;/summary&gt;/// &lt;param name=&quot;list&quot;&gt;集合&lt;/param&gt;/// &lt;returns&gt;&lt;/returns&gt;publ
将目录下面所有的 .cs 文件合并到一个 code.cs 文件中,写著作权复制代码时的必备良药 @echo off echo 将该目录下所有.cs文件的内容合并到一个 code.cs 文件中! pause dir /ad/s/b &gt; folderPath.txt md codeTemp for
做接口开发的时候,往往接受参数或返回值是一个XML的字符串。如下图,不方便辨识 两种方法, 1.将它保存为xxx.xml,然后用浏览器打开。这种方法稍微有些麻烦。 2.使用 UltraEdit 工具
一个字段控制多个状态选项private void GenerateAdvice_OnClick(object sender, RoutedEventArgs e){ TestStatus c1 = TestStatus.A | TestStatus.C | TestStatus.E; v...
效果如下: 代码如下:
StartUp.cs public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseEndpoints(endpoints =&gt; { endpoints.MapControllerRoute(