MailMergeBookmarks.vb
  1. ''
  2. '' This code is part of Document Solutions for Word demos.
  3. '' Copyright (c) MESCIUS inc. All rights reserved.
  4. ''
  5. Imports System
  6. Imports System.IO
  7. Imports System.Drawing
  8. Imports System.Collections.Generic
  9. Imports System.Linq
  10. Imports GrapeCity.Documents.Word
  11.  
  12. '' This sample demonstrates one possible approach to generating documents
  13. '' using a specially prepared DOCX as the template, and filled with data programmatically,
  14. '' useful for example in mail merge applications.
  15. '' Here the template document has parts that should be replaced with data marked
  16. '' with bookmarks, each bookmark defined on the whole part that needs replacing.
  17. '' For convenience, such parts in the document text are enclosed in square brackets,
  18. '' with text equal to the corresponding bookmark's name.
  19. '' In MS Word, use Insert | Bookmarks to inspect or add bookmarks.
  20. Public Class MailMergeBookmarks
  21. Function CreateDocx() As GcWordDocument
  22. Dim doc = New GcWordDocument()
  23.  
  24. '' Load the template document:
  25. doc.Load(Path.Combine("Resources", "WordDocs", "MailMergeBmk-tpl.docx"))
  26. '' Get the bookmarks collection:
  27. Dim bmks = doc.Body.Bookmarks
  28.  
  29. '' Method to replace a bookmarked text with a specified value.
  30. '' Note:
  31. '' - We replace the first bookmarked run with the specified value,
  32. '' so the replacement will be formatted as the first bookmarked run;
  33. '' - MS Word may have created multiple runs for a bookmarked text,
  34. '' so we need to make sure we remove all but the first run.
  35. Dim setBmkText As Action(Of String, String) =
  36. Sub(bmk, value)
  37. If Not bmks.Contains(bmk) Then
  38. Return
  39. End If
  40. Dim t = bmks(bmk).GetRange()
  41. t.Texts(0).Value = value
  42. For i = t.Texts.Count - 1 To 1 Step -1
  43. t.Texts(i).Delete()
  44. Next
  45. End Sub
  46.  
  47. '' Replace bookmarks with actual data. In a real life sample,
  48. '' this would usually be a loop over a data source.
  49. setBmkText("title", "Mr.")
  50. setBmkText("surname", "Smith")
  51. setBmkText("address", "123 Bits Dr.")
  52. setBmkText("city", "Byteville")
  53. setBmkText("state", "VT")
  54. setBmkText("zip", "12345")
  55. setBmkText("country", "U.S.A.")
  56.  
  57. '' Done:
  58. Return doc
  59. End Function
  60. End Class
  61.