Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Render HTML with CSS in Java

Tags:

java

html

css

I'm trying to display HTML in my java application that has a linked stylesheet include in my HTML.

I am transforming my XML to HTML using XSLT from Java. I want to include a stylesheet so I can easily style the html output. However the stylesheet is being ignored and the html is being output normally.

To do this I am using a JEditorPane and HTMLEditorKit. I found some sample code on Dev Daily to do this.

My stylesheet is sitting on my local hard drive and I wondered if anyone knew how I could use it?

I have the following code:

JEditorPane jEditorPane = new JEditorPane();
jEditorPane.setEditable( false );

HTMLEditorKit kit = new HTMLEditorKit();
jEditorPane.setEditorKit(kit);

try {    
    kit.getStyleSheet().importStyleSheet( new URL( "file://D:\\mycssfile.css" ) );
} catch( MalformedURLException ex ) {
}

Document doc = kit.createDefaultDocument();
jEditorPane.setDocument(doc);
jEditorPane.setText(html);

In my html output from xsl the css is linked using the following - I get the same result with it included or excluded:

<link rel="stylesheet" type="text/css" href="mycss.css" />

Any ideas?

Cheers,

Andez

like image 939
Andez Avatar asked Oct 14 '10 15:10

Andez


1 Answers

Your URL isn't valid, so it can't find your CSS file. Change it to:

kit.getStyleSheet().importStyleSheet(new URL("file:///D:/mycssfile.css"));

Or better still, instead of using a URL, add the css file to your classpath and then load it as a resource, like this:

kit.getStyleSheet().importStyleSheet(MyClassName.class.getResource("mycssfile.css"));
like image 103
dogbane Avatar answered Oct 11 '22 10:10

dogbane