Wpf Replace Text into RichTextBox - c#

I work in WPF C#, i want to replace text into RichtextBox
i load my rtf File who contain picture it's work fine.
If i use this :
ReposLettresFusion m_ReposLettresFusion = new ReposLettresFusion();
TextRange range = new TextRange(rtb.Document.ContentStart, rtb.Document.ContentEnd);
FileStream fStream = new FileStream(#pPath, FileMode.Create);
range.Text = m_ReposLettresFusion.Fusion(pPkGuidLettre, range.Text);
range.Save(fStream, DataFormats.Rtf);
fStream.Close();
rtb.LoadRtf(pPath);
m_ReposLettresFusion = null;
range = null;
It's change my text but i loose my picture and fonts all my formatting.
How i can replace text and keep all formatting of the Rtf
Thank you

Try this :
public void Fusion(ref Xceed.Wpf.Toolkit.RichTextBox pRichTextControl)
{
foreach (KeyValuePair<string, string> entry in LettreFusion)
{
string keyword = entry.Key;
string newString = entry.Value;
TextRange text = new TextRange(pRichTextControl.Document.ContentStart, pRichTextControl.Document.ContentEnd);
TextPointer current = text.Start.GetInsertionPosition(LogicalDirection.Forward);
while (current != null)
{
string textInRun = current.GetTextInRun(LogicalDirection.Forward);
if (!string.IsNullOrWhiteSpace(textInRun))
{
int index = textInRun.IndexOf(keyword);
if (index != -1)
{
TextPointer selectionStart = current.GetPositionAtOffset(index, LogicalDirection.Forward);
TextPointer selectionEnd = selectionStart.GetPositionAtOffset(keyword.Length, LogicalDirection.Forward);
TextRange selection = new TextRange(selectionStart, selectionEnd);
selection.Text = newString;
pRichTextControl.Selection.Select(selection.Start, selection.End);
pRichTextControl.Focus();
}
}
current = current.GetNextContextPosition(LogicalDirection.Forward);
}
}
}

Related

Read PDF Line By Line using iText7 and Fill on Textboxes Winforms

I am working on a WinForms application. I use the pdf file to reset the password and the values on pdf are stored as key-value pairs(email: xxxx#mail.com, pass: 11111).
What I want to do:
Read the PDF file line by line and fill the appropriate textboxes.
What I Have done:
public bool CreatePDF(string location, string email, string key)
{
if(location != "" && email != "" && key != "")
{
PdfWriter pdfwriter = new PdfWriter(location);
PdfDocument pdf = new PdfDocument(pdfwriter);
Document document = new Document(pdf);
Paragraph fields = new Paragraph("Email: "+email + "\n" + "Secret Key: "+key);
document.Add(fields);
document.Close();
return true;
}
else
{
return false;
}
}
public string ReadPDF(string location)
{
var pdfDocument = new PdfDocument(new PdfReader(location));
StringBuilder processed = new StringBuilder();
var strategy = new LocationTextExtractionStrategy();
string text = "";
for (int i = 1; i <= pdfDocument.GetNumberOfPages(); ++i)
{
var page = pdfDocument.GetPage(i);
text += PdfTextExtractor.GetTextFromPage(page, strategy);
processed.Append(text);
}
return text;
}
}
Thank you in advance Guys!. Any suggestions on CreatePDF are also welcome.
This is what I came up with,
var pdfDocument = new PdfDocument(new PdfReader("G:\\Encryption_File.pdf"));
StringBuilder processed = new StringBuilder();
var strategy = new LocationTextExtractionStrategy();
string text = "";
for (int i = 1; i <= pdfDocument.GetNumberOfPages(); ++i)
{
var page = pdfDocument.GetPage(i);
text += PdfTextExtractor.GetTextFromPage(page, strategy);
processed.Append(text);
}
text.Split('\n');
string line = "";
line = text + "&";
string[] newLines = line.Split('&');
textBox1.Text = newLines[0].Split(':')[1].ToString();
textBox2.Text = newLines[0].Split(':')[2].ToString();

c# - Trying to populate textbox and listview from txt file

I'm only able to load the textbox and can't seem to get the listview to populate. But, after I remove this.textBox1.Text = sr.ReadToEnd(); listview has populated. Here's code:
using (StreamReader sr = new StreamReader(openFileDialog1.FileName))
{
string line = String.Empty;
this.textBox1.Text = sr.ReadToEnd(); // remove it, listview working
while ((line = sr.ReadLine()) != null)
{
string[] data = line.Split(new char[0]);
ListViewItem item = new ListViewItem
{
Text = data[0]
};
item.SubItems.Add(data[1]);
listView1.Items.Add(item);
}
}
Screenshots:
Img1
Img2
Well, sr.ReadToEnd() reads the file upto its end, and that's why ReadLine() is of no use.
Let's read the file line by line and update text (which we'll assign to this.textBox1.Text) and listView1.Items:
StringBuilder text = new StringBuilder();
bool firstLine = true;
// We don't want redrawing after each ListViewItem adding
listView1.BeginUpdate();
try {
// File.ReadLines is easier to manipulate with StreamReader
// if you want just read lines
foreach (string line in File.ReadLines(openFileDialog1.FileName)) {
if (!firstLine)
sb.AppendLine();
sb.Append(line);
firstLine = false;
// 3: We want at most 3 chunks (item, subitem and tail to throw away)
string[] data = line.Split(new char[0], 3);
ListViewItem item = new ListViewItem() {
Text = data[0]
};
if (data.Length > 1)
item.SubItems.Add(data[1]);
listView1.Items.Add(item);
}
}
finally {
// The file has been scanned, items added; now we a ready to redraw the listView1
listView1.EndUpdate();
}
this.textBox1.Text = text.ToString();
You can use the following.
ReadToEnd does this: Reads all characters from the current position to the end of the stream. You are losing the position of the stream.
using (StreamReader sr = new StreamReader(openFileDialog1.FileName))
{
string line = String.Empty;
StringBuilder sb = new StringBuilder();
// this.textBox1.Text = sr.ReadToEnd(); // remove it, listview working
while ((line = sr.ReadLine()) != null)
{
string[] data = line.Split(new char[0]);
ListViewItem item = new ListViewItem
{
Text = data[0]
};
item.SubItems.Add(data[1]);
listView1.Items.Add(item);
sb.AppendLine(line);
}
this.textBox1.Text = sb.ToString();
}
You can try this:
string filename = openFileDialog1.FileName;
var lines = File.ReadAllLines(filename);
textBox1.Text = string.Join(Environment.NewLine, lines);
foreach ( string line in lines )
{
var items = line.Split(new char[0]);
if ( items.Length > 0 )
{
var item = new ListViewItem(items[0]);
if ( items.Length > 1 )
item.SubItems.Add(items[1]);
listView1.Items.Add(item);
}
}

Use different font for SyndicationFeed title than summary in richtextbox - C#

I am making an RSS Reader in C#. It gets the feed and adds it to a rich text box. Is there a way to have the title in a feed be a separate font than the summary in the rich text box? If so, how? Here is my code:
if (feedsList.SelectedItem != null)
{
feedTxt.Text = "";
string url = feedsList.GetItemText(feedsList.SelectedItem);
Uri myUri = new Uri(url, UriKind.Absolute);
XmlReader reader = XmlReader.Create(url);
SyndicationFeed feed = SyndicationFeed.Load(reader);
foreach (SyndicationItem item in feed.Items)
{
feedTxt.Text = feedTxt.Text + item.Title.Text;
feedTxt.Text = feedTxt.Text + "\n\n" + item.Summary.Text + "\n\n";
}
}
Thanks in advance!
You can use Selection property of on RichTextBox control. Something Like this:
if (feedsList.SelectedItem != null)
{
feedTxt.Text = "";
string url = feedsList.GetItemText(feedsList.SelectedItem);
Uri myUri = new Uri(url, UriKind.Absolute);
XmlReader reader = XmlReader.Create(url);
SyndicationFeed feed = SyndicationFeed.Load(reader);
foreach (SyndicationItem item in feed.Items)
{
// Store current content length of RichTextBox
int currentLength = feedTxt.Length;
// Append new content
feedTxt.Text += item.Title.Text + "\n\n";
feedTxt.Text += item.Summary.Text + "\n\n";
// Set the font for Title using selection
feedTxt.SelectionStart = currentLength.Length;
feedTxt.SelectionLength = item.Title.Text.Length;
feedTxt.SelectionFont = new System.Drawing.Font("Tahoma", 24);
// Set the font for Summary using selection
feedTxt.SelectionStart = currentLength + item.Title.Text.Length;
feedTxt.SelectionLength = item.Summary.Text;
feedTxt.SelectionFont = new System.Drawing.Font("Arial", 16);
// Reset Selection
txtTest.SelectionStart = 0;
txtTest.SelectionLength = 0;
}
}
Update
Looks like you can't append new content and style at the same time (possible limitation of Winforms?). My simple solution is to append all the content in one sweep and calculate all the selections you want to style and push them to a List.
Then you do a second pass looping through all your selections and do the styling.
You need this struct first:
struct ArticleSelection
{
public int TitleStart { get; set; }
public int TitleEnd { get; set; }
public int SummaryStart { get; set; }
public int SummaryEnd { get; set; }
};
Updated Code
if (feedsList.SelectedItem != null)
{
feedTxt.Text = "";
string url = feedsList.GetItemText(feedsList.SelectedItem);
Uri myUri = new Uri(url, UriKind.Absolute);
XmlReader reader = XmlReader.Create(url);
SyndicationFeed feed = SyndicationFeed.Load(reader);
// Create List to store our selections
List<ArticleSelection> articleSelections = new List<ArticleSelection>();
// Loop all incoming content
foreach (SyndicationItem item in feed.Items)
{
// Store current content length of RichTextBox
int currentLength = feedTxt.Length;
// Append new content
feedTxt.Text += item.Title.Text + "\n\n";
feedTxt.Text += item.Summary.Text + "\n\n";
// Calculate selection
articleSelections.Add(new ArticleSelection()
{
TitleStart = currentLength,
TitleEnd = feed.Item1.Length,
SummaryStart = currentLength + feed.Item1.Length,
SummaryEnd = feedTxt.Text - currentLength // This accounts for new lines above
}); ;
}
// Loop through the content and style it
foreach (ArticleSelection selection in articleSelections)
{
// Set the selection for Title
txtTest.SelectionStart = selection.TitleStart;
txtTest.SelectionLength = selection.TitleEnd;
txtTest.SelectionFont = new Font("Tahoma", 24);
// Set the selection for Summary
txtTest.SelectionStart = selection.SummaryStart;
txtTest.SelectionLength = selection.SummaryEnd;
txtTest.SelectionFont = new Font("Arial", 14);
}
// Remove Selection
txtTest.DeselectAll();
}
You should get something like this:

Display contents of Textfile data to ListView in C#

I have a listview in my form.
In my text file I have this:
24-7-2017:13:44:40;x;0.0078;y;-0.0147;z;0.9879;
24-7-2017:13:44:41;x;0.0069;y;-0.0069;z;1.0104;
24-7-2017:13:44:40; represents the time where I want to put in the first column of the listview
x;0.0078;y;-0.0147;z;0.9879; is where I want to create three columns to put the X,Y,Z in the each column and the data in the respective column
the next line will then be in row 2 in their respective column
they are separated by ";"
How I go about displaying it in the listview?
Try this
System.Windows.Forms.ListView listView = new System.Windows.Forms.ListView();
DateTime = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
X = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
Y = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
Z = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
SuspendLayout();
listView.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
DateTime,
X,
Y,
Z});
listView.GridLines = true;
listView.View = System.Windows.Forms.View.Details;
DateTime.Text = "DateTime";
X.Text = "X";
Y.Text = "Y";
Z.Text = "Z";
this.Controls.Add(this.listView);
StreamReader file = new StreamReader("filepath");
string sLine;
while ((sLine = file.ReadLine()) != null)
{
string[] sarr= sLine.Split(';');
StringBuilder sb = new StringBuilder(sarr[0]);
sb[sarr[0].IndexOf(':')] = ' ';
sarr[0] = sb.ToString().Replace(':', '.');
string[] sData = { sarr[0], sarr[2], sarr[4], sarr[6] };
ListViewItem item = new ListViewItem(sData);
listView.Items.Add(item);
}
after this you can add your first data into listView and then do for remain the same. And make sure your listView view property set to Details.
output:
Here is the new tested answer with the solution.
public Form1()
{
InitializeComponent();
//read the file
System.IO.StreamReader file =
new System.IO.StreamReader("yourFileName.txt");
//set list view in details mode
listView1.View = View.Details;
//Set columns in listview
listView1.Columns.Add("Date Time");
listView1.Columns.Add("X");
listView1.Columns.Add("Y");
listView1.Columns.Add("Z");
string line = "";
//read text file line by line.
while (( line = file.ReadLine()) != null)
{
var itemMC = new ListViewItem(new[] { line.ToString().Split(';')[0].ToString(), line.ToString().Split(';')[2].ToString(),
line.ToString().Split(';')[4].ToString(), line.ToString().Split(';')[6].ToString() });
listView1.Items.Add(itemMC);
}
file.Close();
}
Here is the output(from the given data in question) :

read /write html to/from slide of Powerpoint presentation

Is it possible to get slide html of PPT in C#.
and also how can we crate new slide using html while creating presentation using interop?
You can read from PPT file and get the text out of each slide, see below for an example :
static void Main(string[] args)
{
Microsoft.Office.Interop.PowerPoint.Application PowerPoint_App = new Microsoft.Office.Interop.PowerPoint.Application();
Microsoft.Office.Interop.PowerPoint.Presentations multi_presentations = PowerPoint_App.Presentations;
Microsoft.Office.Interop.PowerPoint.Presentation presentation = multi_presentations.Open(#"C:\PPT\myPowerpoint.pptx");
string presentation_text = "";
for (int i = 0; i < presentation.Slides.Count; i++)
{
foreach (var item in presentation.Slides[i+1].Shapes)
{
var shape = (PowerPoint.Shape)item;
if (shape.HasTextFrame == MsoTriState.msoTrue)
{
if (shape.TextFrame.HasText == MsoTriState.msoTrue)
{
var textRange = shape.TextFrame.TextRange;
var text = textRange.Text;
presentation_text += text+" ";
}
}
}
}
PowerPoint_App.Quit();
Console.WriteLine(presentation_text);
}

Categories

Resources