html生成wrod文档,并智能生成目录
注意:首页网页标签不要有h1等标签,不然会生成目录
使用的是Aspose.Words
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.InsertHtml(temHtml);
if (isCatalogue)
{
NodeCollection paragraphs = doc.GetChildNodes(NodeType.Paragraph, true);
foreach (Paragraph paragraph in paragraphs)
{
if (paragraph.ToString(SaveFormat.Text).Contains("目录"))
{
// 在找到的段落后面插入目录
builder.MoveTo(paragraph);
builder.InsertParagraph();
builder.InsertTableOfContents("\\o \"1-4\" \\h \\z");
break;
}
}
// 更新目录
doc.UpdateFields();
// 访问文档的样式集合
StyleCollection styles = doc.Styles;
// 修改与目录条目关联的样式的字体颜色为黑色
foreach (Style style in styles)
{
if (style.Name.StartsWith("Hyperlink"))
{
// 修改字体颜色为黑色
style.Font.Color = Color.Black;
}
}
//菜单下添加新页
foreach (Paragraph paragraph in paragraphs)
{
if (paragraph.ToString(SaveFormat.Text).Contains("政策快车线下服务"))
{
builder.MoveTo(paragraph);
builder.InsertBreak(BreakType.SectionBreakNewPage);
break;
}
}
}
MemoryStream outStream = new MemoryStream();
doc.Save(outStream, SaveFormat.Docx);
return outStream.ToArray();
return outStream.ToArray();
使用的是cshtml模板生成html数据(RazorEngine.3.10.0)
public class RazorRenderer { public static string RenderModel(string template, object model) { if (string.IsNullOrEmpty(template)) return string.Empty; return Engine.Razor.RunCompile(template, Guid.NewGuid().ToString(), modelType: model.GetType(), model: model); } public static string Render(string template, object model) { if (string.IsNullOrEmpty(template)) return string.Empty; return Engine.Razor.RunCompile(template, Guid.NewGuid().ToString(), null, model); } public static string GetTemplate(string templateName) { string name = templateName; if (!name.Contains(",")) name += ".txt"; string templatePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "template", name); if (File.Exists(templatePath)) { using (FileStream fsRead = new FileStream(templatePath, FileMode.Open)) { int fsLen = (int)fsRead.Length; byte[] heByte = new byte[fsLen]; int r = fsRead.Read(heByte, 0, heByte.Length); return System.Text.Encoding.UTF8.GetString(heByte); } } return string.Empty; } }