wordprocessingml footnote number style (superscripts) - apache-poi

I just added a footnote to the word document.
but it seems little bit wierd.
Footnote numbers are usually entered as superscripts, but not now.
How can I insert a footnote number as a superscript?
this is my code..
r = p.createRun()
String footnoteText = "exexexex "
BigInteger footnoteId = createFootnote(document, footnoteText)
r = p.createRun()
//r.getCTR().addNewRPr().addNewRStyle().setVal("FootnoteReference")
r.getCTR().addNewFootnoteReference().setId(footnoteId)
Thanks!

https://www.python2.net/questions-332393.htm
XWPFStyles styles = document.createStyles()
XWPFStyle style = new XWPFStyle(CTStyle.Factory.newInstance(), styles)
style.getCTStyle().setType(STStyleType.CHARACTER)
style.getCTStyle().setStyleId("FootnoteReference")
style.getCTStyle().addNewRPr().addNewVertAlign().setVal(STVerticalAlignRun.SUPERSCRIPT)
styles.addStyle(style)

Related

XSSFWorkbook make part of cell content to bold using apache poi

My project need is to make part of a string bold leaving any OR and AND like the below example.
TOWING PACK 11 OR TOWING PACK 13 AND TOWING PACK 14 OR TOWING PACK 15
I tried to follow the reverse approach.
I tried to make the entire cell BOLD // This works
Then using RichTextString make "OR" and "AND" to normal Italics. //The issue - After the first "OR" all the rest of the string is formatted to normal format.
Output I am getting:
TOWING PACK 11 OR TOWING PACK 13 AND TOWING PACK 14 OR TOWING PACK 15
I am using poi 5.2.3 and below is the code sample. Can anyone point out what is wrong here.
CreationHelper creationHelper = workbook.getCreationHelper();
XSSFFont fontBold = workbook.createFont();
fontBold.setBold(true);
XSSFFont fontItalic = workbook.createFont();
fontItalic.setItalic(true);
fontItalic.setBold(false);
XSSFCellStyle boldstyle = workbook.createCellStyle();
boldstyle.setFont(fontBold);
int startrow = 2;
Iterator<Row> boldrowIterator = spreadsheet.iterator();
while (boldrowIterator.hasNext()) {
Row boldrow = boldrowIterator.next();
if (boldrow.getRowNum()==startrow) {
out.println(boldrow.getCell(9));
Cell boldcell = boldrow.getCell(9);
boldcell.setCellStyle(boldstyle);
startrow = startrow+1;
String Featuredescription = boldrow.getCell(9).getStringCellValue();
if (Featuredescription.contains("OR")) {
RichTextString richTextString = creationHelper.createRichTextString(Featuredescription);
String word = " OR ";
int startIndex = Featuredescription.indexOf(word);
int endIndex = startIndex + word.length();
out.println("Featuredescription: " + Featuredescription + startIndex + endIndex);
richTextString.applyFont(startIndex, endIndex, fontItalic);
boldcell.setCellValue(richTextString);
}
} }
EDIT
XSSFCellStyle linstyle = workbook.createCellStyle();
Font linfont = workbook.createFont();
linfont.setColor(IndexedColors.ORANGE.getIndex());
linstyle.setFont(linfont);
Iterator<Row> linrowIterator = spreadsheet.iterator();
while (linrowIterator.hasNext())
{
Row linrow = linrowIterator.next();
Iterator <Cell> lincellIterator = linrow.cellIterator();
if (linrow.getRowNum()==linrowcount) {
if (linrow.getCell(13).getStringCellValue().contains("LIN")) {
while (lincellIterator.hasNext())
{
Cell lincell = lincellIterator.next();
lincell.setCellStyle(linstyle);
} } linrowcount = linrowcount+1; }
}
I would recommend using a simple regular expression to find all the occurrences of AND and OR (note the spaces included in these strings). Doing this lets you easily determine the location of each occurrence within the overall string (the indexes of where each word starts and ends). You can use this to set everything to bold (like you are already doing) and then set each OR and AND to normal.
My code assumes your test text is in cell A1 - and that is the only cell I test. You can add back your looping logic to handle more cells.
You will also need:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
I have added comments to the code to explain specific lines:
FileInputStream file = new FileInputStream(new File("C:/temp/poi/rich_formatting_in.xlsx"));
Workbook wb = new XSSFWorkbook(file);
Sheet sheet = wb.getSheet("Sheet1");
CreationHelper creationHelper = wb.getCreationHelper();
Row row = sheet.getRow(0);
Cell cell = row.getCell(0);
String content = cell.getStringCellValue();
Font bold = wb.createFont();
bold.setBold(true);
Font normal = wb.createFont();
normal.setBold(false);
//normal.setItalic(true); // uncomment, if you need italics, as well.
RichTextString richStr = creationHelper.createRichTextString(content);
richStr.applyFont(bold); // set everything to bold
String regex = "( AND | OR )"; // note the spaces in the strings
Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
Matcher matcher = pattern.matcher(content);
while (matcher.find()) {
// process each found group (one group for each AND and OR):
for (int i = 1; i <= matcher.groupCount(); i++) {
// matcher.start(i) finds where the start of the match is
// matcher.end(i) finds the position of the end of the match
// we can use these start and end positions to set that text to normal:
richStr.applyFont(matcher.start(i), matcher.end(i), normal);
}
}
// write the final string to the spreadsheet:
cell.setCellValue(richStr);
// write the spreadsheet to a file so we can see the results:
try (FileOutputStream out = new FileOutputStream(new File("C:/temp/poi/rich_formatting_out.xlsx"))) {
wb.write(out);
}
The results are:
The regex ( AND | OR ) is very basic - it assumes every occurrence of the words AND and OR surrounded by spaces are what need to be adjusted.

Insert Charc into String in a Range where character X exist at Index - swift 2.0

Please could somebody help me.
I am trying to add a new line (\n) into an existing string.
Lets say the string is 20+ Characters long, I want to find a space " " between the range of 15 and 20 then inset a new line (\n) just after the index to where the char " " (space) is
I hope that makes sense :F
Code i have for this so far is as follows
var newString = string
newString[newString.startIndex..< newString.startIndex.advancedBy(16)]
/* let startIndex = newString.startIndex.advancedBy(16)
let endIndex = newString.endIndex
let newRange = startIndex ..< endIndex
print("start index = \(newRange)")*/
let range: Range<String.Index> = newString.rangeOfString(" ")!
let index: Int = newString.startIndex.distanceTo(range.startIndex)
newString.insert("\n", atIndex: newString.startIndex.advancedBy(index))
label.text = newString
if I try the following
let newIndex = name.startIndex.advancedBy(19).distanceTo(range.endIndex)
I get the error message
fatal error: can not increment endIndex
Ive got a feeling I'm on the right tracks but the above will inset a new line at the index where space first appears in the string and not between the index of e.g. 15 and 20
Thanks for your help in advance
Thomas
The following finds the first space in the range 15..<END_OF_YOUR_STRING, and replaces it with a new line (\n). In your question you stated you explicitly wanted to look for a space in range 15...20, and also insert a new line after the space. Below I have assumed that you actually want:
To replace the space by a new line, since you'll otherwise have a trailing space on the line following the line break.
To search for the first space starting at index 15, but continuing until you find one (otherwise: if you find no space within range 15...20, no line break should be inserted?).
Both of these deviations from your question can be quite easily reverted, so tell me if you'd prefer me to follow your instructions to specifically to the point (rather than including my own reason), and I'll update this answer.
Solution as follows:
var foo = "This is my somewhat long test string"
let bar = 15 /* find first space " " starting from index 'bar' */
if let replaceAtIndex = foo[foo.startIndex.advancedBy(bar)..<foo.endIndex]
.rangeOfString(" ")?.startIndex.advancedBy(bar) {
foo = foo.stringByReplacingCharactersInRange(
replaceAtIndex...replaceAtIndex, withString: "\n")
}
print(foo)
/* This is my somewhat
long test string */
Note that there is a off-by-one difference between finding a space in the range of 15 to 20 and the 15:th to 20:th character (the latter is in the range 14...19). Above, we search for the first space starting at the 16th character (index 15).
Thanks to dfri for pointing me in the right direction. Although his answer was correct for my problem specifically I've provided the following code to help
if string.characters.count >= 20
{
let bar = 15 // where to split the code to begin looking for the character
let beginString = string.substringWithRange(name.startIndex..<name.startIndex.advancedBy(bar))
var endString = string[string.startIndex.advancedBy(bar)..<name.endIndex]
if endString.containsString(" ")
{
let range = endString.rangeOfString(" ")
if let i = range
{
endString.insert("\n", atIndex:i.startIndex.advancedBy(1) )
let newString = "\(beginString)\(endString)"
label.text = newString
}
}
}

Error whilst translating C# to VB.NET

Can anyone translate the following in VB.NET?
// propare a few short names
ChartArea CA = chart1.ChartAreas[0];
Series S1 = chart1.Series[0];
// this would be option one:
S1.IsValueShownAsLabel = true;
// we clear any previous CustomLabels
CA.AxisY.CustomLabels.Clear();
// we create a version of our points collection which sorted by Y-Values:
List<DataPoint> ptS = S1.Points.OrderBy(x => x.YValues[0]).ToList();
// now, for option three we add the custom labels:
for (int p = 0; p < ptS.Count; p++)
{
CustomLabel L = new CustomLabel(ptS[p].YValues[0] - 0.5,
ptS[p].YValues[0] + 0.5,
ptS[p].YValues[0].ToString("##0.0000"),
0, LabelMarkStyle.None);
CA.AxisY.CustomLabels.Add(L);
// this is option two: tooltips for each point
ptS[p].ToolTip = ptS[p].YValues[0].ToString("##0.0000");
}
This comes from the following Stack Overflow question:
Display Y-Values on Y-Axis without rounding [closed]
I tried the following:
area1.AxisY.CustomLabels.Clear()
Dim pointSeries As List(Of DataPoint)
**Line with error:**
pointSeries = mySeriesRecord.Points.OrderBy(Function(x) x.YValues(0))
Dim len As Integer = pointSeries.Count()
For p As Integer = 0 To pointSeries.Count Step 1
Dim L As CustomLabel
L = New CustomLabel(pointSeries(p).YValues(0), pointSeries(p).YValues(len) + 0.5, pointSeries(p).YValues(0).ToString("##':'#0.00"), 0, LabelMarkStyle.None)
area1.AxisY.CustomLabels.Add(L)
Next
But that does not work. The error is:
OrderedEnumerable
2[System.Web.UI.DataVisualization.Charting.DataPoint,System.Double]
unable to convert to type System.Collections.Generic.List
Any help would be appreciated.
Robert
Did you try something like this?
Dim ptS As List(Of DataPoint) = S1.Points.OrderBy(Function(x) x.YValues(0)).ToList()
For converting from/to C# to/from VB.NET you can use telerik's online tool:
http://converter.telerik.com/

Converting images into a linear color palette with JS, losing colors

The project in question: https://github.com/matutter/Pixel2 is a personal project to replace some out of date software at work. What it should do is, the user adds an image and it generates a color palette of the image. The color palette should have no duplicate colors. (thats the only important stuff)
My question is: why do larger or hi-res or complex images not work as well? (loss of color data)
Using dropzone.js I have the user put a picture on the page. The picture is a thumbnail. Next I use jquery to find the src out of a <img src="...">. I pass that src to a function that does this
function generate(imgdata) {
var imageObj = new Image();
imageObj.src = imgdata;
convert(imageObj); //the function that traverses the image data pulling out RGB
}
the "convert" function pulls out the data fairly simply by
for(var i=0, n=data.length; i<n; i+=4, pixel++ ) {
r = data[i];
g = data[i+1];
b = data[i+2];
color = r + g + b; // format is a string of **r, g, b**
}
finally, the last part of the main algorithme filters out duplicate colors, I only want just 1 occurrence of each... here's the last part
color = monoFilter(color); // the call
function monoFilter(s) {
var unique = [];
$.each(s, function(i, el){
if($.inArray(el, unique) === -1) unique.push(el);
});
unique.splice(0,1); //remove undefine
unique.unshift("0, 0, 0"); //make sure i have black
unique.push("255, 255, 255"); //and white
return unique;
}
I'm hoping someone can help me identify why there is such a loss of color data in big files.
If anyone is actually interesting enough to look at the github, the relivent files are js/pixel2.js, js/dropzone.js, and ../index.html
This is probably the cause of the problem:
color = r + g + b; // format is a string of **r, g, b**
This simply adds the numbers together and the more pixels you have the higher risk you run to get the same number. For example, these colors generate the same result:
R G B
color = 90 + 0 + 0 = 90;
color = 0 + 90 + 0 = 90;
color = 0 + 0 + 90 = 90;
even though they are completely different colors.
To avoid this you can do it like this if you want a string:
color = [r,g,b].join();
or you can create an integer value of them (which is faster to compare with than a string):
color = (b << 16) + (g << 8) + r; /// LSB byte-order
Even an Euclidean vector would be better:
color = r*r + g*g + b*b;
but with the latter you risk eventually the same scenario as the initial one (but useful for nearest color scenarios).
Anyways, hope this helps.
"The problem was that I wasn't accounting for alpha. So a palette from an image that uses alpha would have accidental duplicate records."
I figured this out after finding this Convert RGBA color to RGB

line break in string in c#

I'm loading a text from the resource loader which includes '\n' to indicate a new line. A textblock takes this text and displays it, but I can't see the line break? I'm also trying to replace every '\n' by Environment.NewLine, but nothing happens. What can I do?
Here is a little bit code:
TextBlock text = new TextBlock();
text.FontSize = 18;
var str = loader.GetString("AboutText");
//str.Replace("\n", Environment.NewLine);
text.Text = str;
text.TextAlignment = TextAlignment.Justify;
text.TextWrapping = TextWrapping.Wrap;
text.Margin = new Thickness(10, 10, 10, 10);
It looks like the Resource file is escaping \n to \\n, this means that there are basically 2 solutions to solve this.
you can either
var str = Regex.Unescape(loader.GetString("AboutText"));
or in your resx file you can replace \n with normal break line by pressing Shift Enter.
Try "\r\n". It works for me.
TextBlock text = new TextBlock();
text.FontSize = 18;
var str = "Hello\r\nWorld";
text.Text = str;
text.TextAlignment = TextAlignment.Justify;
text.TextWrapping = TextWrapping.Wrap;
text.Margin = new Thickness(10, 10, 10, 10);
layoutRoot.Children.Add(text);

Resources