[转载]PDFSharp生成PDF. - 天天不在 - 博客园

[转载]PDFSharp生成PDF. – 天天不在 – 博客园.

在上面用OpenXML生成word后,原来利用Word2010里的导出成PDF功能就不能用.

然后找开源组件生成PDF,最开始用的是iTextSharp,做完导出报表了才发现,这个开源协议用的是AGPL,只能放弃,重新查找后,找到 PDFSharp(MTI协议).结合了MigraDoc来生成PDF,过程大同小异,对比iTextSharp,在画相关元素时,会慢不少,20页A4 内容,OpenXML和iTextSharp都能保持在2S内输出完成,而PDFSharp需要5-10S,不知是不是因为GDI+的原因.

代码不讲解了,只贴出来,只说明一点,对中文的支持,需要设置下.

System.Drawing.Text.PrivateFontCollection pfcFonts = new System.Drawing.Text.PrivateFontCollection();
string strFontPath = @”C:/Windows/Fonts/msyh.ttf”;//字体设置为微软雅黑
pfcFonts.AddFontFile(strFontPath);
Style style = document.Styles[“Normal”];
style.Font = new MigraDoc.DocumentObjectModel.Font(pfcFonts.Families[0].Name, 12);

复制代码
  1 using System;
  2 using System.Collections.Generic;
  3 using System.Text;
  4 using System.IO;
  5 using PdfSharp;
  6 using PdfSharp.Drawing;
  7 using PdfSharp.Pdf;
  8 using PdfSharp.Pdf.IO;
  9 using MigraDoc.DocumentObjectModel;
 10 using MigraDoc.DocumentObjectModel.Tables;
 11 using MigraDoc.DocumentObjectModel.Shapes;
 12 using System.Drawing;
 13 using MigraDoc.Rendering;
 14 namespace EDM.ReportTemplate
 15 {
 16     public class ExportPDF : ExportReport
 17     {
 18         private Section section;
 19         private SizeF PdfSize;
 20 
 21         public override void Execute()
 22         {
 23             var size = InitPage();
 24             Document doc = new Document();
 25             section = doc.AddSection();
 26             section.PageSetup = InitPage();
 27             DefineStyles(doc);
 28             PForm.ReportProgress(PShow.StartExecute, null);
 29             //CreateHead();
 30             foreach (ReportCommon common in Commons)
 31             {
 32                 if (common is ReportTable)
 33                 {
 34                     ReportTable table = common as ReportTable;
 35                     // ChangeTableColumn(table);
 36                     AddTable(table, doc);
 37                 }
 38                 if (common is ReportText)
 39                 {
 40                     ReportText table = common as ReportText;
 41                     AddText(table, doc);
 42                 }
 43                 if (common is ReportImage)
 44                 {
 45                     ReportImage table = common as ReportImage;
 46                     AddImage(table, doc);
 47                 }
 48                 if (common is ReportValueList)
 49                 {
 50                     ReportValueList table = common as ReportValueList;
 51                     AddValueList(table, doc);
 52                 }
 53                 if (common is ReportValue)
 54                 {
 55                     ReportValue table = common as ReportValue;
 56                     AddValue(table, doc);
 57                 }
 58                 SetExectueProgress(common);
 59             }
 60             PForm.ReportProgress(PShow.EndExecute, null);
 61             PdfDocumentRenderer pdfRenderer = new PdfDocumentRenderer(true);
 62             pdfRenderer.Document = doc;
 63             pdfRenderer.RenderDocument();
 64             pdfRenderer.Save(FileName);
 65         }
 66 
 67         public static void DefineStyles(Document document)
 68         {
 69             System.Drawing.Text.PrivateFontCollection pfcFonts = new System.Drawing.Text.PrivateFontCollection();
 70             string strFontPath = @"C:/Windows/Fonts/msyh.ttf";//字体设置为微软雅黑 
 71             pfcFonts.AddFontFile(strFontPath);
 72             Style style = document.Styles["Normal"];
 73             style.Font = new MigraDoc.DocumentObjectModel.Font(pfcFonts.Families[0].Name, 12);
 74             style.Font.Color = Colors.Black;
 75 
 76             style = document.Styles["Heading1"];
 77             //style.Font.Name = "Tahoma";
 78             style.Font.Size = 20;
 79             style.Font.Bold = true;
 80             style.ParagraphFormat.Alignment = ParagraphAlignment.Center;
 81             // style.Font.Color = Colors.DarkBlue;
 82             style.ParagraphFormat.PageBreakBefore = true;
 83             style.ParagraphFormat.SpaceAfter = 6;
 84 
 85             style = document.Styles["Heading2"];
 86             style.Font.Size = 16;
 87             style.Font.Bold = true;
 88             style.ParagraphFormat.PageBreakBefore = false;
 89             style.ParagraphFormat.SpaceBefore = 6;
 90             style.ParagraphFormat.SpaceAfter = 6;
 91             style.ParagraphFormat.Alignment = ParagraphAlignment.Left;
 92 
 93             style = document.Styles["Heading3"];
 94             style.Font.Size = 14;
 95             style.Font.Bold = true;
 96             style.Font.Italic = true;
 97             style.ParagraphFormat.SpaceBefore = 6;
 98             style.ParagraphFormat.SpaceAfter = 3;
 99             style.ParagraphFormat.Alignment = ParagraphAlignment.Left;
100 
101             style = document.Styles["Heading4"];
102             style.Font.Size = 12;
103             style.Font.Bold = true;
104             style.Font.Italic = true;
105             style.ParagraphFormat.SpaceBefore = 3;
106             style.ParagraphFormat.SpaceAfter = 3;
107             style.ParagraphFormat.Alignment = ParagraphAlignment.Left;
108 
109             style = document.Styles[StyleNames.Header];
110             style.ParagraphFormat.AddTabStop("16cm", TabAlignment.Right);
111 
112             style = document.Styles[StyleNames.Footer];
113             style.ParagraphFormat.AddTabStop("8cm", TabAlignment.Center);
114 
115             // Create a new style called TextBox based on style Normal
116             style = document.Styles.AddStyle("TextBox", "Normal");
117             style.ParagraphFormat.Alignment = ParagraphAlignment.Justify;
118             style.ParagraphFormat.Borders.Width = 2.5;
119             style.ParagraphFormat.Borders.Distance = "3pt";
120             //TODO: Colors
121             style.ParagraphFormat.Shading.Color = Colors.SkyBlue;
122 
123             // Create a new style called TOC based on style Normal
124             style = document.Styles.AddStyle("TOC", "Normal");
125             style.ParagraphFormat.AddTabStop("16cm", TabAlignment.Right, TabLeader.Dots);
126             style.ParagraphFormat.Font.Color = Colors.Blue;
127 
128             // Create a new style called Table based on style Normal
129             style = document.Styles.AddStyle("Table", "Normal");
130             style.Font.Name = pfcFonts.Families[0].Name;
131             style.Font.Size = 12;
132 
133             // Create a new style called Reference based on style Normal
134             style = document.Styles.AddStyle("Reference", "Normal");
135             style.ParagraphFormat.SpaceBefore = "5mm";
136             style.ParagraphFormat.SpaceAfter = "5mm";
137             style.ParagraphFormat.TabStops.AddTabStop("16cm", TabAlignment.Right);
138         }
139 
140         public PageSetup InitPage()
141         {
142             PageSetup pageSetup = new PageSetup();
143             pageSetup.PageFormat = PageFormat.Letter;
144             PdfSharp.PageSize size = PdfSharp.PageSize.Letter;
145             if (PageSize == "A4")
146             {
147                 pageSetup.PageFormat = PageFormat.A4;
148                 size = PdfSharp.PageSize.A4;
149             }
150             if (PageSize == "B4")
151             {
152                 pageSetup.PageFormat = PageFormat.B5;
153                 size = PdfSharp.PageSize.A5;
154             }
155             var psize = PageSizeConverter.ToSize(size);
156             if (IsOrientation)
157             {
158                 pageSetup.Orientation = Orientation.Landscape;
159                 double width = psize.Width;
160                 psize.Width = psize.Height;
161                 psize.Width = width;
162             }
163             PdfSize = psize.ToSizeF();
164             return pageSetup;
165         }
166 
167         public void CreateHead()
168         {
169             var image = section.Headers.Primary.AddImage("../../PowerBooks.png");
170             image.Height = "2.5cm";
171             image.LockAspectRatio = true;
172             image.RelativeVertical = RelativeVertical.Line;
173             image.RelativeHorizontal = RelativeHorizontal.Margin;
174             image.Top = ShapePosition.Top;
175             image.Left = ShapePosition.Right;
176             image.WrapFormat.Style = WrapStyle.Through;
177         }
178 
179         public void AddTable(ReportTable table, Document document)
180         {
181             var ptable = section.AddTable();
182             ptable.Style = "Table";
183             ptable.Borders.Width = 0.25;
184             ptable.Borders.Left.Width = 0.5;
185             ptable.Borders.Right.Width = 0.5;
186             ptable.Rows.LeftIndent = 0;
187             int colIndex = 0;
188             int cols = table.Column;
189             for (int i = 0; i < cols; i++)
190             {
191                 double width = GetWidth(table.GetWidth(i));
192                 if (width != 0.0)
193                     ptable.AddColumn(width);
194                 else
195                     ptable.AddColumn();
196             }
197 
198             foreach (List<string> strs in table.Table)
199             {
200                 Row row = ptable.AddRow();
201                 for (int i = 0; i < cols; i++)
202                 {
203                     string text = string.Empty;
204                     if (strs.Count > i)
205                     {
206                         if (!string.IsNullOrEmpty(strs[i]))
207                             text = strs[i];
208                     }
209                     //如果有4栏,但是只有三列数据,那到第三列时,开始合并
210                     if (strs.Count != cols && i >= strs.Count - 1)
211                     {
212                         var cell = row.Cells[strs.Count - 1];
213                         if (i == strs.Count - 1)
214                         {
215                             cell.AddParagraph(text);
216                             cell.MergeRight = 0;
217                         }
218                         if (i > strs.Count - 1)
219                         {
220                             cell.MergeRight = cell.MergeRight + 1;
221                         }
222                     }
223                     else
224                     {
225                         row.Cells[i].AddParagraph(text);
226                     }
227                     if (colIndex == 0 && table.IsHaveColumn)
228                     {
229                         row.Format.Font.Bold = true;
230                     }
231                     if (table.IsHaveLevel && colIndex != 0)
232                     {
233                         if (!strs[0].StartsWith(" "))
234                         {
235                             row.Format.Font.Bold = true;
236                         }
237                     }
238                 }
239                 colIndex++;
240             }
241         }
242 
243         public void AddText(ReportText text, Document document)
244         {
245             if (text.Size == 20)
246             {
247                 var paragraph = section.AddParagraph(text.Text, "Heading1");
248             }
249             else if (text.IsHead)
250             {
251                 var paragraph = section.AddParagraph(text.Text, "Heading" + (text.HeadSize - 1));
252             }
253             else
254             {
255                 var paragraph = section.AddParagraph(text.Text);
256                 paragraph.Format.Font.Size = text.Size;
257                 paragraph.Format.Alignment = GetParagraphAlignment(text.Alignment);
258                 paragraph.Format.Font.Bold = text.IsBold;
259             }
260         }
261 
262         public void AddImage(ReportImage image, Document document)
263         {
264             try
265             {
266                 var pImage = section.AddImage(image.Value);
267                 pImage.Width = PdfSize.Width - 100;
268                 pImage.Left = ShapePosition.Center;
269                 section.AddParagraph("");
270             }
271             catch (Exception e)
272             {
273             }
274         }
275 
276         public void AddValueList(ReportValueList valueList, Document document)
277         {
278             var ptable = section.AddTable();
279             ptable.Borders.Visible = false;
280             ptable.Rows.LeftIndent = 0;
281             for (int c = 0; c < valueList.Column; c++)
282             {
283                 ptable.AddColumn(PdfSize.Width / valueList.Column);
284             }
285 
286             for (int i = 0; i < valueList.Values.Count; i++)
287             {
288                 var value = valueList.Values[i];
289                 //当前行数
290                 int rowindex = i / valueList.Column;
291                 //当前列数
292                 int colindex = i % valueList.Column;
293                 if (colindex == 0)
294                 {
295                     ptable.AddRow();
296                 }
297                 var cell = ptable[rowindex, colindex];
298                 cell.Borders.Visible = false;
299                 this.AnalysisText(value);
300                 cell.AddParagraph(value.Text + value.Value);
301             }
302 
303         }
304 
305         public void AddValue(ReportValue value, Document document)
306         {
307             this.AnalysisText(value);
308             var paragraph = section.AddParagraph(value.Text + value.Value);
309             //paragraph.Format.Alignment = GetParagraphAlignment(text.Alignment);
310         }
311 
312         public ParagraphAlignment GetParagraphAlignment(int alignment)
313         {
314             ParagraphAlignment result = ParagraphAlignment.Left;
315             if (alignment == 0)
316                 result = ParagraphAlignment.Center;
317             if (alignment == 1)
318                 result = ParagraphAlignment.Right;
319             return result;
320         }
321 
322     }
复制代码

总的来说,和OpenXML一样,在用OpenXML导出数据时,已经把数据整理为,输出数据,输出图形,输出表格,输出一组数据.这几种形式,我用PDFSharp时,只是针对这几个类型进行处理一下就行了.

毕竟OpenXML只能导出word2007及以上识别的文件,word2003还是需要Ms office com组件,这个类我就不贴了,搜导出word几乎都用的这种.

赞(0) 打赏
分享到: 更多 (0)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏