C# Word copy style from one paragraph to another - c#

In word I have 2 paragraphs, and I'm trying to copy formatting from one to the other.
I've tried:
Word.Style style = activeDocument.Paragraphs[2].get_Style() as Word.Style;
activeDocument.Paragraphs[1].set_Style(style);
and
Word.Style style = activeDocument.Paragraphs[2].Range.CharacterStyle as Word.Style;
activeDocument.Paragraphs[1].Range.set_Style(style);
This doesn't properly copy the style though, and the first paragraphs style is set to the default text styling. How do I get the proper styling information?

I think paragraph[2].get_style() return normal style (default text) because of paragraph[2] style is normal (default text)!! You change formatting text but not save it as style! The style of paragraph[2] not change from default value. See style name in MSWord and create new style then apply it, then 1 variant work fine.

Related

Append predefined style to a Word bookmark with c#

I try to set text and a predefined style to a bookmark. Text is fine, but the style is not set. Whats wrong with this source?:
Word.Application word = new Word.Application();
word.Visible = true;
Word.Document doc = word.Documents.Open("bookmark.dotx");
doc.Activate();
Word.Paragraph paragraph = doc.Bookmarks["navigatorHeadlineBookmark"].Range.Paragraphs.Add();
paragraph.Range.Text = "hello headline";
paragraph.Range.set_Style("navigatorHeadline");
//Debug
paragraph.Range.Select(); //selects the expected text (hello headline)
Word.Selection selection = word.Selection;
selection.set_Style("navigatorHeadline"); //style is not set :-(
Summarizing the steps to trouble-shoot that finally led to the answer:
1. First, make sure the bookmark is in the document and contains the correct text/range.
2. Check that the style name is spelled correctly, keeping in mind that Word handles style names as case-sensitive
3. Direct formatting and character styles will override the formatting of a paragraph style.
This last proved to be the reason style formatting was not appearing: the text was formatted with the Hyperlink style. This is a character style, so was overriding the formatting from the style specified in the code.
In this case, the character style must be removed in order to see the formatting from the paragraph style. Programmatically, this can be done EITHER
By applying the character style "Default Paragraph Font" to the Range
or
By using one of the "clear formatting" methods of the Selection object. Which to choose depends on the exact behavior desired. All formatting can be cleared, all direct formatting can be cleared, or the character style can be cleared (which would give the same result as option 1): Selection.ClearCharacterStyle.

Saving Word document in code-behind changes style names by language in Word 2013 Add in project

I have a problem with saving Active Document in Word 2013 that it changes style names after calling Save() Method.
Application.ActiveDocument.Save();
After I extract that .docx file, I see in styles.xml file that my style names has changed words by language. For example, I have a style name "heading 1", it changes it after save to "Otsikko11". Word "Otsikko" is finnish meaning heading.
How I can prevent this from happening?
My project is Word 2013 Add in
I found the answer how to prevent this from happening. When you create a new style with open xml sdk 2.5:
Style style = new Style()
{
Type = StyleValues.Paragraph,
StyleId = styleid,
CustomStyle = true // LEAVE THIS ONE OUT
};
You have to leave CustomStyle out. Then after saving word document it won't change style names anymore. I accidentally leaved this one out and things started to work out.

How can I insert a newline into a TextBlock without XAML?

I have created a WPF TextBlock inside a Label in code (XAML is not possible in my case) as follows:
Label l = new Label();
TextBlock tb = new TextBlock();
l.Content = tb;
I then come to a situation where I need to set the .Text property of TextBlock containing a new line, such as:
tb.Text = "Hello\nWould you please just work?";
I have tried numerous encodings (HTML encoding, ASCII encoding, etc.) of various newline combinations (carriage return, linefeed, carriage return plus linefeed, linefeed plus carriage return, double linefeed, double carriage return, etc... ad nauseum).
Answers should contain absolutely no XAML.
Answers should assume that the original objects were created using C# code and not XAML.
Answers should not refer to binding of WPF properties. No binding is being used. The "Text" property of the "TextBlock" object is being set. The newline must be inserted there.
If this is impossible, please let me know how I can programmatically add newlines by dynamically replacing each newline in an arbitrary input String into a LineBreak object (or whatever is needed to get this working). The input String will have arbitrary (readable text) contents that I am unable to anticipate in advance because the text itself is dynamic (user-defined); the source strings will have the linefeed character (aka LF, aka \n) but I can easily replace that with whatever is needed.
Also, if it is easier to do this with a Label directly rather than a TextBlock in a Label, that is good too -- I can use that. I just need a control with automatic plain text line wrapping.
You have a few choices:
Use the Environment.NewLine property:
TextBlock tb = new TextBlock();
tb.Text = "Hello" + Environment.NewLine + "Would you please just work?";
Or, manually add Runs and LineBreaks to the TextBlock:
TextBlock tb = new TextBlock();
tb.Inlines.Add(new Run("Hello"));
tb.Inlines.Add(new LineBreak());
tb.Inlines.Add(new Run("Would you please just work?"));
Just another small note. I had a similar problem and took the string from a resource file. What I noticed is that .NET delivered the string "\r\n" as "\\r\\n". When I corrected that by replacing the double-backslashes with normal backslashes everything worked as expected.
You can store string values in "Resources.resw", and get them in code directly.
In the VS resource editor itself not possible to add empty lines to string values. To do this, just edit value in any text editor, add empty lines how many you need, and "Copy -> Paste" to Value column of Visual Studio's resource editor.
For example: value of "Farewell" with 2 line breaks: Goodbye\n\nSave changes? - will look like this in text editor (and as it is, need to be copied to VS):
Goodbye
Save changes?
To get string value of the resource in C# code, call 1 of the following lines (UWP or WinUI3), depending on your application.
UWP code:
Windows.ApplicationModel.Resources.ResourceLoader.GetForCurrentView().GetString("Farewell");
WinUI3 code:
new ResourceLoader().GetString("Farewell");

C# RichTextBox colored text

I've a RichTextBox and I want color text in it. Is there any tag option? I'd like something like this [color:red]nick[/color] some message. Because I need to save it as text and I want on reload have also colored text.
Can I do something like this without writing own method?
You can set color for text in RichTextBox with SelectionColor
And if you want to save your rtf as plain text, then you will have to look at rtf format. Example:
{\rtf1\ansi\deff0 {\colortbl;\red0\green0\blue0;\red255\green0\blue0;}
This line is the default color\line \cf2 This line is red\line \cf1
This line is the default color }
EDIT:
From this example - first of all you have to declare color table \colortbl in fololowing format:
{\colortbl; color1; color2; ... ; colorN;}
And then in the text you will have to enclose text with {\cfN YOUR_TEXT} where N is a number of color from table; you can not specify the boundaries of the block {}, then everything after \ cfN will be one color.
As the name says RichTextBox contains RichText
to change the Rtf text with 'rtf specific-tags' you can set/use the
RichTextBox.RtfProperty
also take a look at RichTextBox.SelectionColor to color text patterns in code
but when you don't want to use rtf, you said
need to save as text.
you could write your own 'markup' there is no built in expect rtf/html?
but rtf is text - at all
Example to use RichTextBix.SelectionColor to Color the text
richTextBox1.Text = "Hello";
richTextBox1.Select(0,2);
richTextBox1.SelectionColor = Color.Red;
colors the start of "Hello" red
and now you can access the 'taggeg' text in the RTFProperty of the RichTextBox
If you need examples of how things are encoded in RTF, you can create the document manually in Word or Wordpad, and save it as RTF. This will give you a hint about how to encode your formatting. Furthermore, if you're for instance creating help-documents, you can include them as an embedded resource and load them directly into the RichTextBox, with all the formatting included.
rtfMain.SaveFile(dlgSave.FileName);
From Reference Save text from rich text box with C#

is there a way to add a bookmark that is different than the text in the pdf document

using migradoc, i see how you can add a bookmark automatically by doing this:
Paragraph p1 = document.LastSection.AddParagraph("Project Updates", "Heading2");
but what if i want to add a bookmark that says "Updates" but the text in the paragraph header says "My Project Updates"
is that possible?
When I needed bookmarks without visible text, I used a hack: white text with a very small font size (0.01).
I also created a style "Heading1WithoutBookmark" that is a clone of Heading1 but with
style.ParagraphFormat.OutlineLevel = OutlineLevel.BodyText;
This allows me to have the bookmark point to a page that only contains an image while the text is showing on the following page.
It also allows to have different text on the page and in the bookmark.

Categories