CopyKeepSource.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. using GcFont = GrapeCity.Documents.Word.Font;
  11.  
  12. namespace DsWordWeb.Demos
  13. {
  14. // This sample shows the use of new in v4.2 FormattingCopyStrategy.KeepSource option.
  15. // That option allows to keep source formatting even when copying content
  16. // between documents, and when the documents have similarly named but different styles .
  17. public class CopyKeepSource
  18. {
  19. public GcWordDocument CreateDocx()
  20. {
  21. // The name of the style used in both documents:
  22. const string styleName = "X-style";
  23.  
  24. // The target document:
  25. var doc = new GcWordDocument();
  26.  
  27. // Add a paragraph style to the target document:
  28. var xStyleTgt = doc.Styles.Add(styleName, StyleType.Paragraph);
  29. xStyleTgt.Font.Color.RGB = Color.Blue;
  30. xStyleTgt.Font.Bold = true;
  31. xStyleTgt.ParagraphFormat.Indentation.RightIndent += 72;
  32. // Add a paragraph with that style:
  33. var textTgt = $"This paragraph in the target document " +
  34. $"is associated with a custom paragraph style named \"{styleName}\". " +
  35. $"That style specifies the font to be blue and bold, and the whole paragraph " +
  36. $"is indented by 1\" on the right.";
  37. doc.Body.Paragraphs.Add(textTgt, doc.Styles[styleName]);
  38.  
  39. // The source DOCX, we will copy from it to the target document keeping formatting:
  40. var docSrc = new GcWordDocument();
  41. // Add a style with the same name to the source:
  42. var xStyleSrc = docSrc.Styles.Add(styleName, StyleType.Paragraph);
  43. xStyleSrc.Font.Color.RGB = Color.Red;
  44. xStyleSrc.Font.Italic = true;
  45. xStyleSrc.ParagraphFormat.Alignment = ParagraphAlignment.Right;
  46. xStyleSrc.ParagraphFormat.Indentation.LeftIndent += 72;
  47. // Add a paragraph with the style, this paragraph will be copied to target:
  48. var textSrc = "This paragraph is copied from the source to the target DOCX. " +
  49. $"In the source DOCX, this paragraph was associated with a custom style also named \"{styleName}\". " +
  50. $"That style specifies the font to be red and italic, the whole paragraph is right-aligned " +
  51. $"and indented 1\" from the left. " +
  52. $"Due to a conflict with the same-named but different style in the target document " +
  53. $"its name is changed to \"{styleName}1\".";
  54. var paraSrc = docSrc.Body.Paragraphs.Add(textSrc, docSrc.Styles[styleName]);
  55.  
  56. // Copy paragraph from source to target using FormattingCopyStrategy.KeepSource:
  57. paraSrc.GetRange().CopyTo(doc.Body, InsertLocation.End, FormattingCopyStrategy.KeepSource);
  58.  
  59. // Done:
  60. return doc;
  61. }
  62. }
  63. }
  64.