C#代码实现HTML转神器
2.执⾏语句: 需要转换的⽂件路径(获取URL) 保存的⽂件路径
事例代码:
1.构造HTML代码,待$号的为待替换的内容
string strHtml = "<html>" +
"  <head>" +
"      <meta http-equiv='Content-Type' content='text/html; charset=utf-8' />" +
"      <title></title>" +
"  </head>" +
"  <body>" +
"      <div style='padding: 20px 40px;border: 0px;'>" +
"        <h3 style='display: block;font-family: inherit;font-weight: 600;font-size: 32px;line-height:67px;text-align: center;border-bottom: 1px solid;margin-b                  "        <p><label style='text-decoration: underline;font-size: 22px;'>$UnitName</label>:</p>" +
"        <p style='text-indent:2em;font-size: 22px;line-height:35px;'>贵司$START_DATE⾄$END_DATE<label style='text-decoration: underline;'>$SYS_K                  "        <p> </p>" +
"        <p style='text-align:right;font-size: 22px;'>$USER_INFO  </p>" +
"        <p style='text-align:right;font-size: 22px;'>$SYS_TIME  </p>" +
"      </div>" +
"    </body>" +
"</html>";
2.替换HTML中的内容
var strNewHtml = strHtml.Replace("$UnitName", SumData.UNIT_NAME).Replace("$START_DATE", SumData.START_INVOICE_DATE)
.Replace("$END_DATE", SumData.END_INVOICE_DATE).Replace("$SYS_KIND", SumData.INVOICE_KIND_NAME + sysName)
.Replace("$INVOICE_SUM", Convert.ToDouble(SumData.INVOICE_SUM).ToString("N")).Replace("$CURRENCY_NAME", SumData.CURRENCY_NA                    .Replace("$REFUSE_INFO", SumData.REFUSE_INFO).Replace("$INVOICE_PROTEST_SUM", Convert.ToDouble(SumData.INVOICE_PROTEST_S                    .Replace("$INVOICE_DUE_SUM", Convert.ToDouble(SumData.INVOICE_DUE_SUM).ToString("N"))
.Replace("$USER_INFO", _UserInfo.CorpName + _UserInfo.DeptName).Replace("$SYS_TIME", DateTime.Now.ToString("yyyy年MM⽉dd⽇"));
3.将HTML保存成⽂件或者的⼀个新页⾯(这⾥的做法是保存成⽂件)
string fileName = AppDomain.CurrentDomain.BaseDirectory + @"PDF/OUTPUTPDF/ProtestPrint.html";
FileStream _file = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite);
using (StreamWriter sw = new StreamWriter(_file))
{
sw.WriteLine(strNewHtml);
sw.Flush();
sw.Close();
_file.Close();
}
4.将⽂件转成PDF
string WkHtmlToPdf_URL = AppDomain.CurrentDomain.BaseDirectory + @"wkhtmltopdf/";
html代码转链接string savePath = AppDomain.CurrentDomain.BaseDirectory + @"PDF/OUTPUTPDF/" + ProtestInstructions.PROTEST_INSTRUCTIONS_NO + ".pdf"; //执⾏
Process p = System.Diagnostics.Process.Start(WkHtmlToPdf_URL, fileName + " " + savePath);
//若不加这⼀⾏,程序就会马上执⾏下⼀句⽽抓不到⽂件发⽣意外:System.IO.FileNotFoundException: 不到⽂件 ''。
p.WaitForExit();
//把⽂件读进⽂件流
System.IO.FileStream fs = new System.IO.FileStream(savePath, System.IO.FileMode.Open);
byte[] file = new byte[fs.Length];
fs.Read(file, 0, file.Length);
fs.Close();

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。