DataTplImage.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 System.Globalization;
  11. using GrapeCity.Documents.Word;
  12.  
  13. namespace DsWordWeb.Demos
  14. {
  15. // This sample shows how to use the image formatter in a data template.
  16. public class DataTplImage
  17. {
  18.  
  19. public GcWordDocument CreateDocx()
  20. {
  21. // The data source.
  22. //
  23. // The 'imagePath' yields the absolute path of an image,
  24. // which is one of accepted value types for the image formatter.
  25. //
  26. // For reference, the following value types are supported by the image formatter:
  27. // - A byte array containing the image data;
  28. // - A System.IO.Stream object that can be used to read the image data;
  29. // - A System.Drawing.Image object;
  30. // - A string from which an absolute file URI of the image can be created, or Base64-encoded image data.
  31. var data = new[]
  32. {
  33. new { name = "Minerva", imagePath = Path.GetFullPath(Path.Combine("Resources", "Images", "minerva.jpg")) },
  34. new { name = "Colosseum", imagePath = Path.GetFullPath(Path.Combine("Resources", "Images", "colosseum.jpg")) },
  35. new { name = "Venus Felix", imagePath = Path.GetFullPath(Path.Combine("Resources", "Images", "lady.jpg")) },
  36. };
  37.  
  38. var doc = new GcWordDocument();
  39.  
  40. // Add the data source to the data template data sources:
  41. doc.DataTemplate.DataSources.Add("ds", data);
  42.  
  43. // The single paragraph added to the document contains template tags:
  44. // - {{#ds}}..{{/ds}} -- root template, 'ds' is the name of the data source;
  45. // - {{ds.name}} -- fetches the image name;
  46. // - {{ds.imagePath}:image(266,400)} -- fetches the image file, resizes the image to specified size.
  47. var p = doc.Body.Paragraphs.Add("{{#ds}}{{ds.name}}:\n{{ds.imagePath}:image(266,400)}{{/ds}}");
  48.  
  49. // This call expands all data templates in the document,
  50. // replacing template tags with data (iterating over all data items):
  51. doc.DataTemplate.Process(CultureInfo.GetCultureInfo("en-US"));
  52.  
  53. // Done:
  54. return doc;
  55. }
  56. }
  57. }
  58.