DocumentBuilderInsertHtml Method (String)

Inserts an HTML string into the document.

Namespace:  Aspose.Words
Assembly:  Aspose.Words (in Aspose.Words.dll) Version: 20.2
Syntax
public void InsertHtml(
	string html
)

Parameters

html
Type: SystemString
An HTML string to insert into the document.
Remarks

You can use InsertHtml to insert an HTML fragment or whole HTML document.

Examples
Inserts HTML into a document. The formatting specified in the HTML is applied.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

const string html = "<P align='right'>Paragraph right</P>" + "<b>Implicit paragraph left</b>" +
                    "<div align='center'>Div center</div>" + "<h1 align='left'>Heading 1 left.</h1>";

builder.InsertHtml(html);

doc.Save(ArtifactsDir + "DocumentBuilder.InsertHtml.doc");
Examples
Shows how to mail merge HTML data into a document.
public void InsertHtml()
{
    Document doc = new Document(MyDir + "Field MERGEFIELD.docx");

    // Add a handler for the MergeField event
    doc.MailMerge.FieldMergingCallback = new HandleMergeFieldInsertHtml();

    const string html = @"<html>
            <h1>Hello world!</h1>
    </html>";

    // Execute mail merge
    doc.MailMerge.Execute(new string[] { "htmlField1" }, new object[] { html });

    // Save resulting document with a new name
    doc.Save(ArtifactsDir + "MailMergeEvent.InsertHtml.docx");
}

private class HandleMergeFieldInsertHtml : IFieldMergingCallback
{
    /// <summary>
    /// This is called when merge field is actually merged with data in the document.
    /// </summary>
    void IFieldMergingCallback.FieldMerging(FieldMergingArgs args)
    {
        // All merge fields that expect HTML data should be marked with some prefix, e.g. 'html'
        if (args.DocumentFieldName.StartsWith("html") && args.Field.GetFieldCode().Contains("\\b"))
        {
            FieldMergeField field = args.Field;

            // Insert the text for this merge field as HTML data, using DocumentBuilder
            DocumentBuilder builder = new DocumentBuilder(args.Document);
            builder.MoveToMergeField(args.DocumentFieldName);
            builder.Write(field.TextBefore);
            builder.InsertHtml((string) args.FieldValue);

            // The HTML text itself should not be inserted
            // We have already inserted it as an HTML
            args.Text = "";
        }
    }

    void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs args)
    {
        // Do nothing
    }
}
See Also