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