Render HTML with CSS in Java – Education Career Blog

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();

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

Document doc = kit.createDefaultDocument();

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?




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:


Leave a Comment