Tail truncation for each 2 formatted text spans - c#

In our mobile app we have 2 DateTime values separated by a '-', e.g. "2022/07/13 00:00 - 2023/07/13 23:59". In landscape mode we achieve the formatting desired by using formatted text, spans and maxlines properties. In portrait mode however, we still desire displaying the values on 2 lines, but each span must be truncated with tail truncation. E.g.
20/07/2021 ...
20/07/2022 ...
I've tried something like and variations of:
control.MaxLines = 2;
control.LineBreakMode = LineBreakMode.TailTruncation;
control.FormattedText.Spans.Add(new Span { Text = dates[0] + seperator });
control.FormattedText.Spans.Add(new Span { Text = System.Environment.NewLine });
control.FormattedText.Spans.Add(new Span { Text = dates[1].TrimStart() });
It's worth mentioning that this logic should be functional for different widths of the custom control being used (based off of a label). Is there something small I'm missing or is this not possible using formatted text?
Thanks in advance!

Related

Apply bold formatting to specific text on Powerpoint textbox programmatically

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;

How many spaces does \t use in c#

I am building a report using StringBuilder and the details of it to be properly intended and aligned
for which i will be using
private static int paperWidth = 55; //it defines the size of paper
private static readonly string singleLine = string.Empty.PadLeft(paperWidth, '-');
StringBuilder reportLayout;
reportLayout.AppendLine("\t" + "Store Name");
I want Store Name in center and many such more feilds by use of \t
Thanks in Advance.
EDIT
I want to print like. Store Name in center
If you're simulating what tabs look like at a terminal you should
stick with 8 spaces per tab. A Tab character shifts over to the next
tab stop. By default, there is one every 8 spaces. But in most shells
you can easily edit it to be whatever number of spaces you want
You can realize this through the following Code:
string tab = "\t";
string space = new string(' ', 8);
StringBuilder str = new StringBuilder();
str.AppendLine(tab + "A");
str.AppendLine(space + "B");
string outPut = str.ToString(); // will give two lines of equal length
int lengthOfOP = outPut.Length; //will give you 15
From the above example we can say that in .Net the length of \t is
calculated as 1
A Tab is a Tab and its meaning is created by the application that renders it.
Think of a word processor where a Tab means:
Go to the next tab stop.
You can define the tab stops!
To center output do not use Tabs, use the correct StringFormat :
StringFormat fmt = new StringFormat()
{ Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center };
This centers the text inside a rectanlge in both directions:
e.Graphics.DrawString(someText, someFont, someBrush, layoutRectangle, fmt);
or something like it..
But it looks as if you want to embed the centering inside a text.
This will only work if you really know everything about the output process, i.e. the device, the Font and Size as well as the margins etc..
So it will probably not be reliable at all, no matter what you do.
The best alternative may be to either give up on plain text or use a fixed number of spaces to 'mean' 'centered' and then watch for this number when you render.
If you don't have control over the rendering, it will not work.

C# Equal Tab Spacing

So I have a C# program that collects a list of customers. The list displays Customer ID, Customer Name, and Customer Phone Number. The list is shown in a multi-line text box. My issue is, a customer is allowed to either use first and last name, or first middle and last name, and when the list is displayed, if one of the customers only put a first and last name, the phone number is literally right next to the name instead of tabbed like the others. I will demonstrate what I mean below.
Notice how Bob Anthony's phone number is off compared to Mary and John? What would I use to make sure that every line has the same space in the tabs?
While some type of a data grid or list view would probably be more appropriate, if you want to keep it in string form you can use some of the composite formatting features in String.Format - notably the alignment flag:
string.Format("{0,-8} {1,-20} {2}", stuff)
The negative/positive indicates left/right alignment. Note that strings aren't truncated for you, you'll have to do that if you don't already know the max width.
You should get length of the longest item and add space after other items so that all of them be equal. By the way, I suggest you to use DataGridView for your application. Something like this:
dataGridView1.Rows.Add(3);
dataGridView1.Rows[0].Cells[0].Value = customer.ID;
dataGridView1.Rows[0].Cells[1].Value = customer.Name;
dataGridView1.Rows[0].Cells[2].Value = customer.Phone;
As everyone has said a DataGridView is recomendable and easy to use, instead of truncating the information or padding it the user can resize the columns. If you still want to do it that way then you have to get each customer and format it accordingly:
var text = new StringBuilder();
foreach (var customer in Customers)
{
var format = String.Format("{0} {1} {2}\n",
FormatField(customer.Id,6),
FormatField(customer.Name,20),
FormatField(customer.Phone,10) // Might need extra formating
);
text.Append(format);
}
And to format it:
private string FormatField(object field, int size)
{
var value = field.ToString();
if (value.Length == size)
return value;
return value.Length > size
? value.Substring(0,size)
: value.PadRight(size, ' ');
}
Depending on where you display it you will see some inconsistencies, like its not the same "view width" the characters "iii" and "MMM" even that they have the same length.

Trying to pad decimal number with leading spaces

for (int iCount = 0; iCount < oForm.LineItems.Count; iCount++)
{
// cartDetails is a stringbuilder here.
cartDetails.Append(String.Format("{0:0}", oForm.LineItems[iCount].Quantity));
cartDetails.Append(String.Format("{0:0.00}", oForm.LineItems[iCount].Price));
cartDetails.Append(String.Format("{0:0.00}", oForm.LineItems[iCount].ExtendedPrice));
//cartDetails.Append(string.Format("{0,10:#,##0.00}", oForm.LineItems[iCount].Price) + "</TD><TD>");
//cartDetails.Append(string.Format("{0,10:#,##0.00}", oForm.LineItems[iCount].ExtendedPrice) + "</TD><TD>");
//cartDetails.Append(String.Format("{0}", oForm.LineItems[iCount].Quantity).PadLeft(4)+ "</TD><TD>");
//cartDetails.Append(String.Format("{0:0.00}", oForm.LineItems[iCount].Price).PadLeft(8) + "</TD><TD>");
I have pastd the source code I am using. I add qty, price, extendedprice and all are decimal columns. All I am looking to do is to pad left with leading spaces. Decimal rounding to 2 digits seems to be happening.
Those commented lines above are some of the other options I have tried.
Currently if qty has values such as 4 and 40, they don't get aligned when I print them in a table. Same with price.
CAn someone please suggest what am I doing here?
Update1: Tried Lucas suggestion, but it is not working. Here is what I am geting.
cartDetails.Append(String.Format("{0:0,10}", oForm.LineItems[iCount].Quantity));
When I try the above, it shows 10 for every line irrespective of the value in oForm.LineItems[iCount].Quantity.
And if I change
String.Format("{0:0,4}", it shows 04 for all the records
You can use AppendFormat method instead of appending formatted string.
Also correct format will be {index,padding:format}. And consider to use foreach instead of for:
foreach (var lineItem in oForm.LineItems)
{
cartDetails.AppendFormat("{0,4:0}", lineItem.Quantity);
cartDetails.AppendFormat("{0,10:0.00}", lineItem.Price);
// etc
}
Remark: This is for alignemend in caracter based representation such as text files
Have a look at the last section in composite formatting (MSDN).
First format the number as desired and the pad the result
cartDetails.AppendFormat("{0,4}", // padding with spaces
String.Format("{0:0}", oForm.LineItems[iCount].Quantity)); // format number
Addtition: If you want to position your data in a html table you should use css (or inline styles)
<td class="right">This is right aligned</td>
with css
.right { text-align: right; }
or inlined:
<td style="text-align: right">This is right aligned</td>

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