c# wpf export RichTextBox formatting to xml document - c#

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;
}

Related

How to show RichTextBox content in DataGridView

I want to display .Rtf file content in a DataGridView using this code:
System.Windows.Forms.RichTextBox rtBox = new System.Windows.Forms.RichTextBox();
rtBox.Rtf = System.IO.File.ReadAllText(RFileNm);
GridVeds.Rows[i].Cells[0].Value = rtBox.Text;
But some text showing as square i.e for:
{\rtf1\ansi\ansicpg1252\deff0\deftab1134{\fonttbl{\f0\fnil\fprq2\fcharset2
RuchaBold;}} {\colortbl ;\red0\green0\blue0;}
\viewkind4\uc1\pard\nowidctlpar\cf1\lang1033\f0\fs36 P'b4'd4mk
DrtrRn'd6p'a4mt; nlMt'b4pvR'b7ikm'd1pJf, 'a6mh'e7'b4
s'cdM/v,m irhRp'8emW'c1ikR 'c8\par irp'b0m'b0'b4ykR
'ed'c0rmyh,qrRim poFtR'a4mSurp'b0R?m w'cd Lmpup'b0Ryp'f8mfr
jRuh'fe 'c8'c81'c8'c8\par }
How I can solve this problem ?

c# FlowDocument Replace Text with Image, without break after

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.

Inability to properly load Rtf to a RichTextBox

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 ..

underline portion of text using iTextSharp

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);

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