Swing JLabel - strike through HTML text - java

I am having problems adding a HTML strike-through tag to a string of text in Java.
EDIT: I have posted the entire code and I am using Windows 7, Java 8 and Swing.
JLabel LocalSelectorLabel = new JLabel("<html><strike>Text Here</strike><html>");
LocalSelectorLabel.setBounds(12, 50, 55, 16);
LocalTabPanel.add(LocalSelectorLabel);
I have tried the tags: s, del and strike but all of them just give me underlined text.
I have looked around for other tags that might work but I haven't found anything.
EDIT 2: This works for me, thanks:
new JLabel("<html><body><span style='text-decoration: line-through;'>Text Here</span></body></html>");
EDIT 3: Now this is interesting. I ran the code on a different computer and that one displays as strike-through and as underline as expected while the computer I used to ask this question did not.
I see now why I didn't find anything when I searched for a solution.

"<html></strike>Text Here</strike><html>"
Should be:
"<html><strike>Text Here</strike><html>"
The 'opening' </strike> tag should be <strike>.
As an aside, it never hurts to check the HTML using an HTML validator. For 'Swing HTML' set it to HTML 3.2 (or 4.01 transitional, if they stop supporting 3.2).

As a continue of #Gaël answer, using css you can achive your desired result with the follwing code:
new JLabel("<html><body><span style='text-decoration: line-through;'>Text Here</span></body></html>");

Be aware that <strike> tag is not part of HTML5, you should use CSS to achieve this.
EDIT : you're using Swing, so HTML 3.2 and <strike> tag exists (but still not recommended for future updates).

Related

Java JEditorPane replace selected text with a hyperlink

I'm writing a program which uses a JEditorPane to make a simple editor, it uses hyperlinks to allow the user to jump between different pages using a simple hyperlink listener.
The problem is I want to have the ability to have a user select some text and turn it into a link. I found lots of examples doing this on right click using the position of the mouse to select the element in the HTMLDocument but I also want it to be possible to do it via a keyboard shortcut.
From searching and experimenting I came up with the method:
public void createLink() {
HTMLEditorKit kit = new HTMLEditorKit();
try {
String text = jEditorPane1.getSelectedText();
jEditorPane1.replaceSelection("");
kit.insertHTML((HTMLDocument) jEditorPane1.getDocument(),
jEditorPane1.getCaretPosition(),
"" + text + "",
0, 0, HTML.Tag.A);
} catch (BadLocationException | IOException ex) {
Logger.getLogger(Editor.class.getName()).log(Level.SEVERE, null, ex);
}
}
But something just seems ugly about this, I've no idea what corner cases are going to cause problems such as trying to put a link within a link, or overlapping links. Is there a more sensible solution that maps the selected text to elements in the html document?
HTMLEditorKit only supports HTML 3.2, so you will likely encounter several issues. If you are targeting HTML tags beyond version 3.2, then you will be better served by JavaFX HTMLEditor. If you do not want to use JavaFX, then there are alternative implementations for Swing, such as SHEF. If you want some complete examples from scratch, try the O'Reilly HTML Editor Kits book (old but instructive).
From the HTMLEditorKit documentation:
The default support is provided by this class, which supports HTML version 3.2 (with some extensions), and is migrating toward version 4.0.
The earliest version of HTML that could be validated against an XML schema was XHTML 1.0, so finding all of the outlier cases will be challenge with HTMLEditorKit. You might have some luck integrating JTidy.

How to set a label text to a special character?

I need to set a label to have some special characters, I'm trying:
Label label = new Label();
label.setText("•");
label.setText("♦");
label.setText("★");
I'm not seeing the characters rendered though (firefox 17). The output html looks like this:
<div class="gwt-Label"></div>
Is there a different way we need to set the text to those characters?
I do no think it is possible with Label widget. You should be using HTML class which extends Label.
SafeHtmlBuilder builder = new SafeHtmlBuilder();
builder.appendEscaped("★");
HTML widget = new HTML();
widget.setHTML(builder.toSafeHtml());
RootPanel.get().add(widget);
Also ensure best practice of using SafeHtmlBuilder class.
You should make sure your source code uses UTF-8 encoding. If you are using Eclipse, you can set the default encoding in Windows -> Preferences.
The short version of this is: if you do absolutely everything in your GWT project and deployment using UTF-8 encoding, then all your special characters should work as expected.
If you have lots of existing files to convert, the JDK contains a little tool to convert your files for you.
You can use html codes: ★ for star(★), • for bullet (•) and so on.
http://www.quackit.com/html/html_special_characters.cfm

Selenium Click Image Link based on Alt (including quote)

I have a tricky one!
I am trying to test an image button click in Selenium. This is the HTML code:
<img src="/img/buttons/showOnOrder.gif" alt="Show 'On Order'"/>
I completely agree that having the single quote in the alt text is not ideal/good, but for the purposes of this test, I can't currently change the code.
I have tried the following
selenium.click("//img[#alt=\"Show 'On Order'\"]");
selenium.click("xpath=//img[#alt='Show ''On Order''']");
But no joy. Please, please, please make my day and suggest the syntax I can use that works.
Try this :
selenium.click("//a[contains(#href,'onOrder')]/img");
Try like this
selenium.click("//img[contains(#alt,'Show') and contains(#alt,'On Order')]");
or
selenium.click("xpath=//img[#alt='Show \'On Order\'']");
or
selenium.click("css=img[alt*='Show'][alt*='On Order']");

How can I map the XPath in Selenium?

I am currently trying to map the highlighted line shown below in the screen grab.
I've looked at w3schools and looked it up here on SO but cant seem to get my code right.. My selenium script keeps erroring out with cannot identify element.
currently, I am doing something like:
selenium.click("xpath=//table[#id='resultTable']/tbody/tr[#class='level3']/td[#id='resultTable_0_0_1_ob']/span/a[#class='linkOnly']");
I have also tried this:
selenium.click("xpath=//table[#id='resultTable']/tbody[1]/tr[6]/td[2]/span[1]/a[1]");
and this:
selenium.click("xpath=//table[#id='resultTable']/tbody/tr[6]/td[2]/span/a");
Am I doing it right and I just need to put in a delay ? or am I doing this completely wrong ?
EDIT:
Here is the code snippet as requested. Thanks for the pointer, I didn't really notice that there were multiple classes with the same name! Hm, but for some reason, the other two XPaths that I wrote dont work.
In this code snippet, I expanded the table so you can better see how the table is set up. Again, sorry for the image size, but ctrl+scroll up should enlarge the picture.
I'd prefer using css selectors as they work faster (currently using webdriver + java)
so solution to your problem be like:
String cssSelector = "tr[class='level3']>td[id='resultTable_0_0_1_ob']>span>a[class='linkOnly']"
driver.findElement(By.cssSelector(cssSelector)).click():
driver.manage.timeouts.implicitWait(3,TimeUnit.SECONDS);
As you got ID='resultTable_0_0_1_ob' I think this ID should help in finding unique element on the page.
2nd way to solve your problem:
also if framework which your site is implemented on supports jQuery you can easly use jQuery:
JavascriptExecutor js = (JavascriptExecutor) driver;
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("var x = $("tr[class='level3']>td[id='resultTable_0_0_1_ob']>span>a[class='linkOnly'];");
stringBuilder.append("x.click();");
js.executeScript(stringBuilder.toString());
And don't forget to verify your xpaths, css selectors in firepath(firebug extension) in firefox.
Picture below provided:
Hope this helps you.
xpath=//table[#id='resultTable']/tbody/tr[#class='level3']/td[#id='resultTable_0_0_1_ob']/span/a[#class='linkOnly']
The Corresponding CSS is css=#resultTable > tbody > tr.level3 > #resultTable_0_0_1_ob > span > .linkOnly

HTML content to pdf in JAVA [duplicate]

Does anyone know if it is possible to convert a HTML page (url) to a PDF using iText?
If the answer is 'no' than that is OK as well since I will stop wasting my time trying to work it out and just spend some money on one of a number of components which I know can :)
I think this is exactly what you were looking for
http://today.java.net/pub/a/today/2007/06/26/generating-pdfs-with-flying-saucer-and-itext.html
http://code.google.com/p/flying-saucer
Flying Saucer's primary purpose is to render spec-compliant XHTML and CSS 2.1 to the screen as a Swing component. Though it was originally intended for embedding markup into desktop applications (things like the iTunes Music Store), Flying Saucer has been extended work with iText as well. This makes it very easy to render XHTML to PDFs, as well as to images and to the screen. Flying Saucer requires Java 1.4 or higher.
I have ended up using ABCPdf from webSupergoo.
It works really well and for about $350 it has saved me hours and hours based on your comments above.
The easiest way of doing this is using pdfHTML.
It's an iText7 add-on that converts HTML5 (+CSS3) into pdf syntax.
The code is pretty straightforward:
HtmlConverter.convertToPdf(
"<b>This text should be written in bold.</b>", // html to be converted
new PdfWriter(
new File("C://users/mark/documents/output.pdf") // destination file
)
);
To learn more, go to http://itextpdf.com/itext7/pdfHTML
The answer to your question is actually two-fold. First of all you need to specify what you intend to do with the rendered HTML: save it to a new PDF file, or use it within another rendering context (i.e. add it to some other document you are generating).
The former is relatively easily accomplished using the Flying Saucer framework, which can be found here: https://github.com/flyingsaucerproject/flyingsaucer
The latter is actually a much more comprehensive problem that needs to be categorized further.
Using iText you won't be able to (trivially, at least) combine iText elements (i.e. Paragraph, Phrase, Chunk and so on) with the generated HTML. You can hack your way out of this by using the ContentByte's addTemplate method and generating the HTML to this template.
If you on the other hand want to stamp the generated HTML with something like watermarks, dates or the like, you can do this using iText.
So bottom line: You can't trivially integrate the rendered HTML in other pdf generating contexts, but you can render HTML directly to a blank PDF document.
Use itext libray:
Here is the sample code. It is working perfectly fine:
String htmlFilePath = filePath + ".html";
String pdfFilePath = filePath + ".pdf";
// create an html file on given file path
Writer unicodeFileWriter = new OutputStreamWriter(new FileOutputStream(htmlFilePath), "UTF-8");
unicodeFileWriter.write(document.toString());
unicodeFileWriter.close();
ConverterProperties properties = new ConverterProperties();
properties.setCharset("UTF-8");
if (url.contains(".kr") || url.contains(".tw") || url.contains(".cn") || url.contains(".jp")) {
properties.setFontProvider(new DefaultFontProvider(false, false, true));
}
// convert the html file to pdf file.
HtmlConverter.convertToPdf(new File(htmlFilePath), new File(pdfFilePath), properties);
Maven dependencies
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext7-core</artifactId>
<version>7.1.6</version>
<type>pom</type>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>html2pdf</artifactId>
<version>2.1.3</version>
</dependency>
Use iText's HTMLWorker
Example
When I needed HTML to PDF conversion earlier this year, I tried the trial of Winnovative HTML to PDF converter (I think ExpertPDF is the same product, too). It worked great so we bought a license at that company. I don't go into it too in depth after that.

Categories

Resources