Free Support Forum - aspose.com

Insert html into docx

Our project requirement is to insert complex html content into docx document, I mean replace placeholders with html content.
We were using docx4j but it was not retaining the formatting and getting distorted at times.
So now looking for alternative and wanted to check if that is even possible with Apose.words.

If yes then can please direct with an example.

@wrushu2004,

You can inserts an HTML string into the document by using DocumentBuilder.InsertHtml method.

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.InsertHtml(
    "<P align='right'>Paragraph right</P>" +
    "<b>Implicit paragraph left</b>" +
    "<div align='center'>Div center</div>" +
    "<h1 align='left'>Heading 1 left.</h1>");

doc.Save("D:\\temp\\18.9.doc");

The following example replaces text specified with regular expression with HTML.

public void ReplaceWithInsertHtml()
{
    // Open the document.
    Document doc = new Document(MyDir + "Range.ReplaceWithInsertHtml.doc");

    doc.Range.Replace(new Regex(@"<CustomerName>"), new ReplaceWithHtmlEvaluator(), false);

    // Save the modified document.
    doc.Save(MyDir + "Range.ReplaceWithInsertHtml Out.doc");

}

private class ReplaceWithHtmlEvaluator : IReplacingCallback
{
    /// <summary>
    /// NOTE: This is a simplistic method that will only work well when the match
    /// starts at the beginning of a run.
    /// </summary>
    ReplaceAction IReplacingCallback.Replacing(ReplacingArgs e)
    {
        DocumentBuilder builder = new DocumentBuilder((Document)e.MatchNode.Document);
        builder.MoveTo(e.MatchNode);
        // Replace '<CustomerName>' text with a red bold name.
        builder.InsertHtml("<b><font color='red'>James Bond</font></b>");

        e.Replacement = "";
        return ReplaceAction.Replace;
    }
}

Hope, this helps.

Thanks I am able to insert the html at desired location.