MailMergeBookmarks.vb
''
'' This code is part of Document Solutions for Word demos.
'' Copyright (c) MESCIUS inc. All rights reserved.
''
Imports System
Imports System.IO
Imports System.Drawing
Imports System.Collections.Generic
Imports System.Linq
Imports GrapeCity.Documents.Word

'' This sample demonstrates one possible approach to generating documents
'' using a specially prepared DOCX as the template, and filled with data programmatically,
'' useful for example in mail merge applications.
'' Here the template document has parts that should be replaced with data marked
'' with bookmarks, each bookmark defined on the whole part that needs replacing.
'' For convenience, such parts in the document text are enclosed in square brackets,
'' with text equal to the corresponding bookmark's name.
'' In MS Word, use Insert | Bookmarks to inspect or add bookmarks.
Public Class MailMergeBookmarks
    Function CreateDocx() As GcWordDocument
        Dim doc = New GcWordDocument()

        '' Load the template document:
        doc.Load(Path.Combine("Resources", "WordDocs", "MailMergeBmk-tpl.docx"))
        '' Get the bookmarks collection:
        Dim bmks = doc.Body.Bookmarks

        '' Method to replace a bookmarked text with a specified value.
        '' Note:
        '' - We replace the first bookmarked run with the specified value,
        ''   so the replacement will be formatted as the first bookmarked run;
        '' - MS Word may have created multiple runs for a bookmarked text,
        ''   so we need to make sure we remove all but the first run.
        Dim setBmkText As Action(Of String, String) =
            Sub(bmk, value)
                If Not bmks.Contains(bmk) Then
                    Return
                End If
                Dim t = bmks(bmk).GetRange()
                t.Texts(0).Value = value
                For i = t.Texts.Count - 1 To 1 Step -1
                    t.Texts(i).Delete()
                Next
            End Sub

        '' Replace bookmarks with actual data. In a real life sample,
        '' this would usually be a loop over a data source.
        setBmkText("title", "Mr.")
        setBmkText("surname", "Smith")
        setBmkText("address", "123 Bits Dr.")
        setBmkText("city", "Byteville")
        setBmkText("state", "VT")
        setBmkText("zip", "12345")
        setBmkText("country", "U.S.A.")

        '' Done:
        Return doc
    End Function
End Class