Apply bold formatting to specific text on Powerpoint textbox programmatically - c#

I have a code that iterates through all the shapes in a Powerpoint presentation (single slide), finds the one that is a textbox and checks whether it is the one I want to replace the text with (and does so if it is, obviously).
All that is working fine, but I want to set the text bold in 2 parts of the text: the name of the person and the name of the course (it's a diploma). I have tried adjusting the ideas/code from this answer, but to no success.
Could anybody help me?
Below is the code I have:
Presentation certificadoCOM = powerpointApp.Presentations.Open(#"C:\Users\oru1ca\Desktop\certCOM.pptx");
// iterates through all shapes
foreach (Shape shape in certificadoCOM.Application.ActivePresentation.Slides.Range().Shapes)
{
// gets the name of the shape and checks whether is a textbox
string shapeName = shape.Name;
if (shapeName.StartsWith("Text Box"))
{
// gets the text from the shape, and if it's the one to change, replace the text
string shapeText = shape.TextFrame.TextRange.Text;
if (shapeText.StartsWith("Concedemos"))
{
shape.TextFrame.TextRange.Text = "Concedemos à Sra. " + nomeP[i] + ",\n representando [...]";
}
}
}

TextRange has methods to select a range of text within the TextFrame.
For example, .Words(int) will select a selection of words (a set of characters separated via spaces) which you can then apply styles to (in this case .Bold.
Code example:
//Set the first 3 words as bold.
shape.TextFrame.TextRange.Words(3).Font.Bold = true;

Related

Finding list of objects that contain full or just part of searched string

I've a list of paragraphs. Each paragagraph can contain Text. I'm trying to search for a string that may be as whole within a single paragraph, or spread across multiple paragraphs with as bad case where each letter is different paragraph.
public List<WordParagraph> FindText(string text) {
List<WordParagraph> list = new List<WordParagraph>();
var found = false;
Paragraph currentParagraph = null;
foreach (var paragraph in this.Paragraphs) {
//if (currentParagraph == null) {
// currentParagraph = paragraph._paragraph;
//} else {
// if (currentParagraph != paragraph._paragraph) {
// found = false;
// }
//}
// paragraph.Text
// logic missing to find text that can start within some paragraph.Text, but
// can span across multiple paragraphs
// for example searching for text "This Is MyTest" within 4 paragraphs that
// may be written like
// paragraph.Text = "Thi"
// paragraph.Text = "s Is"
// paragraph.Text = " MyTes"
// paragraph.Text = "t"
}
return list;
}
I've tried some logic around foreach char in text, and nested loop over text from the paragraph.text but the logic was failing me.
To give you a bit of background. Consider a Word Document that has a single sentence - one long sentence but each word, or even letter is formatted differently - different font size, bold, underline or whatever. It looks like this:
Now what Word actually saved in the file is a single paragraph, but each paragraph has multiple "runs". The run contains a Text element. Each text element contains the text that you see in Word, but due to formatting of possibly even each word it can be split into many many small Text properties.
Now in my example, I've simplified the logic and for me, each "run" is a paragraph with a text. So List of WordParagraphs is a list of runs within Screenshot you see.
Now I need to find a string "I have that" from the whole sentence you see in word. That means I need to go thru all paragraphs, find the first letter that matches and then check if next letter matches as well, if not I need to start again.
My brain is having hard time to grasp this logic in code.

How to search and highlight a substring within button text? (C#)

I'd like to try and search an array of buttons for a particular string... if the string is found, would it be possible to highlight (bold/underline/change text colour) the substring within it? I've already got the below code but it changes the font colour of the whole text within the button.....
buttons[i].GetComponentInChildren<Text>().color = Color.red;
Here's an example of what I'm trying to do:
I have an array of 3 buttons with texts bench, bend and beneficial respectively. I'd like to search those strings for the substring ben. If it's found I'd like to change the text colour of just that substring within the word.
Enable RichText on the Text component itself.
You can then wrap part of text with a color markdown like so:
<color=red>ben</color>eficial
Code-wise, you only have to fetch the current text (and remove any markdown) first, then replace all of your occurrences of the word to match with the exact same word, but a wrapper around it, like so:
[SerializeField]
private Text targetText;
void Start()
{
// Ensures that this text can support rich text.
// (Or enable it yourself in the inspector.)
targetText.supportRichText = true;
WrapMatchingWordInRed("benef");
}
public void WrapMatchingWordInRed(string wordToMatch) {
// Will remove any color-related markdown expression from your text.
var currText = Regex.Replace(targetText.text, "<.*?>", string.Empty);
// Apply red-color to words that matches.
string textWithMarkdown = currText.Replace(wordToMatch, "<color=red>" + wordToMatch + "</color>");
targetText.text = textWithMarkdown;
}
It will look like this:

Getting a paragraph value in MigraDoc

I've got a line here :
Paragraph par = row.Cells[0].AddParagraph("Value");
Is there a way to get the text value from par? I have tried par.GetValue() but that didn't work
Paragraphs can contain a mix of text with different sizes, fonts, attributes along with images and other things.
Here's a code snippet that gets the first text element:
if (para.Elements.Count > 0)
{
Text t = para.Elements[0] as Text;
if (t != null)
{
string s = t.Content;
...
}
}
You know what your code adds to the paragraph, so you should know what you have to extract.
I do not know what you are trying to do. Every MigraDoc document object has a Tag member for custom use. You can assign any object (including string) to this Tag.

Displaying coloured text in a RichTextbox

so i have a string of characters that are typically formatted like this:
" text" where the bold character is red.
i want to display these types of strings in a richtextbox with the bold character being red.
i have the text in a string variable and i have the location of the red character (in the string) in an int variable.
my solution is:
get characters before the red character
get red character
get characters after the red character
display characters before the red character
display red character (with foreground = Brushes.Red)
display characters after the red characters
this is what i've got so far:
https://github.com/icebbyice/rapide/blob/master/rapide/SpreadWindow.xaml.cs
find: "//stackoverflow" (also, seperateOutputs is not completed)
i stopped there because i thought there had to be a more efficient way to do it because i will be changing the content of the rich text box often (up to 1000 content changes / 60 seconds).
so, is there a better way to do this?
You could do this:
// getting keywords/functions
string keywords = #"\b(e)\b";
MatchCollection keywordMatches = Regex.Matches(codeRichTextBox.Text, keywords);
// saving the original caret position + forecolor
int originalIndex = codeRichTextBox.SelectionStart;
int originalLength = codeRichTextBox.SelectionLength;
Color originalColor = Color.Black;
// MANDATORY - focuses a label before highlighting (avoids blinking)
menuStrip1.Focus();
// removes any previous highlighting (so modified words won't remain highlighted)
codeRichTextBox.SelectionStart = 0;
codeRichTextBox.SelectionLength = codeRichTextBox.Text.Length;
codeRichTextBox.SelectionColor = originalColor;
// scanning...
foreach (Match m in keywordMatches)
{
codeRichTextBox.SelectionStart = m.Index;
codeRichTextBox.SelectionLength = m.Length;
codeRichTextBox.SelectionFont = new Font(codeRichTextBox.Font, FontStyle.Bold);
}
// restoring the original colors, for further writing
codeRichTextBox.SelectionStart = originalIndex;
codeRichTextBox.SelectionLength = originalLength;
codeRichTextBox.SelectionColor = originalColor;
codeRichTextBox.SelectionFont = new Font(codeRichTextBox.Font, FontStyle.Regular);
// giving back the focus
codeRichTextBox.Focus();
That belongs in the RichTextBox TextChanged Event
If you type e, it will display it Bold. Any other text will be displayed as Font.Regular
If you would like to change the syntax from e, then look at the keywords string
This is all I have for this, I hope it helps you :)

How to highlight text using string indexes in WPF RichTextBox?

I'm working on a custom RichTextBox which highlights certain words typed in it.
(more like highlight certain strings, because I intent to highlight strings that are not separated by spaces)
I search for strings by loading the text to memory, and looking for a list of strings one by one, then applying formatting to them.
Issue is that, index I get from the plain text representation, doesn't necessarily point to the same position in the RichTextBox's content, when formatting is applied.
(First formatting is perfect. Any subsequent formatting starts to slip to the left. I assume this is because formatting adds certain elements to the documents which makes my indexes incorrect.)
Sample pseudo code for this is as follows.
// get the current text
var text = new TextRange(Document.ContentStart, Document.ContentEnd).Text;
// loop through and highlight
foreach (string entry in WhatToHighlightCollection)
{
var currentText = text;
var nextOccurance = currentText.IndexOf(suggestion); //This index is Unreliable !!!
while (nextOccurance != -1)
{
// Get the offset from start. (There appears to be 2 characters in the
// beginning. I assume this is document and paragraph start tags ??
// So add 2 to it.)
int offsetFromStart = (text.Length) - (currentText.Length) + 2;
var startPointer = Document.ContentStart.
GetPositionAtOffset(offsetFromStart + nextOccurance, LogicalDirection.Forward);
var endPointer = startPointer.GetPositionAtOffset(suggestion.Length, LogicalDirection.Forward);
var textRange = new TextRange(startPointer, endPointer);
textRange.ApplyPropertyValue(TextElement.BackgroundProperty, new SolidColorBrush(Colors.Yellow));
textRange.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Bold);
textRange.ApplyPropertyValue(TextElement.FontFamilyProperty, new FontFamily("Segoe UI"));
// Go to the next occurance.
currentText = currentText.Substring(nextOccurance + suggestion.Length);
nextOccurance = currentText.IndexOf(suggestion);
}
}
How do I map string indexes to rich text box content ?
NOTE: I'm not worried about the performance of this at the moment, although any suggestions are always welcome, as currently I run this on every TextChanged event to highlight 'as the user type' and it's getting a bit sluggish.

Categories