簡體   English   中英

如何將StyledDocument從textPane保存到.doc文件?

[英]How to save a StyledDocument from textPane into a .doc file?

我什至不知道這是否可能,但是我想做的是將樣式文檔(用戶可以更改文本:粗體,下划線,斜體和3種字體大小)保存在.doc文件中-這樣他就可以以后可以使用任何其他支持樣式文本的文本編輯器自行打開它。

我在下面編寫了代碼...編輯器起作用了,我可以在文本上應用樣式,但是當我保存時,它將文本保存為黑色,沒有樣式。 我不知道問題出在哪里。 動作可能無法保存。 我嘗試了作家和緩沖作家,但沒有用。 我還嘗試使用HTML編輯器工具包,但它根本不起作用-它保存了一個空白文檔。

也許有人知道如何保存樣式? 感謝幫助:)

public class EditFrame extends javax.swing.JFrame {

JFrame frameEdit = this;
File file; //A file I would like to save to -> fileName.doc
StyledDocument doc;   
HashMap<Object, Action> actions;
StyledEditorKit kit;

public EditFrame() {
    super();
    initComponents();
    JMenu editMenu = createEditMenu();
}

protected JMenu createEditMenu() {
    JMenu menu = editMenu;

    Action action = new StyledEditorKit.BoldAction();
    action.putValue(Action.NAME, "Bold");
    menu.add(action);

    action = new StyledEditorKit.ItalicAction();
    action.putValue(Action.NAME, "Italic");
    menu.add(action);

    //...

    return menu;
}

//I'm guessing this doesn't work correctly too (doesn't read styles), but this is another subject :)
public void readFile(File f) {
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(f), "windows-1250"));
        textPane.read(reader, null);
        textPane.requestFocus();
    } catch (IOException ex) {
        Logger.getLogger(EditFrame.class.getName()).log(Level.SEVERE, null, ex);
    }
}

//SAVE METHOD
private void save(java.awt.event.ActionEvent evt) {                      
    try {
        BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));
        kit = (StyledEditorKit) textPane.getEditorKit();
        doc = (StyledDocument) textPane.getDocument();
        kit.write(out, doc, 0, doc.getLength());
    } catch (FileNotFoundException ex) {
        Logger.getLogger(EditFrame.class.getName()).log(Level.SEVERE, null, ex);
    } catch (UnsupportedEncodingException | BadLocationException ex) {
        Logger.getLogger(EditFrame.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(EditFrame.class.getName()).log(Level.SEVERE, null, ex);
    }
}                     

public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new EditFrame().setVisible(true);
        }
    });
}
}

您可以使用RTFEditorKit ,它支持RTF格式 許多文字處理程序(包括MS Word)都可以使用這種格式。 堅持使用write()OutputStream ,它編寫“適合這種內容處理程序的格式”。 另一個使用Writer將“以純文本形式寫入給定流”。

為什么StyledEditorKit不起作用?

StyledEditorKitDefaultEditorKit獲取其write()實現,“它將文本視為純文本。” StyledEditorKit內部存儲樣式文本,但是不知道任何外部格式。 您必須進入子類之一HTMLEditorKitRTFEditorKit ,以獲取覆蓋默認write() 重寫的方法知道如何將內部格式轉換為外部格式,例如RTF。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM