C# 利用PdfSharp生成Pdf文件

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文件,如下所示:

核心代码

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

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

具体代码,如下所示:

  1         /// <summary>
  2         /// 生成Pdf
  3         /// </summary>
  4         /// <param name="filePath"></param>
  5         /// <param name="bo"></param>
  6         /// <returns></returns>
  7         public bool GeneratePdf(string filePath, PdfBo bo) {
  8             int margin_left_right = 30;//左右边距
  9             int margin_top_bottom = 30;//上下边距
 10             //1. 定义文档对象
 11             PdfDocument document = new PdfDocument();
 12             //2. 新增一页
 13             PdfPage page = document.AddPage();
 14             // 设置纸张大小
 15             page.Size = PageSize.A4;
 16             //3. 创建一个绘图对象
 17             XGraphics gfx = XGraphics.FromPdfPage(page);
 18             XFont font = new XFont("华文宋体", 40, XFontStyle.Bold);
 19             //定制化内容开始
 20             int cur_x = 0 + margin_left_right;
 21             int cur_y = 0 + margin_top_bottom;
 22             //标题1
 23             gfx.DrawString(bo.Head1, font, XBrushes.Red, new XRect(cur_x, cur_y, page.Width-2*cur_x, 80), XStringFormats.Center);
 24             //序号
 25             font = new XFont("华文宋体", 12, XFontStyle.Regular);
 26             cur_y = cur_y + 80;
 27             gfx.DrawString(bo.No, font, XBrushes.Black, new XRect(cur_x, cur_y, 100, 20), XStringFormats.CenterLeft);
 28             //密级
 29             cur_x = cur_x + 200;
 30             gfx.DrawString(string.Format("密级[{0}]",bo.Private), font, XBrushes.Black, new XRect(cur_x, cur_y, 100, 20), XStringFormats.CenterLeft);
 31             //缓级
 32             cur_x = cur_x + 100;
 33             gfx.DrawString(string.Format("缓级[{0}]", bo.Speed), font, XBrushes.Black, new XRect(cur_x, cur_y, 100, 20), XStringFormats.CenterLeft);
 34             //签发人
 35             cur_x = cur_x + 100;
 36             gfx.DrawString(string.Format("签发人:{0}", bo.Person), font, XBrushes.Black, new XRect(cur_x, cur_y, 100, 20), XStringFormats.CenterLeft);
 37             //一条横线
 38             cur_x = 0 + margin_left_right;
 39             cur_y = cur_y + 20;
 40             XPen pen = new XPen(XColor.FromKnownColor(XKnownColor.Black), 1);
 41             gfx.DrawLine(pen, cur_x, cur_y, page.Width-cur_x, cur_y+2);
 42             //标题2
 43             font = new XFont("华文宋体", 20, XFontStyle.Regular);
 44             cur_y = cur_y + 10;
 45             gfx.DrawString(bo.Head2, font, XBrushes.Black, new XRect(cur_x, cur_y, page.Width-2*cur_x, 40), XStringFormats.Center);
 46             //抬头
 47             font = new XFont("华文宋体", 15, XFontStyle.Bold);
 48             cur_y = cur_y + 40;
 49             gfx.DrawString(bo.Title, font, XBrushes.Black, new XRect(cur_x, cur_y, page.Width, 40), XStringFormats.CenterLeft);
 50             //正文 ,自动换行
 51             cur_y = cur_y + 40;
 52             XTextFormatter tf = new XTextFormatter(gfx);
 53             font = new XFont("华文宋体", 12, XFontStyle.Regular);
 54             
 55             //测量当前内容下,一行可以多少个汉字
 56             int cnt = 0;
 57             int height = 0;
 58             for (int i = 0; i < bo.Content.Length; i++) { 
 59                 XSize xsize=gfx.MeasureString(bo.Content.Substring(0,i+1), font, XStringFormats.TopLeft);
 60                 double width = xsize.Width;
 61                 if (width >= page.Width - 2 * cur_x) {
 62                     cnt = i; //表示一行可以放多少个汉字。
 63                     height =(int) xsize.Height;
 64                     break;
 65                 }
 66             }
 67             cnt = cnt > 0 ? cnt : bo.Content.Length;//每一行多少汉字
 68             string[] arrContent = bo.Content.Split('\n');
 69             string new_content = "";
 70             int total_lines = 0;
 71             foreach (string content in arrContent) {
 72                 if (content.Length <= cnt)
 73                 {
 74                     new_content+=string.Format("{0}\n",content);
 75                     total_lines++;
 76                 }
 77                 else {
 78                     string tmpContent = content;
 79                     int lines = content.Length / cnt + 1;
 80                     for (int j = 0; j < lines; j++) {
 81                         tmpContent = tmpContent.Insert(j * cnt, "\n");
 82                         total_lines++;
 83                     }
 84                     new_content += string.Format("{0}\n", tmpContent);
 85                 }
 86             }
 87             int num  = new_content.Length - new_content.Replace("\r", "").Length;
 88             //计算矩形
 89             XRect rect = new XRect(cur_x, cur_y, page.Width - 2 * cur_x, (total_lines+num)*(height+2));
 90             tf.DrawString(new_content, font, XBrushes.Black, rect, XStringFormats.TopLeft);
 91             //主题词
 92             cur_y = cur_y + (total_lines + num) * (height + 2) + 20;
 93             font = new XFont("华文宋体", 12, XFontStyle.Bold);
 94             gfx.DrawString(string.Format("主题词:{0}",bo.Keyword), font, XBrushes.Black, new XRect(cur_x, cur_y, page.Width, 40), XStringFormats.CenterLeft);
 95             //再加一条横线
 96             cur_y = cur_y + 40;
 97             gfx.DrawLine(pen, cur_x, cur_y, page.Width - cur_x, cur_y + 2);
 98             cur_y = cur_y + 2;
 99             font = new XFont("华文宋体", 10, XFontStyle.Regular);
100             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);
101             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);
102             //水印开始
103             font = new XFont("华文宋体", 20, XFontStyle.BoldItalic);
104             // 计算长度
105             var size = gfx.MeasureString(bo.Watermark, font);
106 
107             // 定义旋转中心
108             gfx.TranslateTransform(page.Width / 2, page.Height / 2);
109             gfx.RotateTransform(-Math.Atan(page.Height / page.Width) * 180 / Math.PI);
110             gfx.TranslateTransform(-page.Width / 2, -page.Height / 2);
111 
112             // 字符样式
113             var format = new XStringFormat();
114             format.Alignment = XStringAlignment.Near;
115             format.LineAlignment = XLineAlignment.Near;
116 
117             //画刷
118             XBrush brush = new XSolidBrush(XColor.FromArgb(128, 255, 0, 0));
119             for (int i = 0; i < 3; i++) { 
120                 gfx.DrawString(bo.Watermark, font, brush,
121                 new XPoint((page.Width - size.Width) / (1.5+i*0.5), (page.Height - size.Height) / (1.5 + i * 0.5)),
122                 format);
123             }
124             //水印结束
125             //6. 保存文档
126             document.Save(filePath);
127             return true;
128         }
View Code

PdfBo是一个实体类,和页面代码相对应,如下所示:

 

 1 namespace DemoPdf
 2 {
 3     /// <summary>
 4     /// Pdf模型
 5     /// </summary>
 6     public class PdfBo
 7     {
 8         /// <summary>
 9         /// 标题1
10         /// </summary>
11         public string Head1 { get; set; }
12 
13         /// <summary>
14         /// 标题2
15         /// </summary>
16         public string Head2 { get; set; }
17 
18         /// <summary>
19         /// 编号
20         /// </summary>
21         public string No { get; set; }
22 
23         /// <summary>
24         /// 密级
25         /// </summary>
26         public string Private { get; set; }
27 
28         /// <summary>
29         /// 紧急程度
30         /// </summary>
31         public string Speed { get; set; }
32 
33         /// <summary>
34         /// 签发人
35         /// </summary>
36         public string Person { get; set; }
37 
38         /// <summary>
39         /// 公司
40         /// </summary>
41         public string Company { get; set; }
42 
43         /// <summary>
44         /// 部门
45         /// </summary>
46         public string Dept { get; set; }
47 
48         /// <summary>
49         /// 关键词
50         /// </summary>
51         public string Keyword { get; set; }
52 
53         /// <summary>
54         /// 抬头
55         /// </summary>
56         public string Title { get; set; }
57 
58         /// <summary>
59         /// 内容
60         /// </summary>
61         public string Content { get; set; }
62 
63         /// <summary>
64         /// 水印
65         /// </summary>
66         public string Watermark { get; set; }
67     }
68 }
View Code

备注

临江仙·柳外轻雷池上雨

【作者】欧阳修 【朝代】宋
 
柳外轻雷池上雨,雨声滴碎荷声。小楼西角断虹明。阑干倚处,待得月华生。
燕子飞来窥画栋,玉钩垂下帘旌。凉波不动簟纹平。水精双枕,傍有堕钗横。
posted @ 2021-04-01 23:09  老码识途呀  阅读(9657)  评论(10编辑  收藏  举报