I have a WPF Project (with MVVM Light) that contains a RichTextBox control with Toolbar like below image
I try to store the formatted text ( user can change rich text box content style to 'Bold','Italics','underline' or increase or decrease the font size ) to sql lite database.
I am using TextRange class to capture the RichTextBox content.
/* Get Richtext box text. */
TextRange range;
range = new TextRange(((FlowDocument)document).ContentStart,
((FlowDocument)document).ContentEnd);
/* Get Richtext box text. */
But it's not captured correct text if the text is bold or italics. I googled many hours, but i can't find a right method to my requirement. Please advice if anyone have idea.
I don't know where the formatting data is stored in relation to the rich text box properties, but the TextRange.Text property is just a raw string of text.
My approach would be the extract the raw RTF data and save/load this accordingly. This also has the advantages of being able to be opened in any other rich text editor such as Microsoft Word.
To get an RTF string representation you can use this code:
var ms = new MemoryStream();
var doc = RichTextBox.Document;
var range = new TextRange(doc.ContentStart, doc.ContentEnd);
range.Save(ms, DataFormats.Rtf);
string rtfString = ASCIIEncoding.Default.GetString(ms.ToArray());
//You can then save this string to the database or whatever you want...
and to load an RTF string back into the RichTextBox you can use this code.
string rtfText = LoadTextFromDatabase() //However you read the saved string..
var ms = new MemoryStream(ASCIIEncoding.Default.GetBytes(rtfText));
RichTextBox.Selection.Load(ms, DataFormats.Rtf);
Hope this helps and is a suitable solution for you.
Related
I am trying to inset formatted footnotes into an open word document using a WinForms application.
While I am able to use Interop.Word to set plain text footnotes and so long as I use plain text it works fine. However, I also want the user to be able to paste rich text formatted text from a rich text box into the footnote. This never works and always shows the rich text codes.
I know that footnotes can take formatting because if I put the rich text int a clipboard and paste it into a footnote the formatting is preserved.
I have even tried putting the rich text into the clipboard and then setting the string (s) to the clipboard contents using "s = Clipboard.GetText(TextDataFormat.Rtf);" It seems as if this should be exactly what I am pasting, but if I paste into the footnote it works. If the program sets it using the code below it does not work.
I appreciate any help.
application = (Microsoft.Office.Interop.Word.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Word.Application");
application.ActiveDocument.Footnotes.Add(application.Selection.Range, "", s);
Cindy's answer was helpful. I fixed the problem by doing the following:
Saving the current selected position in the document and current clipboard contents.
Inserting a blank footnote.
Selecting the footnote.
Putting the string into the clipboard as rich text format.
Sending/pasting the information from the clipboard to Word.
Restoring the clipboard and original selected position in the document.
I'm writing a program to display the contents of an Excel worksheet using a Grid. To that end, I'm retrieving the worksheet as one big string full of XML using Office Interop, like so :
// Get the cells Range from Excel:
Range rng = sheet.get_Range(Cell(row1, col1), Cell(row2, col2));
// Get the XML representing that Range:
return rng.get_Value(XlRangeValueDataType.xlRangeValueXMLSpreadsheet);
I could create a FlowDocument from this XML string, and if I do assign it to a control on my GUI then that control will render the XML so that it looks exactly like what Excel shows. But I will have all the cells in the Range rendered onto a single control, which is not what I want : I want to be able to render any given cell onto any given control.
I couldn't find a fast and elegant way to extract the XML for individual cells via Interop : it just takes forever and a week. So I spent a whole day writing a class that parses the big XML string into an array of XML fragments each representing a cell. The strings in that array look like this :
<Cell><ss:Data ss:Type="String" xmlns="http://www.w3.org/TR/REC-html40"><Font html:Color="#000000">Some random text with </Font><B><Font html:Color="#000000">some bold characters</Font></B><Font html:Color="#000000">, and so on and so forth</Font></ss:Data></Cell>
This is actually HTML : from Visual Studio's debugger I can use the HTML viewer and it'll show me this :
Some random text with some bold characters, and so on and so forth
And by the way, this line was rendered correctly by the Stack Overflow website as soon as I pasted it in.
So I felt pretty confident that I could now create, programmatically, FlowDocument objects for each Excel cell, assign them to my GUI controls, and I'd get nice rendering of my Excel cells in any layout I care to program.
Except this doesn't work. When I put the FlowDocument into a control, the control just displays the HTML source code, it does not render it.
Here's how I create the FlowDocument :
FlowDocument tmp = new FlowDocument();
TextRange tr = new TextRange(tmp.ContentStart, tmp.ContentEnd);
byte[] byteArray = Encoding.ASCII.GetBytes(string_full_of_html);
MemoryStream stream = new MemoryStream(byteArray);
tr.Load(stream, DataFormats.Rtf);
(to explain : I allocate a FlowDocument, then create a TextRange through which I'll load the HTML, then turn my string full of HTML into a stream, then feed that stream to the TextRange)
I've tried different "DataFormats" : HTML, oddly, doesn't work. It gives me the exception "'HTML Format' data format not supported". RTF works but, like HTML, only displays the string I fed in, it doesn't render it.
Visual Studio can render my XML strings with its "HTML Visualizer", and I understand it is written with WPF. So I know there's a mechanism in there that does what I need, but I can't find it. That's where you come in, brave code Jedis !
Am writing data in .rtf Format from a RichTextBox using (Text is color coded )
RichTextBox .SaveFile(path);
There is a 'Clear Text' button on the GUI on click of which clears the RichTextBox .
The problem arises when new data is printed on the RichTextBox instead of appending the data the RichTextBox .SaveFile(path) method clears out the previous data and contains only the newly added data.
How can i append the data? StreamWriter is wrtitng the data in plain text i need it in .RTF.
Can anybody help me on this?
You can save the previous data in a variable, set the richTextBox's data to previous+new and then call the SaveFile method.
Seems like saving from the rich text box overwrites the file. You can have a look at this or this for more info.
Some of the solutions suggested are saving to a different file, or reading, concatenating, and saving.
There is no option to append text to RTF file as you have already read from the comments.
What you can do, however, is use 2 RichEdit controls, one that reads the stream in using EM_STREAMIN message (this will preserve the char format) and concatenate the new data to it. For the preservation of the char format of the new data from the other RichEdit control (colors,fonts etc), you have to use EM_GETCHARFORMAT message on the selection of the new data you want to concatenate. And then, you need to use EM_SETCHARFORMAT message with SCF_SELECTION OR SCF_WORD to set the char format on the RichEdit control that will hold all data together. After that, use EM_REPLACESEL message to concatenate all the data together. Finally, use EM_STREAMOUT message to save all of the stream at one go.
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#
I have a text file in which I have a word like $variable. I read it all and look if the "$variable" is in it. Then I want to replace the word "$variable" to the content of a text box and afterwards write the text in the same text file back.
If I use constantly strings like
string var = "hello";
It works. But can anyone tell me how to do this with the content of a text box?
This might help:
How to write to a file
http://msdn.microsoft.com/en-us/library/6ka1wd3w
and how to read from a file
http://msdn.microsoft.com/en-us/library/db5x7c0d
and to get the value from the textbox use
string textValue = txtMyValue.Text;
but then use the name you gave to your textbox