RichTextBox with source of rtf string displays incorrect - c#

I have string with rft formatted text. I believe th string is correct, because when i enter in in notepad and save as rtf document, it is displayed correctly.
The problem is that the highlight is not applied to the text when i try to pass it to RichTextBox.
Expected result is RichtextBox with grey bold text with highlighted word "PORTS", but i get only bold grey text
Rtf string that I pass to RichTextBox:
"{\rtf1\ansi\ansicpg1252\deff0\nouicompat\deflang1033{\fonttbl{\f0\fnil\fcharset0 Segoe UI;}}{\colortbl;\red50\green146\blue255;\red235\green153\blue45;\red105\green105\blue105;}\viewkind0\uc1\pard\sa0\sl276\slmult1\cf0\f0\fs32\lang9\b\cf3\highlight2 PORTS\highlight0 documentation. \cf0\b0\par}"
Rtf string that I save as rtf document:
{\rtf1\ansi\ansicpg1252\deff0\nouicompat\deflang1033{\fonttbl{\f0\fnil\fcharset0 Segoe UI;}}{\colortbl;\red50\green146\blue255;\red235\green153\blue45;\red105\green105\blue105;}\viewkind0\uc1\pard\sa0\sl276\slmult1\cf0\f0\fs32\lang9\b\cf3\highlight2 PORTS\highlight0 documentation. \cf0\b0\par}
Example of rtf string that is displayed correctly(here text is not bald and not grey):
"{\rtf1\ansi\ansicpg1252\deff0\nouicompat\deflang1033{\fonttbl{\f0\fnil\fcharset0 Segoe UI;}}{\colortbl;\red50\green146\blue255;\red235\green153\blue45;\red105\green105\blue105;}\viewkind0\uc1\pard\sa0\sl276\slmult1\cf0\f0\fs30\lang9\highlight2 Port\highlight0 Serial \highlight2 port\highlight0 that uses COM \highlight2 port\highlight0 s\par}"
Method that i use to set string to RithTextBox:
private void UpdateRtf()
{
MemoryStream stream = new MemoryStream(ASCIIEncoding.Default.GetBytes(RtfString));
TextRange range = new TextRange(Document.ContentStart, Document.ContentEnd);
range.Load(stream, DataFormats.Rtf);
}

Related

DocX Set BookMark font styles C#

I am using xceedsoftware/DocX to generate word documents from templates in C#, Unable to set styles for bookmark text alone. Trying to create extension, please find below code. I can only see option to set font styles for entire paragraph, not a single bookmark. Am I missing something. How do I set font style, background color, strikethrough, etc., for my bookmark text alone?
public static void ProcessBookMark(this DocX doc, string BookMarkName, string BookMarkValue, bool? Bold = false)
{
var Bm = doc.Bookmarks[BookMarkName];
if (Bm != null)
{
Bm.SetText(BookMarkValue);
Bm.Paragraph.Font("Arial");
if (Bold==true)
Bm.Paragraph.Bold();
}
}

How to get formatted text from RichTextBox and show it to TextBlock in WPF?

Following code is just not returning formatted text.
string StringFromRichTextBox(RichTextBox rtb)
{
TextRange textRange = new TextRange(
rtb.Document.ContentStart,
rtb.Document.ContentEnd
);
return textRange.Text;
}
I want to get formatted text and show it on TextBlock in wpf.

RichTextBox loses all the formatting when exporting to word

I copied word content to richtextbox without loosing format perfectly, but now I am editing the content in the richtextbox.
Now I want to export the richtextbox content to a word document without losing any formating, in C# using WinForms. How do you do it?
WordApp.ActiveDocument.SaveAsQuickStyleSet("abc.doc");
Range rng = WordApp.ActiveDocument.Range(0, 0);
for (int i = 0; i < _dgvrow.Cells.Count; ++i)
{
// add code to loop thru controls and TypeText into word document
Label lb = (Label)this.Controls["lblfield" + (i+1).ToString()];
rng.Text += lb.Text;
rng.Select();
Control ctrl = this.Controls["txtfield" + (i+1).ToString()];
if(ctrl is RichTextBox)
{
RichTextBox rb = (RichTextBox)ctrl;
rng.Text += rb.Text + Environment.NewLine;
rng.Select();
}
else if (ctrl is TextBox)
{
TextBox rb = (TextBox)ctrl;
rng.Text += rb.Text + Environment.NewLine;
rng.Select();
}
}
The Text property of a RichTextBox just returns plain text. Use the Rtf property to return rtf-formatted text.
Unfortunately, Word does not have a method for inserting RTF text. However you can paste RTF-text from the clipboard
Clipboard.SetText(rb.Rtf, TextDataFormat.Rtf);
rng.Paste()
You want to get the rich text format of your control, not just the plain text.
Replace rb.Text with rb.Rtf.
From MSDN:
The Text property does not return any information about the formatting applied to the contents of the RichTextBox. To get the rich text formatting (RTF) codes, use the Rtf property.
Additionally, if you want to save the rich text format to a file, that's built in:
rb.SaveFile(yourFilePath);
With running look over your say I can suggest which I coded correctly.
Save your coded rich text box with save file method as .rtf or .doc and then open in the microsoft word.
Will not fail.
with regards.

How to append \line into RTF using RichTextBox control

When using the Microsoft RichTextBox control it is possible to add new lines like this...
richtextbox.AppendText(System.Environment.NewLine); // appends \r\n
However, if you now view the generated rtf the \r\n characters are converted to \par not \line
How do I insert a \line control code into the generated RTF?
What does't work:
Token Replacement
Hacks like inserting a token at the end of the string and then replacing it after the fact, so something like this:
string text = "my text";
text = text.Replace("||" "|"); // replace any '|' chars with a double '||' so they aren't confused in the output.
text = text.Replace("\r\n", "_|0|_"); // replace \r\n with a placeholder of |0|
richtextbox.AppendText(text);
string rtf = richtextbox.Rtf;
rtf.Replace("_|0|_", "\\line"); // replace placeholder with \line
rtf.Replace("||", "|"); // set back any || chars to |
This almost worked, it breaks down if you have to support right to left text as the right to left control sequence always ends up in the middle of the placeholder.
Sending Key Messages
public void AppendNewLine()
{
Keys[] keys = new Keys[] {Keys.Shift, Keys.Return};
SendKeys(keys);
}
private void SendKeys(Keys[] keys)
{
foreach(Keys key in keys)
{
SendKeyDown(key);
}
}
private void SendKeyDown(Keys key)
{
user32.SendMessage(this.Handle, Messages.WM_KEYDOWN, (int)key, 0);
}
private void SendKeyUp(Keys key)
{
user32.SendMessage(this.Handle, Messages.WM_KEYUP, (int)key, 0);
}
This also ends up being converted to a \par
Is there a way to post a messaged directly to the msftedit control to insert a control character?
I am totally stumped, any ideas guys? Thanks for your help!
Adding a Unicode "Line Separator" (U+2028) does work as far as my testing showed:
private void Form_Load(object sender, EventArgs e)
{
richText.AppendText("Hello, World!\u2028");
richText.AppendText("Hello, World!\u2028");
string rtf = richText.Rtf;
richText.AppendText(rtf);
}
When I run the program, I get:
Hello, World!
Hello, World!
{\rtf1\ansi\ansicpg1252\deff0\deflang1031{\fonttbl{\f0\fnil\fcharset0 Courier New;}}
{\colortbl ;\red255\green255\blue255;}
\viewkind4\uc1\pard\cf1\f0\fs17 Hello, World!\line Hello, World!\line\par
}
It did add \line instead of \par.
Since you want to use a different RTF code, I think you may need to forget about the simplistic AppendText() method and manipulate the .Rtf property of your RichTextBox directly instead. Here is a sample (tested) to demonstrate:
RichTextBox rtb = new RichTextBox();
//this just gets the textbox to populate its Rtf property... may not be necessary in typical usage
rtb.AppendText("blah");
rtb.Clear();
string rtf = rtb.Rtf;
//exclude the final } and anything after it so we can use Append instead of Insert
StringBuilder richText = new StringBuilder(rtf, 0, rtf.LastIndexOf('}'), rtf.Length /* this capacity should be selected for the specific application */);
for (int i = 0; i < 5; i++)
{
string lineText = "example text" + i;
richText.Append(lineText);
//add a \line and CRLF to separate this line of text from the next one
richText.AppendLine(#"\line");
}
//Add back the final } and newline
richText.AppendLine("}");
System.Diagnostics.Debug.WriteLine("Original RTF data:");
System.Diagnostics.Debug.WriteLine(rtf);
System.Diagnostics.Debug.WriteLine("New Data:");
System.Diagnostics.Debug.WriteLine(richText.ToString());
//Write the RTF data back into the RichTextBox.
//WARNING - .NET will reformat the data to its liking at this point, removing
//any unused colors from the color table and simplifying/standardizing the RTF.
rtb.Rtf = richText.ToString();
//Print out the resulting Rtf data after .NET (potentially) reformats it
System.Diagnostics.Debug.WriteLine("Resulting Data:");
System.Diagnostics.Debug.WriteLine(rtb.Rtf);
Output:
Original RTF data:
{\rtf1\ansi\ansicpg1252\deff0\deflang1033{\fonttbl{\f0\fnil\fcharset0 Microsoft Sans Serif;}}
\viewkind4\uc1\pard\f0\fs17\par
}
New RTF Data:
{\rtf1\ansi\ansicpg1252\deff0\deflang1033{\fonttbl{\f0\fnil\fcharset0 Microsoft Sans Serif;}}
\viewkind4\uc1\pard\f0\fs17\par
example text0\line
example text1\line
example text2\line
example text3\line
example text4\line
}
Resulting RTF Data:
{\rtf1\ansi\ansicpg1252\deff0\deflang1033{\fonttbl{\f0\fnil\fcharset0 Microsoft Sans Serif;}}
\viewkind4\uc1\pard\f0\fs17\par
example text0\line example text1\line example text2\line example text3\line example text4\par
}
if you are using paragraphs to write to richtextbox you can use the LineBreak() same code shown below
Paragraph myParagraph = new Paragraph();
FlowDocument myFlowDocument = new FlowDocument();
// Add some Bold text to the paragraph
myParagraph.Inlines.Add(new Bold(new Run(#"Test Description:")));
myParagraph.Inlines.Add(new LineBreak()); // to add a new line use LineBreak()
myParagraph.Inlines.Add(new Run("my text"));
myFlowDocument.Blocks.Add(myParagraph);
myrichtextboxcontrolid.Document = myFlowDocument;
Hope this helps!

How to get RTF from RichTextBox

How do I get the text in RTF of a RichTextBox? I'm trying to get like this, but the property does not exist.
RichTextBox rtb = new RichTextBox();
string s = rtb.Rtf;
To get the actual XAML created by the user inside of the RichTextBox:
TextRange tr = new TextRange(myRichTextBox.Document.ContentStart,
myRichTextBox.Document.ContentEnd);
MemoryStream ms = new MemoryStream();
tr.Save(ms, DataFormats.Xaml);
string xamlText = ASCIIEncoding.Default.GetString(ms.ToArray());
EDIT: I don't have code in front of me to test, but an instance of the TextRange type has a Save (to stream) method that takes a DataFormats parameter, which can be DataFormats.Rtf
There are 2 RichTextBox classes, one from the winforms framework and one from the WPF framework:
System.Windows.Controls.RichTextBox wpfBox;
System.Windows.Forms.RichTextBox winformsBox;
Only the Winforms RichTextBox has an Rtf property, the other has a Document property which contains a FlowDocument.

Categories