ReplaceInTemplate.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.Linq;
  9. using GrapeCity.Documents.Word;
  10.  
  11. namespace DsWordWeb.Demos
  12. {
  13. // This sample shows how to fill a template document with data
  14. // using the RangeBase.Replace extension method provided by
  15. // the RangeBaseFindReplaceExtensions class.
  16. //
  17. // The template document is similar to the document generated by
  18. // the ProcurementLetter sample, but the data values in that document
  19. // were changed to template placeholders (in the form '__%<name>%__')
  20. // using MS Word. In the sample, we use the text replace functionality
  21. // to change the placeholders back to original data. The resulting
  22. // document can be viewed by running the ProcurementLetterTpl sample.
  23. //
  24. // In a real life application, the same approach can be used for example
  25. // to go over a record set, generating a document for each record.
  26. public class ReplaceInTemplate
  27. {
  28. public GcWordDocument CreateDocx()
  29. {
  30. // Placeholders and sample data:
  31. (string placeholder, string data)[] placeholderData =
  32. {
  33. ("__%c_name%__", "Nancy Davolio"),
  34. ("__%c_title%__", "Chief Procurement Officer"),
  35. ("__%c_phone%__", "555-543-5432"),
  36. ("__%c_url%__", "www.acmeinc.com"),
  37. ("__%c_address%__", "5432 Street West, Townsvilla, State 54321"),
  38. ("__%to_name%__", "Mark"),
  39. ("__%dlr_name%__", "AMA Ltd"),
  40. ("__%order_no%__", "8393"),
  41. };
  42.  
  43. // Load the document:
  44. var doc = new GcWordDocument();
  45. doc.Load(Path.Combine("Resources", "WordDocs", "ProcurementLetterTpl.docx"));
  46.  
  47. // Replace all placeholders in the body with sample data values:
  48. foreach ((string placeholder, string data) pair in placeholderData)
  49. doc.Body.Replace(pair.placeholder, pair.data);
  50.  
  51. // Done:
  52. return doc;
  53. }
  54. }
  55. }
  56.