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

作者:Alan.hsiang 时间:2022-01-18 17:31:30 

目录
  • PdfSharp下载

  • 涉及知识点

  • 文档示例图

  • 核心代码

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

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;
   }

来源:https://www.cnblogs.com/hsiang/archive/2021/04/01/14608694.html

标签:c#,PdfSharp,生成,Pdf
0
投稿

猜你喜欢

  • 如何使用Jenkins构建GIT+Maven项目

    2021-11-18 04:42:52
  • Java去掉小数点后面无效0的方案与建议

    2023-11-29 11:46:57
  • java教程之java注解annotation使用方法

    2023-11-13 20:18:57
  • C# Split函数根据特定分隔符分割字符串的操作

    2023-11-07 07:40:25
  • c#中XML解析文件出错解决方法

    2022-01-21 00:38:50
  • 使用@Value值注入及配置文件组件扫描

    2023-12-01 21:24:12
  • Android三方依赖冲突Gradle中exclude的使用

    2023-05-05 05:09:56
  • JAVA Optional类用法分享

    2022-01-07 02:36:08
  • MyBatis注解式开发映射语句详解

    2023-06-07 20:31:23
  • StringUtils里的isEmpty方法和isBlank方法的区别详解

    2023-07-15 04:29:16
  • Java中如何避免sql注入实例详解

    2022-08-24 14:42:06
  • Java基本数据类型(动力节点java学院整理)

    2022-09-26 12:14:13
  • 处理java异步事件的阻塞和非阻塞方法分析

    2023-04-16 05:06:01
  • C#调用新浪微博API实例代码

    2022-12-21 14:02:15
  • Unity 按钮事件封装操作(EventTriggerListener)

    2022-07-08 10:07:08
  • 浅谈抛出异常和捕获异常的一些区别

    2023-10-19 15:25:24
  • 解决Mybatis-plus和pagehelper依赖冲突的方法示例

    2022-06-28 16:52:59
  • java操作excel表格详解

    2021-08-20 14:35:46
  • Unity实现俄罗斯方块游戏

    2023-05-30 21:07:22
  • Spring创建bean的几种方式及使用场景

    2021-06-20 14:16:35
  • asp之家 软件编程 m.aspxhome.com