CopyKeepSource.cs
- //
- // This code is part of Document Solutions for Word demos.
- // Copyright (c) MESCIUS inc. All rights reserved.
- //
- using System;
- using System.IO;
- using System.Drawing;
- using System.Linq;
- using GrapeCity.Documents.Word;
- using GcFont = GrapeCity.Documents.Word.Font;
-
- namespace DsWordWeb.Demos
- {
- // This sample shows the use of new in v4.2 FormattingCopyStrategy.KeepSource option.
- // That option allows to keep source formatting even when copying content
- // between documents, and when the documents have similarly named but different styles .
- public class CopyKeepSource
- {
- public GcWordDocument CreateDocx()
- {
- // The name of the style used in both documents:
- const string styleName = "X-style";
-
- // The target document:
- var doc = new GcWordDocument();
-
- // Add a paragraph style to the target document:
- var xStyleTgt = doc.Styles.Add(styleName, StyleType.Paragraph);
- xStyleTgt.Font.Color.RGB = Color.Blue;
- xStyleTgt.Font.Bold = true;
- xStyleTgt.ParagraphFormat.Indentation.RightIndent += 72;
- // Add a paragraph with that style:
- var textTgt = $"This paragraph in the target document " +
- $"is associated with a custom paragraph style named \"{styleName}\". " +
- $"That style specifies the font to be blue and bold, and the whole paragraph " +
- $"is indented by 1\" on the right.";
- doc.Body.Paragraphs.Add(textTgt, doc.Styles[styleName]);
-
- // The source DOCX, we will copy from it to the target document keeping formatting:
- var docSrc = new GcWordDocument();
- // Add a style with the same name to the source:
- var xStyleSrc = docSrc.Styles.Add(styleName, StyleType.Paragraph);
- xStyleSrc.Font.Color.RGB = Color.Red;
- xStyleSrc.Font.Italic = true;
- xStyleSrc.ParagraphFormat.Alignment = ParagraphAlignment.Right;
- xStyleSrc.ParagraphFormat.Indentation.LeftIndent += 72;
- // Add a paragraph with the style, this paragraph will be copied to target:
- var textSrc = "This paragraph is copied from the source to the target DOCX. " +
- $"In the source DOCX, this paragraph was associated with a custom style also named \"{styleName}\". " +
- $"That style specifies the font to be red and italic, the whole paragraph is right-aligned " +
- $"and indented 1\" from the left. " +
- $"Due to a conflict with the same-named but different style in the target document " +
- $"its name is changed to \"{styleName}1\".";
- var paraSrc = docSrc.Body.Paragraphs.Add(textSrc, docSrc.Styles[styleName]);
-
- // Copy paragraph from source to target using FormattingCopyStrategy.KeepSource:
- paraSrc.GetRange().CopyTo(doc.Body, InsertLocation.End, FormattingCopyStrategy.KeepSource);
-
- // Done:
- return doc;
- }
- }
- }
-