JTextPane with HTMLEditorKit: missing content when saving

Hi

When trying to save an HTML document to disc I only get HTML tags saved without any content. Similar topic was reported in this forum some time ago (see http://forum.java.sun.com/thread.jspa?threadID=700324&messageID=4066928), however the solution (as well as many other tips from other places) didn't help.

Here is the example code:

import java.awt.BorderLayout;

import java.awt.Color;

import java.io.File;

import java.io.FileWriter;

import javax.swing.JFrame;

import javax.swing.JTextPane;

import javax.swing.SwingUtilities;

import javax.swing.text.BadLocationException;

import javax.swing.text.SimpleAttributeSet;

import javax.swing.text.StyleConstants;

import javax.swing.text.html.HTMLDocument;

import javax.swing.text.html.HTMLEditorKit;

/**HTMLWriter: starts a JTextPane, generates an HTML test document and saves it to file

* -> it displays the text correctly in the pane, but it doesn't save the content to the file

* @author Chris

*/

publicclass HTMLWriterextends JFrame{

protected JTextPane m_editorPane;

protected HTMLDocument m_doc;

protected HTMLEditorKit m_editorKit;

/** Creates a new instance of HTMLWriter */

public HTMLWriter(){

//Create the text pane and configure it.

m_editorPane =new JTextPane();

m_editorKit =new HTMLEditorKit();

m_editorPane.setEditorKit(m_editorKit);

//Create the document and initialize it

m_doc = (HTMLDocument)m_editorKit.createDefaultDocument();

// m_doc.setAsynchronousLoadPriority(-1);

m_editorPane.setDocument(m_doc);

String initString ="Some text2";

SimpleAttributeSet attr =new SimpleAttributeSet();

StyleConstants.setFontFamily(attr,"SansSerif");

StyleConstants.setFontSize(attr, 16);

StyleConstants.setForeground(attr, Color.red);

try{

m_doc.insertString(m_doc.getLength(), initString +"\n", attr);

}catch (BadLocationException ble){

System.err.println("Couldn't insert initial text.");

}

//Add the components

getContentPane().add(m_editorPane, BorderLayout.CENTER);

//Save the document to c:\temp.htm (MS Windows)

File f =new File("c:\\","temp.htm");

try{

FileWriter fw =new FileWriter(f);

int len = m_doc.getLength();

m_editorKit.write(fw, m_doc, 0, len);

/* I also tried to generate a new HTMLEditorKit object:

HTMLEditorKit newKit = new HTMLEditorKit();

newKit.write(fw, m_doc, 0, len); */

fw.flush();

/* I also tried passing OutputStream object to m_editorKit.write():

OutputStream out = new BufferedOutputStream(new FileOutputStream(f));

int len = m_doc.getLength();

m_editorKit.write(out, m_doc, 0, len);

out.close();

*/

}catch (Exception exSave){

System.out.println(" Error while Saving : " + exSave.getMessage());

}

}

publicstaticvoid main(String[] args){

final HTMLWriter frame =new HTMLWriter();

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.pack();

frame.setVisible(true);

}

}

The output in c:/temp.htm looks as follows:

<html>

<head>

</head>

<body>

<p style="margin-top: 0">

<font size="5" face="SansSerif" color="#ff0000">

</font>

</body>

</html>

I work with NetBeans 5.5 and JDK 1.6.

Thank you for your help!

[5682 byte] By [Christoph.Ia] at [2007-11-27 5:27:12]
# 1

I changed:

m_doc.insertString(m_doc.getLength(), initString + "\n", attr);

to

m_doc.insertString(m_doc.getLength(), initString + "\n", null);

and it worked fine. I guess since its an HTML document it doesn't like you playing with attributes directly and you should be using the HTML tags.

camickra at 2007-7-12 14:48:35 > top of Java-index,Desktop,Core GUI APIs...
# 2

Thanks camikr for your reply. Helped me to 慸ig?in a new direction. Together with http://www.manning.com/robinson2/ I found the following solution:

import java.awt.BorderLayout;

import java.awt.Color;

import java.io.File;

import java.io.FileWriter;

import javax.lang.model.element.Element;

import javax.swing.JFrame;

import javax.swing.JTextPane;

import javax.swing.text.AttributeSet;

import javax.swing.text.BadLocationException;

import javax.swing.text.MutableAttributeSet;

import javax.swing.text.SimpleAttributeSet;

import javax.swing.text.StyleConstants;

import javax.swing.text.html.HTMLDocument;

import javax.swing.text.html.HTMLDocument.BlockElement;

import javax.swing.text.html.HTMLEditorKit;

/**HTMLWriter: starts a JTextPane, generates an HTML test document, inserts a formatted string and saves it to file

* @author Chris

*/

public class HTMLWriter extends JFrame {

protected JTextPane m_editorPane;

protected HTMLDocument m_doc;

protected HTMLEditorKit m_editorKit;

/** Creates a new instance of HTMLWriter */

public HTMLWriter() {

// create the text pane and configure it.

m_editorPane = new JTextPane();

m_editorKit = new HTMLEditorKit();

m_editorPane.setEditorKit(m_editorKit);

// create attribute set

MutableAttributeSet attr = new SimpleAttributeSet();

StyleConstants.setFontFamily(attr, "SansSerif");

StyleConstants.setFontSize(attr, 16);

StyleConstants.setForeground(attr, Color.red);

// create the document and initialize it

m_doc = (HTMLDocument)m_editorKit.createDefaultDocument();

m_editorPane.setDocument(m_doc);

// insert a string

String initString = "Some text\n";

int startPos = m_editorPane.getCaretPosition();

try{

m_doc.insertString(startPos, initString, null); // this safes the content correctly, but has no font style defined

// notice: m_doc.insertString(startPos, initString, attr) wouldn't assign attributes correctly

}catch(BadLocationException ble){

System.out.println(ble.getMessage());

}

// assign the attribute set to the inserted string

m_doc.setCharacterAttributes(startPos, initString.length(),attr,false);

//Add the components / display the jFrame

getContentPane().add(m_editorPane, BorderLayout.CENTER);

//Save the document to c:\temp.htm (MS Windows)

File f = new File("c:\\","temp.htm");

try {

FileWriter fw = new FileWriter(f);

int len = m_doc.getLength();

m_editorKit.write(fw, m_doc, 0, len);

fw.flush();

} catch (Exception exSave) {

System.out.println(" Error while Saving : " + exSave.getMessage());

}

}

public static void main(String[] args) {

final HTMLWriter frame = new HTMLWriter();

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.pack();

frame.setVisible(true);

}

}

The output now looks fine:

<html>

<head>

</head>

<body>

<p style="margin-top: 0">

<font size="5" face="SansSerif" color="#ff0000">Some text

</font>

</body>

</html>

Christoph.Ia at 2007-7-12 14:48:35 > top of Java-index,Desktop,Core GUI APIs...