Good day, everyone.
How can I apply predefined styles of word document to inserted HTML?
Like:
builder.InsertHTML(post.Title)
// apply style from document "Media-title"
builder.InsertHTML(post.Content)
// apply style "Media-content"
Please note InsertHtml() overload with useBuilderFormatting will not override styles of HTML text having inline styles. You may implement INodeChangingCallback for applying styles/formatting to HTML text. Please check following code snippet for reference.
public static void HtmlFormatting()
{
// Create a blank document object
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Set up and pass the object which implements the handler methods.
doc.NodeChangingCallback = new HandleNodeChanging_FontChanger();
// Insert sample HTML content
builder.InsertHtml("<p>Hello World</p>");
doc.NodeChangingCallback = null;
builder.InsertHtml("<p>Some Test Text</p>");
doc.Save(@"Out.docx");
}
public class HandleNodeChanging_FontChanger : INodeChangingCallback
{
// Implement the NodeInserted handler to set default font settings for every Run node inserted into the Document
void INodeChangingCallback.NodeInserted(NodeChangingArgs args)
{
// Change the font of inserted text contained in the Run nodes.
if (args.Node.NodeType == NodeType.Run)
{
Run run = (Run)args.Node;
Console.WriteLine(run.Text);
run.Font.StyleName = "Intense Emphasis";
// Aspose.Words.Font font = ((Run)args.Node).Font;
// font.Size = 24;
// font.Name = "Arial";
}
}
void INodeChangingCallback.NodeInserting(NodeChangingArgs args)
{
// Do Nothing
}
void INodeChangingCallback.NodeRemoved(NodeChangingArgs args)
{
// Do Nothing
}
void INodeChangingCallback.NodeRemoving(NodeChangingArgs args)
{
// Do Nothing
}
}
I work with Aspose as developer Evangelist.
Well, after a couple of hours of finding a solution I've got this to work:
builder.ParagraphFormat.ClearFormatting();
builder.ParagraphFormat.Style = styles["word_style1"];
builder.Writeln(post.Title);
builder.InsertParagraph();
builder.ParagraphFormat.Style = styles["word_style2"];
builder.InsertHtml(post.Annotation, true);
builder.InsertParagraph();
builder.ParagraphFormat.Style = styles["word_style3"];
builder.InsertHyperlink(post.Url, post.Url, false);
PS: I hope there are any workarounds or improvements to do ot better.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.