|
Re: How to write formatted text to html file?
|
Posted: Aug 7, 2002 3:34 PM
|
|
Ok, here is what I already have (it's not very much!) Important is method update(). My problem is that I just don't know how to insert code after the Body-tag. The code below creates a new BODY tag at the wrong place (inside of <Head>). I also tried to iterate through the document and retrieve the Position of <Body> what also didn't work. (Element.getStartOffset() returnd a value of 3 what I can't apply to the HTML-file)
import javax.swing.text.html.*; import javax.swing.text.*; import java.net.*; import java.io.*; import javax.swing.JTextPane; import javax.swing.text.html.parser.*;
public class HTMLUpdator { //Document with new text from JTextPane HTMLDocument textDoc; //Document with existing Text from "guestlog.htm" HTMLDocument doc; JTextPane textpane; URL base; HTMLEditorKit kit;
public HTMLUpdator(URL base) { //Place of "guestlog.htm" this.base = base;
}
public void update(){
try{ //Construct a reader to load "guestlog.htm" Reader rd = getReader(base.toString());
//Read guestlog.htm into doc; kit.read(rd, doc,0); System.out.println("Content of guestlog.htm: " + doc.getText(0,doc.getLength())); System.out.println("Content of JTextPane: "+ textDoc.getText(0,textDoc.getLength())); //Insert new text from JTextPane into doc kit.insertHTML(doc,doc.getStartPosition().getOffset(), "<p>" + textDoc.getText(0,textDoc.getLength()) + "</p>", 0,0,HTML.Tag.BODY);
//Write doc back to disk as "guestlog.htm" File f = new File("guestlog.htm"); try { FileOutputStream fstrm = new FileOutputStream(f); kit.write(fstrm,doc,0,doc.getLength()); } catch (IOException io) {System.out.println(io.toString());};
} catch (Exception e) { e.printStackTrace(); } }
public void setJTextPane(JTextPane in){ this.textpane = in; this.textDoc = (HTMLDocument)in.getDocument(); this.kit = new HTMLEditorKit(); this.doc = (HTMLDocument)kit.createDefaultDocument(); }
static Reader getReader(String uri) throws IOException { if (uri.startsWith("http:")|| uri.startsWith("file:")) { // Retrieve from Internet. URLConnection conn = new URL(uri).openConnection(); return new InputStreamReader(conn.getInputStream()); } else { // Retrieve from file. return new FileReader(uri); } }
}
The Created HTML-Code looks like follows (look at the wrong body tag inside head):
<html> <head> <body> <p> "Text from JTextPane" </p> </body> <title>G?stebuch </title>
</head> <body bgcolor="#000000" text="#FFFFCC" link="#FF9900" alink="#669933" background="_themes/artsy/arttilea.jpg" vlink="#999900">
</body> </html>
Help is very appreciated!
Greetings, Markus
|
|