javadatabaseswingstyledtextstyleddocument

How to persistently store styled text from a Document in a database?


So I'm currently working on a program that allows users to created "posts" with styled text. Right now I'm using Java's DefaultStyledDocument, but I'm open to other options (preferably they implement StyledDocument, though). I originally posted something about directly serializing DefaultStyledDocuments here. However, it may be that there is a better way to store these documents. How can I do this?

Additionally, I want to be able to store these styles in a database (probably MySQL), would there be anything else I need to know when thinking about that? Can I directly export to XML?

Finally, a quick discussion on HTMLDocuments. I could use HTMLDocuments for this, however I've heard bad things about Java's HTML renderer, and I also want users to be able to easily edit the styled text. DefaultStyledDocument allows very easy editing use StyledEditorKit. So HTMLDocuments have their drawbacks, and unless alternative can be found, I'd prefer to stick with DefaultStyledDocuments.


Solution

  • The easiest way to do this is to write the document to RTF text using either RTFEditorKit or the AdvancedRTFEditorKit. Which is preferable depends on what you need the document for. The advanced one has support for tables, images, indentation, and more, but requires a separate jar file. RTFEditorKit is built in, but doesn't need a separate Jar file.

    To write with AdvancedRTFEditorKit:

    AdvancedRTFEditorKit editor = new AdvancedRTFEditorKit();
    Writer writer = new StringWriter();
    editor.write(writer, content, 0, content.getLength());
    writer.close();
    String RTFText = writer.toString();
    

    RTFEditorKit uses a similar process. The result of this, a String, is easy to store in most types of databases.