C# 利用PdfSharp生成Pdf文件的示例

 更新时间:2021年04月02日 09:19:57   作者:Alan.hsiang  
这篇文章主要介绍了C# 利用PdfSharp生成Pdf文件的示例,帮助大家更好的理解和学习使用c#,感兴趣的朋友可以了解下

PdfSharp一款开源的用于创建,操作PDF文档的.Net类库,本文以一个简单的小例子,简述如何通过PdfSharp进行创建PDF文档,仅供学习分享使用,如有不足之处,还请指正。

PdfSharp下载

在本例中,主要通过NuGet包管理器进行下载安装,目前PdfSharp版本为v1.5.0.5147,如下所示:

涉及知识点

在生成PDF文档过程中,主要知识点如下:

  1. PdfDocument : 表示一个PDF文档对象,调用save方法保存文档到指定路径。
  2. PdfPage : 表示PDF文档中的一页。
  3. XGraphics:表示页面上的绘制对象,所有的页面内容,都可通过此对象绘制。如:DrawString绘制文本内容,DrawLine绘制直线等。
  4. XFont:绘制文本的字体,字体名称只能取C:\Windows\Fonts目录下的ttf字体文件,不能是ttc格式的字体。
  5. XTextFormatter:表示一个简单的文本字体格式,如识别文本的换行符而实现自动换行等内容。

文档示例图

在本例中,主要是将页面内容写入PDF文件中,页面如下所示:

生成的PDF文件,如下所示:

核心代码

在本例中,核心代码主要包括如下几个部分:

  • 创建文档
  • 绘制文本
  • 绘制直线
  • 设置纸张大小,
  • 设置边界
  • 文本的自动换行

具体代码,如下所示:

/// <summary>
    /// 生成Pdf
    /// </summary>
    /// <param name="filePath"></param>
    /// <param name="bo"></param>
    /// <returns></returns>
    public bool GeneratePdf(string filePath, PdfBo bo) {
      int margin_left_right = 30;//左右边距
      int margin_top_bottom = 30;//上下边距
      //1. 定义文档对象
      PdfDocument document = new PdfDocument();
      //2. 新增一页
      PdfPage page = document.AddPage();
      // 设置纸张大小
      page.Size = PageSize.A4;
      //3. 创建一个绘图对象
      XGraphics gfx = XGraphics.FromPdfPage(page);
      XFont font = new XFont("华文宋体", 40, XFontStyle.Bold);
      //定制化内容开始
      int cur_x = 0 + margin_left_right;
      int cur_y = 0 + margin_top_bottom;
      //标题1
      gfx.DrawString(bo.Head1, font, XBrushes.Red, new XRect(cur_x, cur_y, page.Width-2*cur_x, 80), XStringFormats.Center);
      //序号
      font = new XFont("华文宋体", 12, XFontStyle.Regular);
      cur_y = cur_y + 80;
      gfx.DrawString(bo.No, font, XBrushes.Black, new XRect(cur_x, cur_y, 100, 20), XStringFormats.CenterLeft);
      //密级
      cur_x = cur_x + 200;
      gfx.DrawString(string.Format("密级[{0}]",bo.Private), font, XBrushes.Black, new XRect(cur_x, cur_y, 100, 20), XStringFormats.CenterLeft);
      //缓级
      cur_x = cur_x + 100;
      gfx.DrawString(string.Format("缓级[{0}]", bo.Speed), font, XBrushes.Black, new XRect(cur_x, cur_y, 100, 20), XStringFormats.CenterLeft);
      //签发人
      cur_x = cur_x + 100;
      gfx.DrawString(string.Format("签发人:{0}", bo.Person), font, XBrushes.Black, new XRect(cur_x, cur_y, 100, 20), XStringFormats.CenterLeft);
      //一条横线
      cur_x = 0 + margin_left_right;
      cur_y = cur_y + 20;
      XPen pen = new XPen(XColor.FromKnownColor(XKnownColor.Black), 1);
      gfx.DrawLine(pen, cur_x, cur_y, page.Width-cur_x, cur_y+2);
      //标题2
      font = new XFont("华文宋体", 20, XFontStyle.Regular);
      cur_y = cur_y + 10;
      gfx.DrawString(bo.Head2, font, XBrushes.Black, new XRect(cur_x, cur_y, page.Width-2*cur_x, 40), XStringFormats.Center);
      //抬头
      font = new XFont("华文宋体", 15, XFontStyle.Bold);
      cur_y = cur_y + 40;
      gfx.DrawString(bo.Title, font, XBrushes.Black, new XRect(cur_x, cur_y, page.Width, 40), XStringFormats.CenterLeft);
      //正文 ,自动换行
      cur_y = cur_y + 40;
      XTextFormatter tf = new XTextFormatter(gfx);
      font = new XFont("华文宋体", 12, XFontStyle.Regular);

      //测量当前内容下,一行可以多少个汉字
      int cnt = 0;
      int height = 0;
      for (int i = 0; i < bo.Content.Length; i++) {
        XSize xsize=gfx.MeasureString(bo.Content.Substring(0,i+1), font, XStringFormats.TopLeft);
        double width = xsize.Width;
        if (width >= page.Width - 2 * cur_x) {
          cnt = i; //表示一行可以放多少个汉字。
          height =(int) xsize.Height;
          break;
        }
      }
      cnt = cnt > 0 ? cnt : bo.Content.Length;//每一行多少汉字
      string[] arrContent = bo.Content.Split('\n');
      string new_content = "";
      int total_lines = 0;
      foreach (string content in arrContent) {
        if (content.Length <= cnt)
        {
          new_content+=string.Format("{0}\n",content);
          total_lines++;
        }
        else {
          string tmpContent = content;
          int lines = content.Length / cnt + 1;
          for (int j = 0; j < lines; j++) {
            tmpContent = tmpContent.Insert(j * cnt, "\n");
            total_lines++;
          }
          new_content += string.Format("{0}\n", tmpContent);
        }
      }
      int num = new_content.Length - new_content.Replace("\r", "").Length;
      //计算矩形
      XRect rect = new XRect(cur_x, cur_y, page.Width - 2 * cur_x, (total_lines+num)*(height+2));
      tf.DrawString(new_content, font, XBrushes.Black, rect, XStringFormats.TopLeft);
      //主题词
      cur_y = cur_y + (total_lines + num) * (height + 2) + 20;
      font = new XFont("华文宋体", 12, XFontStyle.Bold);
      gfx.DrawString(string.Format("主题词:{0}",bo.Keyword), font, XBrushes.Black, new XRect(cur_x, cur_y, page.Width, 40), XStringFormats.CenterLeft);
      //再加一条横线
      cur_y = cur_y + 40;
      gfx.DrawLine(pen, cur_x, cur_y, page.Width - cur_x, cur_y + 2);
      cur_y = cur_y + 2;
      font = new XFont("华文宋体", 10, XFontStyle.Regular);
      gfx.DrawString(string.Format("{0}{1}",bo.Company, bo.Dept), font, XBrushes.Black, new XRect(cur_x, cur_y, page.Width-2*cur_x, 40), XStringFormats.CenterLeft);
      gfx.DrawString(DateTime.Now.ToString("yyyy 年 MM 月 dd 日 印发"), font, XBrushes.Black, new XRect(cur_x, cur_y, page.Width-2*cur_x, 40), XStringFormats.CenterRight);
      //水印开始
      font = new XFont("华文宋体", 20, XFontStyle.BoldItalic);
      // 计算长度
      var size = gfx.MeasureString(bo.Watermark, font);

      // 定义旋转中心
      gfx.TranslateTransform(page.Width / 2, page.Height / 2);
      gfx.RotateTransform(-Math.Atan(page.Height / page.Width) * 180 / Math.PI);
      gfx.TranslateTransform(-page.Width / 2, -page.Height / 2);

      // 字符样式
      var format = new XStringFormat();
      format.Alignment = XStringAlignment.Near;
      format.LineAlignment = XLineAlignment.Near;

      //画刷
      XBrush brush = new XSolidBrush(XColor.FromArgb(128, 255, 0, 0));
      for (int i = 0; i < 3; i++) {
        gfx.DrawString(bo.Watermark, font, brush,
        new XPoint((page.Width - size.Width) / (1.5+i*0.5), (page.Height - size.Height) / (1.5 + i * 0.5)),
        format);
      }
      //水印结束
      //6. 保存文档
      document.Save(filePath);
      return true;
    }

以上就是C# 利用PdfSharp生成Pdf文件的示例的详细内容,更多关于c# 生成Pdf文件的资料请关注脚本之家其它相关文章!

相关文章

  • C#窗体间常用的几种传值方式及委托与事件详解

    C#窗体间常用的几种传值方式及委托与事件详解

    这篇文章主要给大家介绍了关于C#窗体间常用的几种传值方式及委托与事件的相关资料,文中通过示例代码介绍的非常详细,对大家学习或者使用小程序具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧
    2019-06-06
  • C# wx获取token的基本方法

    C# wx获取token的基本方法

    这篇文章主要为大家详细介绍了C# wx获取token的基本方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-06-06
  • C#并查集(union-find)算法详解

    C#并查集(union-find)算法详解

    本文详细讲解了C#并查集(union-find)算法,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2022-04-04
  • C#使用oledb操作excel文件的方法

    C#使用oledb操作excel文件的方法

    这篇文章主要介绍了C#使用oledb操作excel文件的方法,涉及C#中oledb操作excel的相关技巧,非常具有实用价值,需要的朋友可以参考下
    2015-05-05
  • C# 实现在控制台上换行输出与不换行输出

    C# 实现在控制台上换行输出与不换行输出

    这篇文章主要介绍了C# 实现在控制台上换行输出与不换行输出,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2021-04-04
  • C#获取机器码的方法详解(机器名,CPU编号,硬盘编号,网卡mac等)

    C#获取机器码的方法详解(机器名,CPU编号,硬盘编号,网卡mac等)

    这篇文章主要介绍了C#获取机器码的方法,结合实例形式详细分析了C#获取硬件机器名、CPU编号、硬盘编号、网卡mac等信息的相关实现方法,需要的朋友可以参考下
    2016-07-07
  • c#爬虫爬取京东的商品信息

    c#爬虫爬取京东的商品信息

    这篇文章主要给大家介绍了关于利用c#爬虫爬取京东商品信息的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们随着小编来一起学习学习吧
    2018-11-11
  • C#将隐私信息(银行账户,身份证号码)中间部分特殊字符替换成*

    C#将隐私信息(银行账户,身份证号码)中间部分特殊字符替换成*

    大家在银行交易某些业务时,都可以看到无论是身份证、银行账号中间部分都是用*号替换的,下面这篇文章主要介绍C#将隐私信息(银行账户,身份证号码)中间部分特殊字符替换成*的相关资料,需要的朋友可以参考下
    2015-08-08
  • C#中利用LINQ to XML与反射把任意类型的泛型集合转换成XML格式字符串的方法

    C#中利用LINQ to XML与反射把任意类型的泛型集合转换成XML格式字符串的方法

    本文主要介绍了C#中利用LINQ to XML与反射把任意类型的泛型集合转换成XML格式字符串的方法:利用反射,读取一个类型的所有属性,然后再把属性转换成XML元素的属性或者子元素。下面注释比较完整,需要的朋友可以看下
    2016-12-12
  • c#可以创建任意控件的拖动方法

    c#可以创建任意控件的拖动方法

    下面小编就为大家分享一篇c#可以创建任意控件的拖动方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-03-03

最新评论