Insert a WebBrowser in a Word Document! Or how to insert a WPF/ Winform Custom UserControl in a Word Document

 This post provides an example on how to insert custom control inside a Word Document using VSTO. You might for example insert controls as button or a whole user interface inside your document.

These controls might either be Winform or WPF control. VSTO allows developers to insert Winform controls inside their document.

Create the project

Create a new project Word 2010 project

 

Then select “Create a new document”.

When the project finished loading, click F7 to open the code behind.

 

 

Create the WPF UserControl

Select the current project and “Add an Item”, select “Visual C# Items > WPF > Use Control (WPF) ”.

 

You can add any component that you feel useful for your document interface.

I personally decided to implement a simple WebBrowser.

 <UserControl x:Class="WordCustomControl.WPFUserControl"
             xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="https://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="https://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300">
    <Grid>
        <WebBrowser Name="MyWebBrowser" />
    </Grid>
</UserControl>

 

Here is the code behind:

  public partial class WinformUserControl : UserControl
    {
        public WinformUserControl()
        {
            InitializeComponent();
            elementHost1.Child = new WPFUserControl();
        }
    }

 

Create the Winform UserControl

Now create a Winform User Control.

 

Use your toolbox to insert an ElementHost and Click “Dock to parent Container”.

 

In your Winform User Control code behind specify that you want the ElementHost to have the WPFUserControl as a child.

 elementHost1.Child = new WPFUserControl();

 

Insert in the Word Document

Going back to word code behind (ThisDocument.cs), we now will add some code to insert our control.

  private void ThisDocument_Startup(object sender, System.EventArgs e)
        {
            Word.Paragraph paragraph = this.Paragraphs.Add();
            WinformUserControl control = new WinformUserControl();
            Word.Range range = paragraph.Range;
            float width = 450;
            float height = 300;
            string objectID = "Winform_UserControl_1";
 
            this.Controls.AddControl(control, range, width, height, objectID);
        }

 

We now have a WebBrowser inside our word document!

 

 

Enjoy,

Linvi