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

时间:2022-01-05 20:11:14

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

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

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

以下是相关代码。

 /// <summary>
/// 格式转换
/// </summary>
/// <param name="content">邮件内容</param>
/// <param name="fileType">转换类型</param>
/// <returns></returns>
private static Byte[] ChangeContent(string content, string fileType)
{ Byte[] fileSteream = null;
try
{ // 定义正则表达式用来匹配 img 标签
Regex regImg = new Regex(@"<img\b[^<>]*?\bmarktype=[""'][^<>]*>", RegexOptions.IgnoreCase);
Regex regImgMarktype = new Regex(@"\bsrc=[""'](?<src>[^\s\t\r\n""'<>]*)[^<>]*", RegexOptions.IgnoreCase);
MatchCollection matches = regImg.Matches(content); // 取得匹配项列表
foreach (Match match in matches)
{
string srcUrl = "";
if (match.Value != null)
{
MatchCollection matchesMarktype = regImgMarktype.Matches(match.Value);
foreach (Match mat in matchesMarktype)
{
var src = mat.Groups["src"].Value;
if (!string.IsNullOrEmpty(src))
{
srcUrl = ServerCommon.SharedDirc + src; //替换图片路径
content = content.Replace(src, srcUrl);
}
}
}
} switch (fileType.ToUpper())
{
case "PDF":
fileSteream = ConversionFormat.HtmlToPDF(content);
break;
case "WORD":
fileSteream = ConversionFormat.HtmlToWrod(content);
break;
case "EXCEL":
fileSteream = ConversionFormat.HtmlToExcel(content);
break;
default:
break;
}
}
catch (Exception ex)
{
//log
} return fileSteream;
} /// <summary>
/// 输出内容格式转换
/// </summary>
public class ConversionFormat
{
public static byte[] HtmlToPDF(string content)
{
var meat = "<meta http-equiv='Content-Type' content='text/html; charset=utf-8'>";//解决PDF乱码问题
var htmlContent = meat + content;
var htmlToPdf = new NReco.PdfGenerator.HtmlToPdfConverter();
var pdfBytes = htmlToPdf.GeneratePdf(htmlContent); return pdfBytes;
} public static byte[] HtmlToWrod(string content)
{
//获得字节数组
byte[] data = new UTF8Encoding().GetBytes(content); return data;
} public static byte[] HtmlToExcel(string content)
{
//获得字节数组
byte[] data = new UTF8Encoding().GetBytes(content); return data;
}
}

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

 public void SaveFile(string fileName, byte[] Bytes)
{
string filePath = @"D:\temp\" + fileName;
if (!(Directory.Exists(@"D:\temp")))
{
Directory.CreateDirectory(@"D:\temp");
}
if (File.Exists(filePath))
{
return;
} FileStream fs = new FileStream(filePath, FileMode.Create);
//获得字节数组
//byte[] data = new UTF8Encoding().GetBytes(pdfBytes);
//开始写入
fs.Write(Bytes, , Bytes.Length);
//清空缓冲区、关闭流
fs.Flush();
fs.Close();
}