C#如何利用PdfSharp生成Pdf文件

发布时间:2021-04-02 11:31:58 作者:小新
来源:亿速云 阅读:1117

这篇文章给大家分享的是有关C#如何利用PdfSharp生成Pdf文件的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。

PdfSharp一款开源的用于创建,操作PDF文档的.Net类库。

PdfSharp下载

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

C#如何利用PdfSharp生成Pdf文件

涉及知识点

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

  1. PdfDocument : 表示一个PDF文档对象,调用save方法保存文档到指定路径。

  2. PdfPage : 表示PDF文档中的一页。

  3. XGraphics:表示页面上的绘制对象,所有的页面内容,都可通过此对象绘制。如:DrawString绘制文本内容,DrawLine绘制直线等。

  4. XFont:绘制文本的字体,字体名称只能取C:\Windows\Fonts目录下的ttf字体文件,不能是ttc格式的字体。

  5. XTextFormatter:表示一个简单的文本字体格式,如识别文本的换行符而实现自动换行等内容。

文档示例图

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

C#如何利用PdfSharp生成Pdf文件

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

C#如何利用PdfSharp生成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文件”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!

推荐阅读:
  1. 如何生成PDF
  2. C#使用doggleReport生成pdf报表的方法

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

pdf文件

上一篇:Android中View事件防抖的处理方案

下一篇:wget下载整个网站或特定目录的案例分析

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》