How to change text in Text element - java

I have this line in my SVG file:
<text id="region1Text" class="regionText" x="77" y="167">2</text>
I can get an object of Text class with this but I cant see any usable method for changing "2" to another number. The appendText method seems to do nothing and I see there is no "setText" method.
My code:
StringReader reader = new StringReader(svgInString);
uri = SVGCache.getSVGUniverse().loadSVG(reader, "myImage");
SVGDiagram diagram = SVGCache.getSVGUniverse().getDiagram(uri);
Text text = (Text) diagram.getElement("region1Text");
text.appendText("20");
When debugging I can see the content variable of the text object is set to "2"(so I think that text element is made correctly) but I'm not able to change it.

After appending the text, you have to use text.rebuild() function. In total it looks like this:
StringReader reader = new StringReader(svgInString);
uri = SVGCache.getSVGUniverse().loadSVG(reader, "myImage");
SVGDiagram diagram = SVGCache.getSVGUniverse().getDiagram(uri);
Text text = (Text) diagram.getElement("region1Text");
text.appendText("20");
text.rebuild();

Related

Get DIV contents with Java Swing

I'm trying to get DIV contents from previously fetched HTML document. I'm using Java Swing.
final java.io.Reader stringReader = new StringReader(html);
final HTMLEditorKit htmlKit = new HTMLEditorKit();
final HTMLDocument htmlDoc = (HTMLDocument) htmlKit.createDefaultDocument();
final HTMLEditorKit.Parser parser = new ParserDelegator();
parser.parse(stringReader, htmlDoc.getReader(0), true);
final javax.swing.text.Element el = htmlDoc.getElement("id");
This code should get a DIV with ID of "id" that I have inside html.
But what next? How to get the contents of div? Been searching it all around but only thing I found is how to get attribute value, not the Element contents.
Should I move to jsoup? I would rather use Java native, but so far I'm stuck.
Thanks!
not the Element contents.
Try something like:
int start = el.getStartOffset();
int end = el.getEndOffset();
String text = htmlDoc.getText(start, end - start);

Encoding for FontFactor.getFont() [duplicate]

This question already has an answer here:
iText : Unable to print mathematical characters like ∈, ∩, ∑, ∫, ∆ √, ∠
(1 answer)
Closed 6 years ago.
Hiyas
I'm trying to display this string:
λλλλλλλλλλλλλλλλλλλλλλλλ
which is read from a RTF file, parsed and put into this variable. It is NOT used as constant in the code.
Font pdfFont = FontFactory.getFont(font.getFont().getName(), BaseFont.IDENTITY_H, embed, font.getFont().getSize2D(), style);
Phrase phrase = new Phrase("λλλλλλλλλλλλλλλλλλλλλλλλ", pdfFont);
ColumnText.showTextAligned(content[i], alignment, phrase, x, y, rotation);
I also tried CP1252 (and basically all the other encodings I found) together with a simple ArialMT.ttf font, but that damn string is never displayed. I can see that the conversion to the byte array inside iText (we use 5.5.0) always returns a null length byte array which explains why the text is not used, but I don't understand why. What encoding would I need to use to make this visible in a PDF?
Thanks a lot
I suppose that you want to get a result that looks like this:
That's easy. I first tried the SunCharacter example from the official documentation. That example was written in answer to the question: iText : Unable to print mathematical characters like ∈, ∩, ∑, ∫, ∆ √, ∠
I then changed the TEXT to:
public static final String TEXT = "Always use the Unicode notation for special characters: \u03bb";
As you can see, I don't use λ in my source code (that's bad practice). Instead I use \u03bb which is the Unicode notation of λ.
The result looked like this:
That's not what you want; you want ArialMT. So I changed the FONT to:
public static final String FONT = "c:/windows/fonts/arial.ttf";
This gave me the desired PDF.
This is the full code sample:
public class LambdaCharacter {
public static final String DEST = "results/fonts/lambda_character.pdf";
public static final String FONT = "c:/windows/fonts/arial.ttf";
public static final String TEXT = "Always use the Unicode notation for special characters: \u03bb";
public static void main(String[] args) throws IOException, DocumentException {
File file = new File(DEST);
file.getParentFile().mkdirs();
new LambdaCharacter().createPdf(DEST);
}
public void createPdf(String dest) throws IOException, DocumentException {
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream(dest));
document.open();
BaseFont bf = BaseFont.createFont(FONT, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
Font f = new Font(bf, 12);
Paragraph p = new Paragraph(TEXT, f);
document.add(p);
document.close();
}
}
I works just fine.
Maybe you aren't really using Arial. Maybe font.getFont().getName() doesn't give you the correct name of the font. Or maybe it gives you the correct name of the font, but you forgot to register the font. In that case, you will see that Helvetica is used. Helvetica can't render a lambda. You need Arial or Cardo-Regular or Arial Unicode or another font, as long as that font knows how to render a lambda.
If you don't know how to register a font, read:
How to load custom font in FontFactory.register in iText or
Creating fonts from *.ttf files using iText or
Using Fonts in System with iTextSharp or
Get list of supported fonts in ITextSharp or
Why is my font not applied when I create a PDF document? or... (there are just too many hits when I search for an answer to that question)

How to add a hyperlink to a XWPFRun

I want to format the text of a XWPF Run as a hyperlink. I am able to add it to the paragraph with the code given below but the adds it in a separate line.
public static void appendExternalHyperlink(String url, String text, XWPFParagraph paragraph){
//Add the link as External relationship
String id=paragraph.getDocument().getPackagePart().addExternalRelationship(url, XWPFRelation.HYPERLINK.getRelation()).getId();
//Append the link and bind it to the relationship
CTHyperlink cLink=paragraph.getCTP().addNewHyperlink();
cLink.setId(id);
//Create the linked text
CTText ctText=CTText.Factory.newInstance();
ctText.setStringValue(text);
CTR ctr=CTR.Factory.newInstance();
ctr.setTArray(new CTText[]{ctText});
CTRPr rpr = ctr.addNewRPr();
CTColor colour = CTColor.Factory.newInstance();
colour.setVal("0000FF"); rpr.setColor(colour);
CTRPr rpr1 = ctr.addNewRPr(); rpr1.addNewU().setVal(STUnderline.SINGLE);
//Insert the linked text into the link
cLink.setRArray(new CTR[]{ctr});
}
And I invoke it like:
XWPFParagraph eduPara = doc.createParagraph();
eduPara.setAlignment(ParagraphAlignment.LEFT);
eduPara.setVerticalAlignment(TextAlignment.TOP);
XWPFRun eduRun7 = eduPara.createRun();
appendExternalHyperlink(center.getEduImpFile(), center.getEduImpFile(), eduPara);
eduRun7.addBreak();
Here center is an object that holds the values I need to print.The get functions give output in String format.
The output I get is as follows:
Program Output
I want the hyperlink to be in the same line as the previous run generating the text "File uploaded:"
This was a mistake on my part as it was going to the next-line because there was not enough space to place the line.

Dom4j get single node text value

Assume I have
<Sports>
<Soccer>
<Players>
<Player_1> Messi Leonel </Player_1>
</Players>
</Soccer>
</Sports>
How to get Player_1 node text in one line without iteration using Dom4J?
Return value should be: Messi Leonel
Thanks
Got it, to the person who looks something like this
File file = new File("/path/to/file.xml");
SAXReader reader = new SAXReader();
Document document = reader.read(file);
String name = document.selectSingleNode("//Sports/Soccer/Players/Player_1").getText();

HTML in JTextArea of JEditorPane, JTextPane

Right I already worked out that JTextArea or JTextField don't support HTML.
I want to add text to a "screen" like a JTextArea and later keep appending text to it.
I tried with JTextArea which worked wonderfully, but it does not support formatting it seems...
So I tried using JEditorPane's subclass JTextPane, but this one does not have it's append function...
Can someone guid me in the right direction how I easily can append text to a JTextPane or format a JTextArea.
Or if there is any other component better for this please tell me :)
The update method is called by a subject which does this for multiple objects. This just gives a bunch of strings which are formatted and then put in a nice frame to show the user.
#Override
public void update(String channel, String sender, String message) {
if(channel.equals(this.subject) || sender.equals(subject)){
StringBuffer b = new StringBuffer();
b.append("<html>");
b.append("<b>");
b.append("</b>");
b.append("[");
b.append(sender);
b.append("] : ");
b.append("</b>");
b.append(message);
b.append("</html>");
b.append("\n");
chatArea.append(b.toString());
}
Can someone guid me in the right direction how I easily can append text to a JTextPane
Document doc = textPane.getDocument();
doc.insertString(doc.getLength(), "some text", green);
And use attributes instead of HTML, its much easier. For example you could define the "green" attributes to be:
SimpleAttributeSet green = new SimpleAttributeSet();
StyleConstants.setForeground(green, Color.GREEN);
You can use JEditorPane. But when you want to append some Strings that that contain HTML tag you should perform some methods not just a insertString() method.
For example, you have
//setup EditorPane
JEditorPane yourEditorPane = new JEditorPane();
yourEditorPane.setContentType("text/html");
//setup HTMLEditorKit
HTMLEditorKit htmlEditorKit = new HTMLEditorKit();
yourEditorPane.setEditorKit(htmlEditorKit);
If you only use insertString()
String htmlText = "<div class='test'><b>Testing</b></div>";
Document doc = yourEditorPane.getDocument();
doc.insertString(doc.getLength(), htmlText, null);
The output will be
< div class = 'test' >< b >Testing< /b >< /div >
You should do this method
htmlEditorKit.insertHTML((HTMLDocument) doc, doc.getLength(), htmlText, 0, 0, null);
So the output on your editorpane will be
Testing
Last, if you want to style your editorpane you can use this method
StyleSheet css = htmlEditorKit.getStyleSheet();
css.addRule(".test {color: green;}");
For formatted output the JEditorPAne is probably the best option.
You can use the getText() method of the JEditorPane to get the text that is currently in the pane, then append the new text and call setText() to put everything back.
e.g.
b.append(chatArea.getText());
b.append("All the other text")
chatArea.setTExt(b.toString());

Categories

Resources