ALIGN_JUSTIFIED for iText list item - pdf

I want to set alignment to list items by writing this code -
ListItem alignJustifiedListItem =
new ListItem(bundle.getString(PrintKeys.AckProcess), normalFont8);
alignJustifiedListItem.setAlignment(Element.ALIGN_JUSTIFIED);
I see this doesn't make any change on alignment (defaulted as left aligned). Changing it to
alignJustifiedListItem.setAlignment(Element.ALIGN_JUSTIFIED_ALL); is actually working but then the last line of the content also expands (as mentioned in doc, as well)
I dont understand when ListItem extends Paragraph, how setAlignment() behaviour can change. I don't see any overriding as well.

Please take a look at the ListAlignment example.
In this example, I create a list with three list items of which I set the alignment to ALIGN_JUSTIFIED:
List list = new List(List.UNORDERED);
ListItem item = new ListItem(text);
item.setAlignment(Element.ALIGN_JUSTIFIED);
list.add(item);
text = "a b c align ";
for (int i = 0; i < 5; i++) {
text = text + text;
}
item = new ListItem(text);
item.setAlignment(Element.ALIGN_JUSTIFIED);
list.add(item);
text = "supercalifragilisticexpialidocious ";
for (int i = 0; i < 3; i++) {
text = text + text;
}
item = new ListItem(text);
item.setAlignment(Element.ALIGN_JUSTIFIED);
list.add(item);
document.add(list);
If you look at the result, you can see that the alignment works as expected:
I deliberately introduced a very long word such as "supercalifragilisticexpialidocious" to show you that all lines but the last are indeed justified.
Update:
In a comment, you claim that the alignment is wrong when you introduce the \ character, and you want me to fix iText. However, there is nothing to fix.
I have adapted the original example like this:
text = "a b c align ";
for (int i = 0; i < 5; i++) {
text = text + "\\" + text;
}
item = new ListItem(text);
item.setAlignment(Element.ALIGN_JUSTIFIED);
list.add(item);
text = "supercalifragilisticexpialidocious ";
text = text + text;
text = text + text;
text = text + "\n" + text;
item = new ListItem(text);
item.setAlignment(Element.ALIGN_JUSTIFIED);
list.add(item);
In the first case, I have introduce the \ character. This didn't change anything to the behavior of the ListItem. In the second case, I introduce a newline character. The result was as expected: a newline character was introduced and the last line of every "paragraph" that was defined by the newline character was indeed not justified. That is what one would normally expect. I would introduce a bug if I would change this.
This is the screen shot of the result:
The introduction of the '\' character in the lines with "a b c align " doesn't have any effect on the alignment. The introduction of the newline half way the "supercalifragilisticexpialidocious " part breaks the list item in two parts. The final line of each part is not justified, which is the desired behavior.
If you do not want this desired behavior, you have to parse the content first and remove all newlines characters (carriage return and line feed).
Update:
In a new comment, you mention the '\' character as an escape character for the ''' character (actually the \' character). I have adapted the original example once more:
text = "a b c\' align ";
for (int i = 0; i < 5; i++) {
text = text + text;
}
item = new ListItem(text);
item.setAlignment(Element.ALIGN_JUSTIFIED);
list.add(item);
The result looks like this:
The text is justified correctly. However, I can imagine that problems can occur if you handle Strings with escape characters incorrectly. In this case, the '\'' character was hardcoded. If you obtain the String from a database and you read that String incorrectly, then you can have strange results. Especially from my days as a PHP developer, I remember instances where a single quote ended up to be stored like this '\\\'' in a database if you didn't watch out.

Related

How to get NPOI Excel RichStringCellValue?

I am using DotNetCore.NPOI (1.2.1) in order to read an MS Excel file.
Some of the cells are of type text and contain formatted strings (e.g. some words in bold).
How do I get the formatted cell value? My final goal: Retrieve the cell text as HTML.
I tried
var cell = row.GetCell(1);
var richStringCellValue = cell.RichStringCellValue;
But this won't let me access the formatted string (just the plain string without formattings).
Does anybody have an idea or solution?
I think you'll have to take longer route in this case. First you'll have to maintain the formatting of cell value like date, currency etc and then extract the style from cell value and embed the cell value under that style.
best option is to write extenstion method to get format and style value.
To get the fomat Please see this link How to get the value of cell containing a date and keep the original formatting using NPOI
For styling first you'll have to check and find the exact style of running text and then return the value inside the html tag , below method will give you idea to extract styling from cell value. Code is untested , you may have to include missing library.
public void GetStyleOfCellValue()
{
XSSFWorkbook wb = new XSSFWorkbook("YourFile.xlsx");
ISheet sheet = wb.GetSheetAt(0);
ICell cell = sheet.GetRow(0).GetCell(0);
XSSFRichTextString richText = (XSSFRichTextString)cell.RichStringCellValue;
int formattingRuns = cell.RichStringCellValue.NumFormattingRuns;
for (int i = 0; i < formattingRuns; i++)
{
int startIdx = richText.GetIndexOfFormattingRun(i);
int length = richText.GetLengthOfFormattingRun(i);
Console.WriteLine("Text: " + richText.String.Substring(startIdx, startIdx + length));
if (i == 0)
{
short fontIndex = cell.CellStyle.FontIndex;
IFont font = wb.GetFontAt(fontIndex);
Console.WriteLine("Bold: " + (font.IsBold)); // return string <b>my string</b>.
Console.WriteLine("Italics: " + font.IsItalic + "\n"); // return string <i>my string</i>.
Console.WriteLine("UnderLine: " + font.Underline + "\n"); // return string <u>my string</u>.
}
else
{
IFont fontFormat = richText.GetFontOfFormattingRun(i);
Console.WriteLine("Bold: " + (fontFormat.IsBold)); // return string <b>my string</b>.
Console.WriteLine("Italics: " + fontFormat.IsItalic + "\n");// return string <i>my string</i>.
}
}
}
Font formatting in XLSX files are stored according to schema http://schemas.openxmlformats.org/spreadsheetml/2006/main which has no direct relationship to HTML tags. Therefore your task is not that much straight forward.
style = cell.getCellStyle();
font = style.getFont(); // or style.getFont(workBook);
// use Font object to query font attributes. E.g. font.IsItalic
Then you will have to build the HTML by appending relevant HTML tags.

How do you split data from a textfile on an array list?

I am trying to code an array list that contains information from a text file that should add all the characters of the names together to give me a total. I have done it but it adds the spaces to, i have tried using .split(" "); but it still didnt work.
here is my code so far
String tempLatinName = " ";
String latinLength = " ";
int letters = 0;
for (int i = 0; i < info.size(); i++) {
tempLatinName = info.get(i).getLatinName();
tempLatinName.split(" ");
latinLength = tempLatinName;
letters += latinLength.length();
}
System.out.println("Total number of letters in all Latin names = " + letters);
any suggestions?
If you want to get the number of characters in your string, instead of tempLatinName.split(" "); you should try latinLength = tempLatinName.replace(" ",""); and then you would get the length with the string without spaces with latinLength.Length
More about replace here
More about Length here
based from here
have you tried the following:
tempLatinName.split(' ');
or
tempLatinName.split();

Lucene Highlighter class: highlight different words in different colors

Probably most people reading the title who know a bit about Lucene won't need much further explanation. NB I use Jython but I think most Java users will understand the Java equivalent...
It's a classic thing to want to do: you have more than one term in your search string... in Lucene terms this returns a BooleanQuery. Then you use something like this code to highlight (NB I am a Lucene newbie, this is all closely tweaked from Net examples):
yellow_highlight = SimpleHTMLFormatter( '<b style="background-color:yellow">', '</b>' )
green_highlight = SimpleHTMLFormatter( '<b style="background-color:green">', '</b>' )
...
stream = FrenchAnalyzer( Version.LUCENE_46 ).tokenStream( "both", StringReader( both ) )
scorer = QueryScorer( fr_query, "both" )
fragmenter = SimpleSpanFragmenter(scorer)
highlighter = Highlighter( yellow_highlight, scorer )
highlighter.setTextFragmenter(fragmenter)
best_fragments = highlighter.getBestTextFragments( stream, both, True, 5 )
if best_fragments:
for best_frag in best_fragments:
print "=== best frag: %s, type %s" % ( best_frag, type( best_frag ))
html_text += "&bull %s<br>\n" % unicode( best_frag )
... and then the html_text is put in a JTextPane for example.
But how would you make the first word in your query highlight with a yellow background and the second word highlight with a green background? I have tried to understand the various classes in org.apache.lucene.search... to no avail. So my only way of learning was googling. I couldn't find any clues...
I asked this question four years ago... At the time I did manage to implement a solution using javax.swing.text.html.HTMLDocument. There's also the interface org.w3c.dom.html.HTMLDocument in the standard Java library. This way is hard work.
But for anyone interested there's a far simpler solution. Taking advantage of the fact that Lucene's SimpleHTMLFormatter returns about the simplest imaginable "marked up" piece of text: chosen words are highlighted with the HTML B tag. That's it. It's not even a "proper" HTML fragment, just a String with <B>s and </B>s in it.
A multi-word query generates a BooleanQuery... from which you can extract multiple TermQuerys by going booleanQuery.clauses() ... getQuery()
I'm working in Groovy. The colouring I want to apply is console codes, as per BASH (or Cygwin). Other types of colouring can be worked out on this model.
So you set up a map before to hold your "markup details":
def markupDetails = [:]
Then for each TermQuery, you call this, with the same text param each time, stipulating a different colour param for each term. NB I'm using Lucene 6.
def createHighlightAndAnalyseMarkup( TermQuery tq, String text, String colour ) {
def termQueryScorer = new QueryScorer( tq )
def termQueryHighlighter = new Highlighter( formatter, termQueryScorer )
TokenStream stream = TokenSources.getTokenStream( fieldName, null, text, analyser, -1 )
String[] frags = termQueryHighlighter.getBestFragments( stream, text, 999999 )
// not sure under what circs you get > 1 fragment...
assert frags.size() <= 1
// NB you don't always get all terms in all returned LDocuments...
if( frags.size() ) {
String highlightedFrag = frags[ 0 ]
Matcher boldTagMatcher = highlightedFrag =~ /<\/?B>/
def pos = 0
def previousEnd = 0
while( boldTagMatcher.find()) {
pos += boldTagMatcher.start() - previousEnd
previousEnd = boldTagMatcher.end()
markupDetails[ pos ] = boldTagMatcher.group() == '<B>'? colour : ConsoleColors.RESET
}
}
}
As I said, I wanted to colourise console output. The colour parameter in the method here is per the console colour codes as found here, for example. E.g. yellow is \033[033m. ConsoleColors.RESET is \033[0m and marks the place where each coloured bit of text stops.
... after you've finished doing this with all TermQuerys you will have a nice map telling you where individual colours begin and end. You work backwards from the end of the text so as to insert the "markup" at the right position in the String. NB here text is your original unmarked-up String:
markupDetails.sort().reverseEach{ pos, markup ->
String firstPart = text.substring( 0, pos )
String secondPart = text.substring( pos )
text = firstPart + markup + secondPart
}
... at the end of which text contains your marked-up String: print to console. Lovely.

How to setText in a textArea from an ArrayList?

I have an ArrayList ArrayList<String> externalDataList = new ArrayList<>(1600);and I would like to display in a textArea first 3 strings, but I can't succed:
Here is my code
textareaShowPreview.setPrefRowCount(3);
Iterator<String> it = externalDataList.iterator();
int tot = 0;
while(it.hasNext() && tot<3){
String element = it.next();
textareaShowPreview.setText(element + "\n");
System.out.println("elements are: " + element);
tot++;
}
The sout correctly print first 3 strings
element are: 23/05/2007 ,30.9455,31.2545,30.9091,30.9545,7518142
element are: 24/05/2007 ,30.6545,31.0909,30.5364,30.6909,12851606
element are: 25/05/2007 ,30.6636,30.8545,30.4818,30.8091,9392088
but in textArea I have only first one
How do I have to modify my code to show in textArea all three strings, one string per row?
Use appendText instead of setText here is a link.
The setText, delete the previous text and set the text you are giving to it. The append keep the current text in your text area.
Hope it helps!

Insert text into flex 3 textarea

I have a textArea and a list. When a user double clicks a list item, the label of the selected item should be inserted into the textarea. When a text is selected in the textArea, it should be replaced, otherwise the text just needs to be inserted into the existing text at the caret point.
I've managed to get the text and everything, I just can't manage to insert it at the caret point. Does anyone know how to do this?
It's actually not JavaScript but Adobe Flex 3. Thanks for the help though, it did push me in the right direction. This is the way its done in Flex 3:
var caretStart:int = textArea.selectionBeginIndex;
var caretEnd:int = textArea.selectionEndIndex;
textArea.text = textArea.text.substring(0,caretStart)
+ newText
+ textArea.text.substr(caretEnd);
The accepted answer works great if you do not have existing HTML formatting. In my case, I inserted a new button into the editor that the user could click to put in a key word. I kept losing all HTML formatting until I dug around in the actual class and sided with a TextRange object:
public function keyWord_Click(event:Event) : void
{
var caretStart:int = txtEditor.textArea.selectionBeginIndex;
var caretEnd:int = txtEditor.textArea.selectionEndIndex;
var newText : String = "[[[KEYWORD]]]";
var tf:TextRange = new TextRange(txtEditor,true,caretStart,caretEnd);
tf.text = newText;
}
The nice thing about this approach is, you can also apply conditional formatting to that TextRange object as needed.
You can use txtarea.selectionStart and txtarea.selectionEnd to get Selected text position.
After that, You delete txt and add new selected text.
I don't known much about Javascript, so I wrote it for U.
You can search on google with keywords:
"Javascript Selected Text TextArea"
"Javascript add text at position"
Sample code:
function insertAtCursor(myField, myValue) {
//IE support
if (document.selection) {
myField.focus();
sel = document.selection.createRange();
sel.text = myValue;
}
//MOZILLA/NETSCAPE support
else if (myField.selectionStart || myField.selectionStart == '0') {
var startPos = myField.selectionStart;
var endPos = myField.selectionEnd;
myField.value = myField.value.substring(0, startPos)
+ myValue
+ myField.value.substring(endPos, myField.value.length);
} else {
myField.value += myValue;
}
caretPos = doGetCaretPosition(myField);
alert(caretPos);
setCaretPosition(myField,caretPos-3);
}