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.
Related
I have a generated RTF FlowDocuments with "[x]" and "[ ]" and need to replace them with checkboxes.
Currently I use Images, looping and do it like this:
//rtf_vorschau is a Flowdocumentreader
while (SelectPlaceholderRTF("[X]", rtf_vorschau))
{
using (MemoryStream tmpStream = new MemoryStream())
{
//WPF
RichTextBox tmprtf = new RichTextBox();
Image tmpimg = new Image();
Paragraph tmppara = new Paragraph();
tmpimg.Source = new ImageSourceConverter().ConvertFromString("Sonstiges\\checkbox_checked.PNG") as ImageSource;
tmppara.Inlines.Add(tmpimg);
tmprtf.Document.Blocks.Add(tmppara) ;
TextRange tmprange = new TextRange(tmprtf.Document.ContentStart, tmprtf.Document.ContentEnd);
tmprange.Save(tmpStream, DataFormats.XamlPackage);
rtf_vorschau.Selection.Load(tmpStream, DataFormats.XamlPackage);
}
}
This works, but my Problem is the Linebreak behind.
So "[X] bla bla" is changing to "(the checkbox image)(linebreak) bla bla" is there a simple way to avoid the linebreak after my Paragraph or "include" the image in the selected Run/Paragraph? or using a Forms RichTextBox or manipulate the final rtf file or add a checkbox directly? Finally it will be converted to a (readable) PDF, so replacing it inside the PDF can be another solution.
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);
}
I have a custom RichTextBox that derives from the RichTextBox base class. Its purpose is to display formatted text. However, any Rtf loaded is displayed as simple text without any formatting: font, font-size, font-style etc.
I have tried the following code to load the Rtf: (Note: rtbEx is the extended richtextbox control; RTF is a string containing the Rtf)
Using a file stream:
FileStream tempFile = File.Open(#"C:\RTF.rtf", FileMode.Open);
tempFile.Position = 0;
rtbEx.LoadFile(tempFile, RichTextBoxStreamType.RichText);
tempFile.Close();
Loading from the specified path:
rtbEx.LoadFile(#"C:\Users\Wilbur Omae\Desktop\RTF.rtf", RichTextBoxStreamType.RichText);
Directly setting the Rtf:
rtbEx.Rtf = RTF;
On checking the Rtf of the rtbEx, it seems to be perfect Rtf, yet it is displayed as plain text.
What could be the issue?
Update 1:
The custom RichTextBox is a control within a custom Form which it to be displayed as a TabPage.
you can use Clipboard in this case :
Clipboard.SetText(RichTextBox1.Rtf, TextDataFormat.Rtf);
and paste it
RichTextBox1.Text= Clipboard.GetText()
It works for me .. try it
As a workaround, I ensured the Rtf was set only when the form had been shown by trapping the Form.Shown event as shown below:
public class SermonReader : Form
{
public RichTextBoxEx rtbEx= new RichTextBoxEx();
private string RTF = "";
public SermonReader(string rtf)
{
RTF = rtf;
Shown += new EventHandler(ehFormShown);
FormBorderStyle = FormBorderStyle.None;
TopLevel = false;
Controls.Add(rtbEx);
rtbEx.Dock = DockStyle.Fill;
}
private void ehFormShown(object sender, EventArgs e)
{
rtbEx.Rtf = RTF;
}
}
I don't know why the issue is this complicated but I hope this helps.
Any other solution? Feel free to comment or answer.
I had the same problem with a richtextbox within a winformscontrol
within a dialog (MFC), the rtb should be filled with rtf, but
after setting RichTextBox.Rtf, loading from file or Clipboard it all was unformatted.
I could solved it by using Postmessage in OnInitDialog with UpdataData(FALSE) (Sets RichTextBox.Rtf again)
in the handler. seems as if creation yet was not complete ..
so in WPF i've created a RichTextBox and implemented the functionality to be able to format selected text (bold, undelined, font, etc...), but now i would like to export all of the formatting to a XML file, so when i would load it the loaded file would give me the same text with the same formatting.
I think that the best way to do this would be, if i could find each place where there is formatting in the RTB and then save it as a text range, but i dont know if RTB has a method for finding if a part of text is formatted.
Here is what i've got:
xaml:
<Button Name = "export" Click = "export_Click"/>
<RichTextBox x:Name="RTB"/>
and the c#:
private void export_Click(object sender, RoutedEventArgs e){
TextRange range = new TextRange();
//here is where i want to access the formatted areas
//something like: range = RTB.document.getBoldArea();
//and then i could export what i got in the text range to a xml file
}
thanks in advance to anyone willing to help!
You can actually access XAML content directly, which is itself obviously XML. You could either save this directly or manipulate/translate it into your own schema.
To get the XAML for a RichTextBox :
static string GetXaml(RichTextBox rt)
{
TextRange range = new TextRange(rt.Document.ContentStart, rt.Document.ContentEnd);
MemoryStream stream = new MemoryStream();
range.Save(stream, DataFormats.Xaml);
string xamlText = Encoding.UTF8.GetString(stream.ToArray());
return xamlText;
}
To set the XAML content for a RichTextBox :
static void SetXaml(RichTextBox rt, string xamlString)
{
StringReader stringReader = new StringReader(xamlString);
XmlReader xmlReader = XmlReader.Create(stringReader);
Section sec = XamlReader.Load(xmlReader) as Section;
FlowDocument doc = new FlowDocument();
while (sec.Blocks.Count > 0)
doc.Blocks.Add(sec.Blocks.FirstBlock);
rt.Document = doc;
}
I have an application that uses itextsharp to fill PDF form fields.
One of these fields has some text with tags. For example:
<U>This text should be underlined</>.
I'd like that the text closed in .. has to be underlined.
How could I do that?
How could I approch it with HTMLWorker for example?
Here's the portion of code where I write my description:
for (int i = 0; i < linesDescription.Count; i++)
{
int count = linesDescription[i].Count();
int countTrim = linesDescription[i].Trim().Count();
Chunk cnk = new Chunk(linesDescription[i] + GeneralPurpose.ReturnChar, TextStyle);
if (firstOpe && i > MaxLinePerPage - 1)
LongDescWrapped_dt_extra.Add(cnk);
else
LongDescWrapped_dt.Add(cnk);
}
Ordinary text fields do not support rich text. If you want the fields to remain interactive, you will need RichText fields. These are fields that are flagged in a way that they accept an RV value. This is explained here: Set different parts of a form field to have different fonts using iTextSharp (Note that I didn't succeed in getting this to work, but you may have better luck.)
If it is OK for you to flatten the form (i.e. remove all interactivity), please take a look at the FillWithUnderline example:
public void manipulatePdf(String src, String dest) throws DocumentException, IOException {
PdfReader reader = new PdfReader(src);
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
stamper.setFormFlattening(true);
AcroFields form = stamper.getAcroFields();
FieldPosition pos = form.getFieldPositions("Name").get(0);
ColumnText ct = new ColumnText(stamper.getOverContent(pos.page));
ct.setSimpleColumn(pos.position);
ElementList elements = XMLWorkerHelper.parseToElementList("<div>Bruno <u>Lowagie</u></div>", null);
for (Element element : elements) {
ct.addElement(element);
}
ct.go();
stamper.close();
}
In this example, we don't fill out the field, but we get the fields position (a page number and a rectangle). We then use ColumnText to add content at this position. As we are inputting HTML, we use XML Worker to parse the HTML into iText objects that we can add to the ColumnText object.
This is a Java example, but it should be easy to port this to C# if you know how to code in C# (which I don't).
You can trythis
Chunk chunk = new Chunk("Underlined TExt", FontFactory.GetFont(FontFactory.TIMES_ROMAN, 12.0f, iTextSharp.text.Font.BOLD | iTextSharp.text.Font.UNDERLINE));
Paragraph reportHeadline = new Paragraph(chunk);
reportHeadline.SpacingBefore = 12.0f;
pdfDoc.Add(reportHeadline);