Render HTML with CSS in Java

I am trying to display HTML code in my Java application that has a related stylesheet contained in my HTML document.

I convert my XML to HTML using XSLT with Java. I want to include a stylesheet to simplify the html output style. However, the stylesheet is ignored, and html is output normally.

For this, I use JEditorPane and HTMLEditorKit. I found Dev Daily sample code to do this.

My stylesheet is sitting on my local hard drive, and I thought, does anyone know how I can 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, css is linked using the following: I get the same result with enabled or excluded:

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

Any ideas?

Greetings

Andez

+4
source share
1 answer

Your url is invalid so it cannot find your CSS file. Change it to:

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

Or even better, instead of using the URL, add the css file to your classpath and then load it as a resource, for example:

 kit.getStyleSheet().importStyleSheet(MyClassName.class.getResource("mycssfile.css")); 
+5
source

All Articles