代码改变世界

将页面内容转换Pdf\Word\Excel格式

2017-05-18 17:01  taozsay  阅读(448)  评论(0)    收藏  举报

项目中用到了将邮件内容转换为Pdf、Word、Excel格式,做为邮件附件发送。

查了一些解决方案,走了一些弯路。以此代码记录下。

转换PDF需要下载NReco.PdfGenerator.dll

以下是相关代码。

 1 /// <summary>
 2 /// 格式转换
 3 /// </summary>
 4 /// <param name="content">邮件内容</param>
 5 /// <param name="fileType">转换类型</param>
 6 /// <returns></returns>
 7 private static Byte[] ChangeContent(string content, string fileType)
 8 {
 9     
10     Byte[] fileSteream = null;
11     try
12     {
13         
14         // 定义正则表达式用来匹配 img 标签 
15         Regex regImg = new Regex(@"<img\b[^<>]*?\bmarktype=[""'][^<>]*>", RegexOptions.IgnoreCase);
16         Regex regImgMarktype = new Regex(@"\bsrc=[""'](?<src>[^\s\t\r\n""'<>]*)[^<>]*", RegexOptions.IgnoreCase);
17         MatchCollection matches = regImg.Matches(content);
18 
19         // 取得匹配项列表 
20         foreach (Match match in matches)
21         {
22             string srcUrl = "";
23             if (match.Value != null)
24             {
25                 MatchCollection matchesMarktype = regImgMarktype.Matches(match.Value);
26                 foreach (Match mat in matchesMarktype)
27                 {
28                     var src = mat.Groups["src"].Value;
29                     if (!string.IsNullOrEmpty(src))
30                     {
31                         srcUrl = ServerCommon.SharedDirc + src; //替换图片路径
32                         content = content.Replace(src, srcUrl);
33                     }
34                 }
35             }
36         }
37 
38         switch (fileType.ToUpper())
39         {
40             case "PDF":
41                 fileSteream = ConversionFormat.HtmlToPDF(content);
42                 break;
43             case "WORD":
44                 fileSteream = ConversionFormat.HtmlToWrod(content);
45                 break;
46             case "EXCEL":
47                 fileSteream = ConversionFormat.HtmlToExcel(content);
48                 break;
49             default:
50                 break;
51         }
52     }
53     catch (Exception ex)
54     {
55          //log
56     }
57 
58     return fileSteream;
59 }    
60 
61 
62 
63 /// <summary>
64 /// 输出内容格式转换
65 /// </summary>
66 public class ConversionFormat
67 {
68     public static byte[] HtmlToPDF(string content)
69     {
70         var meat = "<meta http-equiv='Content-Type' content='text/html; charset=utf-8'>";//解决PDF乱码问题
71         var htmlContent = meat + content;
72         var htmlToPdf = new NReco.PdfGenerator.HtmlToPdfConverter();
73         var pdfBytes = htmlToPdf.GeneratePdf(htmlContent);
74 
75         return pdfBytes;
76     }
77 
78     public static byte[] HtmlToWrod(string content)
79     {
80         //获得字节数组
81         byte[] data = new UTF8Encoding().GetBytes(content);
82 
83         return data;
84     }
85 
86     public static byte[] HtmlToExcel(string content)
87     {
88         //获得字节数组
89         byte[] data = new UTF8Encoding().GetBytes(content);
90 
91         return data;
92     }
93 }

 

简单测试下,添加一个保存文件的方法,就能看到效果了。

 1 public void SaveFile(string fileName, byte[] Bytes)
 2         {
 3             string filePath = @"D:\temp\" + fileName;
 4             if (!(Directory.Exists(@"D:\temp")))
 5             {
 6                 Directory.CreateDirectory(@"D:\temp");
 7             }
 8             if (File.Exists(filePath))
 9             {
10                 return;
11             }
12 
13             FileStream fs = new FileStream(filePath, FileMode.Create);
14             //获得字节数组
15             //byte[] data = new UTF8Encoding().GetBytes(pdfBytes);
16             //开始写入
17             fs.Write(Bytes, 0, Bytes.Length);
18             //清空缓冲区、关闭流
19             fs.Flush();
20             fs.Close();
21         }