List of usage examples for javax.swing JEditorPane getDocument
public Document getDocument()
From source file:EditorPaneExample19.java
public EditorPaneExample19() { super("JEditorPane Example 19"); pane = new JEditorPane(); pane.setEditable(true); // Editable getContentPane().add(new JScrollPane(pane), "Center"); // Add a menu bar menuBar = new JMenuBar(); setJMenuBar(menuBar);//w w w .j a va 2 s. c om // Populate it createMenuBar(); // Build the panel of controls JPanel panel = new JPanel(); panel.setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.gridwidth = 1; c.gridheight = 1; c.anchor = GridBagConstraints.EAST; c.fill = GridBagConstraints.NONE; c.weightx = 0.0; c.weighty = 0.0; JLabel urlLabel = new JLabel("URL: ", JLabel.RIGHT); panel.add(urlLabel, c); JLabel loadingLabel = new JLabel("State: ", JLabel.RIGHT); c.gridy = 1; panel.add(loadingLabel, c); JLabel typeLabel = new JLabel("Type: ", JLabel.RIGHT); c.gridy = 2; panel.add(typeLabel, c); c.gridy = 3; panel.add(new JLabel(LOAD_TIME), c); c.gridy = 4; c.gridwidth = 2; c.weightx = 1.0; c.anchor = GridBagConstraints.WEST; onlineLoad = new JCheckBox("Online Load"); panel.add(onlineLoad, c); onlineLoad.setSelected(true); onlineLoad.setForeground(typeLabel.getForeground()); c.gridy = 5; c.gridwidth = 2; c.weightx = 1.0; c.anchor = GridBagConstraints.WEST; editableBox = new JCheckBox("Editable JEditorPane"); panel.add(editableBox, c); editableBox.setSelected(true); editableBox.setForeground(typeLabel.getForeground()); c.gridy = 6; c.weightx = 0.0; JButton saveButton = new JButton("Save"); panel.add(saveButton, c); saveButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { EditorKit kit = pane.getEditorKit(); try { if (kit instanceof RTFEditorKit) { kit.write(System.out, pane.getDocument(), 0, pane.getDocument().getLength()); System.out.flush(); } else { if (writer == null) { writer = new OutputStreamWriter(System.out); pane.write(writer); writer.flush(); } kit.write(writer, pane.getDocument(), 0, pane.getDocument().getLength()); writer.flush(); } } catch (Exception e) { System.out.println("Write failed"); } } }); c.gridx = 1; c.gridy = 0; c.weightx = 1.0; c.anchor = GridBagConstraints.EAST; c.fill = GridBagConstraints.HORIZONTAL; urlCombo = new JComboBox(); panel.add(urlCombo, c); urlCombo.setEditable(true); loadingState = new JLabel(spaces, JLabel.LEFT); loadingState.setForeground(Color.black); c.gridy = 1; panel.add(loadingState, c); loadedType = new JLabel(spaces, JLabel.LEFT); loadedType.setForeground(Color.black); c.gridy = 2; panel.add(loadedType, c); timeLabel = new JLabel(""); c.gridy = 3; panel.add(timeLabel, c); getContentPane().add(panel, "South"); // Register a custom EditorKit for HTML ClassLoader loader = getClass().getClassLoader(); if (loader != null) { // Java 2 JEditorPane.registerEditorKitForContentType("text/html", "AdvancedSwing.Chapter4.EnhancedHTMLEditorKit", loader); } else { // JDK 1.1 JEditorPane.registerEditorKitForContentType("text/html", "AdvancedSwing.Chapter4.EnhancedHTMLEditorKit"); } // Allocate the empty tree model DefaultMutableTreeNode emptyRootNode = new DefaultMutableTreeNode("Empty"); emptyModel = new DefaultTreeModel(emptyRootNode); // Create and place the heading tree tree = new JTree(emptyModel); tree.setPreferredSize(new Dimension(200, 200)); getContentPane().add(new JScrollPane(tree), "East"); // Change page based on combo selection urlCombo.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { if (populatingCombo == true) { return; } Object selection = urlCombo.getSelectedItem(); loadNewPage(selection); } }); // Change editability based on the checkbox editableBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { pane.setEditable(editableBox.isSelected()); pane.revalidate(); pane.repaint(); } }); // Listen for page load to complete pane.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { if (evt.getPropertyName().equals("page")) { loadComplete(); displayLoadTime(); populateCombo(findLinks(pane.getDocument(), null)); TreeNode node = buildHeadingTree(pane.getDocument()); tree.setModel(new DefaultTreeModel(node)); createMenuBar(); enableMenuBar(true); getRootPane().revalidate(); enableInput(); loadingPage = false; } } }); // Listener for tree selection tree.addTreeSelectionListener(new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent evt) { TreePath path = evt.getNewLeadSelectionPath(); if (path != null) { DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent(); Object userObject = node.getUserObject(); if (userObject instanceof Heading) { Heading heading = (Heading) userObject; try { Rectangle textRect = pane.modelToView(heading.getOffset()); textRect.y += 3 * textRect.height; pane.scrollRectToVisible(textRect); } catch (BadLocationException e) { } } } } }); // Listener for hypertext events pane.addHyperlinkListener(new HyperlinkListener() { public void hyperlinkUpdate(HyperlinkEvent evt) { // Ignore hyperlink events if the frame is busy if (loadingPage == true) { return; } if (evt.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { JEditorPane sp = (JEditorPane) evt.getSource(); if (evt instanceof HTMLFrameHyperlinkEvent) { HTMLDocument doc = (HTMLDocument) sp.getDocument(); doc.processHTMLFrameHyperlinkEvent((HTMLFrameHyperlinkEvent) evt); } else { loadNewPage(evt.getURL()); } } else if (evt.getEventType() == HyperlinkEvent.EventType.ENTERED) { pane.setCursor(handCursor); } else if (evt.getEventType() == HyperlinkEvent.EventType.EXITED) { pane.setCursor(defaultCursor); } } }); }
From source file:EditorPaneExample18.java
public EditorPaneExample18() { super("JEditorPane Example 18"); pane = new JEditorPane(); pane.setEditable(true); // Editable getContentPane().add(new JScrollPane(pane), "Center"); // Add a menu bar menuBar = new JMenuBar(); setJMenuBar(menuBar);//from w w w. ja v a2s. c o m // Populate it createMenuBar(); // Build the panel of controls JPanel panel = new JPanel(); panel.setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.gridwidth = 1; c.gridheight = 1; c.anchor = GridBagConstraints.EAST; c.fill = GridBagConstraints.NONE; c.weightx = 0.0; c.weighty = 0.0; JLabel urlLabel = new JLabel("URL: ", JLabel.RIGHT); panel.add(urlLabel, c); JLabel loadingLabel = new JLabel("State: ", JLabel.RIGHT); c.gridy = 1; panel.add(loadingLabel, c); JLabel typeLabel = new JLabel("Type: ", JLabel.RIGHT); c.gridy = 2; panel.add(typeLabel, c); c.gridy = 3; panel.add(new JLabel(LOAD_TIME), c); c.gridy = 4; c.gridwidth = 2; c.weightx = 1.0; c.anchor = GridBagConstraints.WEST; onlineLoad = new JCheckBox("Online Load"); panel.add(onlineLoad, c); onlineLoad.setSelected(true); onlineLoad.setForeground(typeLabel.getForeground()); c.gridy = 5; c.gridwidth = 2; c.weightx = 1.0; c.anchor = GridBagConstraints.WEST; editableBox = new JCheckBox("Editable JEditorPane"); panel.add(editableBox, c); editableBox.setSelected(true); editableBox.setForeground(typeLabel.getForeground()); c.gridy = 6; c.weightx = 0.0; JButton saveButton = new JButton("Save"); panel.add(saveButton, c); saveButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { EditorKit kit = pane.getEditorKit(); try { if (kit instanceof RTFEditorKit) { kit.write(System.out, pane.getDocument(), 0, pane.getDocument().getLength()); System.out.flush(); } else { if (writer == null) { writer = new OutputStreamWriter(System.out); pane.write(writer); writer.flush(); } kit.write(writer, pane.getDocument(), 0, pane.getDocument().getLength()); writer.flush(); } } catch (Exception e) { System.out.println("Write failed"); } } }); c.gridx = 1; c.gridy = 0; c.weightx = 1.0; c.anchor = GridBagConstraints.EAST; c.fill = GridBagConstraints.HORIZONTAL; urlCombo = new JComboBox(); panel.add(urlCombo, c); urlCombo.setEditable(true); loadingState = new JLabel(spaces, JLabel.LEFT); loadingState.setForeground(Color.black); c.gridy = 1; panel.add(loadingState, c); loadedType = new JLabel(spaces, JLabel.LEFT); loadedType.setForeground(Color.black); c.gridy = 2; panel.add(loadedType, c); timeLabel = new JLabel(""); c.gridy = 3; panel.add(timeLabel, c); getContentPane().add(panel, "South"); // Register a custom EditorKit for HTML ClassLoader loader = getClass().getClassLoader(); if (loader != null) { // Java 2 JEditorPane.registerEditorKitForContentType("text/html", "AdvancedSwing.Chapter4.HiddenViewHTMLEditorKit", loader); } else { // JDK 1.1 JEditorPane.registerEditorKitForContentType("text/html", "AdvancedSwing.Chapter4.HiddenViewHTMLEditorKit"); } // Allocate the empty tree model DefaultMutableTreeNode emptyRootNode = new DefaultMutableTreeNode("Empty"); emptyModel = new DefaultTreeModel(emptyRootNode); // Create and place the heading tree tree = new JTree(emptyModel); tree.setPreferredSize(new Dimension(200, 200)); getContentPane().add(new JScrollPane(tree), "East"); // Change page based on combo selection urlCombo.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { if (populatingCombo == true) { return; } Object selection = urlCombo.getSelectedItem(); loadNewPage(selection); } }); // Change editability based on the checkbox editableBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { pane.setEditable(editableBox.isSelected()); pane.revalidate(); pane.repaint(); } }); // Listen for page load to complete pane.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { if (evt.getPropertyName().equals("page")) { loadComplete(); displayLoadTime(); populateCombo(findLinks(pane.getDocument(), null)); TreeNode node = buildHeadingTree(pane.getDocument()); tree.setModel(new DefaultTreeModel(node)); createMenuBar(); enableMenuBar(true); getRootPane().revalidate(); enableInput(); loadingPage = false; } } }); // Listener for tree selection tree.addTreeSelectionListener(new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent evt) { TreePath path = evt.getNewLeadSelectionPath(); if (path != null) { DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent(); Object userObject = node.getUserObject(); if (userObject instanceof Heading) { Heading heading = (Heading) userObject; try { Rectangle textRect = pane.modelToView(heading.getOffset()); textRect.y += 3 * textRect.height; pane.scrollRectToVisible(textRect); } catch (BadLocationException e) { } } } } }); // Listener for hypertext events pane.addHyperlinkListener(new HyperlinkListener() { public void hyperlinkUpdate(HyperlinkEvent evt) { // Ignore hyperlink events if the frame is busy if (loadingPage == true) { return; } if (evt.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { JEditorPane sp = (JEditorPane) evt.getSource(); if (evt instanceof HTMLFrameHyperlinkEvent) { HTMLDocument doc = (HTMLDocument) sp.getDocument(); doc.processHTMLFrameHyperlinkEvent((HTMLFrameHyperlinkEvent) evt); } else { loadNewPage(evt.getURL()); } } else if (evt.getEventType() == HyperlinkEvent.EventType.ENTERED) { pane.setCursor(handCursor); } else if (evt.getEventType() == HyperlinkEvent.EventType.EXITED) { pane.setCursor(defaultCursor); } } }); }
From source file:EditorPaneExample20.java
public EditorPaneExample20() { super("JEditorPane Example 20"); pane = new JEditorPane(); pane.setEditable(true); // Editable getContentPane().add(new JScrollPane(pane), "Center"); // Add a menu bar menuBar = new JMenuBar(); setJMenuBar(menuBar);//from www .j a v a 2 s .c o m // Populate it createMenuBar(); // Build the panel of controls JPanel panel = new JPanel(); panel.setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.gridwidth = 1; c.gridheight = 1; c.anchor = GridBagConstraints.EAST; c.fill = GridBagConstraints.NONE; c.weightx = 0.0; c.weighty = 0.0; JLabel urlLabel = new JLabel("URL: ", JLabel.RIGHT); panel.add(urlLabel, c); JLabel loadingLabel = new JLabel("State: ", JLabel.RIGHT); c.gridy = 1; panel.add(loadingLabel, c); JLabel typeLabel = new JLabel("Type: ", JLabel.RIGHT); c.gridy = 2; panel.add(typeLabel, c); c.gridy = 3; panel.add(new JLabel(LOAD_TIME), c); c.gridy = 4; c.gridwidth = 2; c.weightx = 1.0; c.anchor = GridBagConstraints.WEST; onlineLoad = new JCheckBox("Online Load"); panel.add(onlineLoad, c); onlineLoad.setSelected(true); onlineLoad.setForeground(typeLabel.getForeground()); c.gridy = 5; c.gridwidth = 2; c.weightx = 1.0; c.anchor = GridBagConstraints.WEST; editableBox = new JCheckBox("Editable JEditorPane"); panel.add(editableBox, c); editableBox.setSelected(true); editableBox.setForeground(typeLabel.getForeground()); c.gridy = 6; c.weightx = 0.0; JButton saveButton = new JButton("Save"); panel.add(saveButton, c); saveButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { EditorKit kit = pane.getEditorKit(); try { if (kit instanceof RTFEditorKit) { kit.write(System.out, pane.getDocument(), 0, pane.getDocument().getLength()); System.out.flush(); } else { if (writer == null) { writer = new OutputStreamWriter(System.out); pane.write(writer); writer.flush(); } kit.write(writer, pane.getDocument(), 0, pane.getDocument().getLength()); writer.flush(); } } catch (Exception e) { System.out.println("Write failed"); } } }); c.gridx = 1; insertButton = new JButton("Insert HTML"); panel.add(insertButton, c); insertButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { if (insertFrame == null) { insertFrame = new HTMLInsertFrame("HTML Insertion", pane); Point pt = EditorPaneExample20.this.getLocationOnScreen(); Dimension d = EditorPaneExample20.this.getSize(); insertFrame.setLocation(pt.x + d.width, pt.y); insertFrame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent evt) { insertFrame.dispose(); insertFrame = null; setInsertButtonState(); } }); insertButton.setEnabled(false); insertFrame.setVisible(true); } } }); insertButton.setEnabled(false); c.gridx = 1; c.gridy = 0; c.weightx = 1.0; c.anchor = GridBagConstraints.EAST; c.fill = GridBagConstraints.HORIZONTAL; urlCombo = new JComboBox(); panel.add(urlCombo, c); urlCombo.setEditable(true); loadingState = new JLabel(spaces, JLabel.LEFT); loadingState.setForeground(Color.black); c.gridy = 1; panel.add(loadingState, c); loadedType = new JLabel(spaces, JLabel.LEFT); loadedType.setForeground(Color.black); c.gridy = 2; panel.add(loadedType, c); timeLabel = new JLabel(""); c.gridy = 3; panel.add(timeLabel, c); getContentPane().add(panel, "South"); // Register a custom EditorKit for HTML ClassLoader loader = getClass().getClassLoader(); if (loader != null) { // Java 2 JEditorPane.registerEditorKitForContentType("text/html", "AdvancedSwing.Chapter4.EnhancedHTMLEditorKit", loader); } else { // JDK 1.1 JEditorPane.registerEditorKitForContentType("text/html", "AdvancedSwing.Chapter4.EnhancedHTMLEditorKit"); } // Allocate the empty tree model DefaultMutableTreeNode emptyRootNode = new DefaultMutableTreeNode("Empty"); emptyModel = new DefaultTreeModel(emptyRootNode); // Create and place the heading tree tree = new JTree(emptyModel); tree.setPreferredSize(new Dimension(200, 200)); getContentPane().add(new JScrollPane(tree), "East"); // Change page based on combo selection urlCombo.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { if (populatingCombo == true) { return; } Object selection = urlCombo.getSelectedItem(); loadNewPage(selection); } }); // Change editability based on the checkbox editableBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { pane.setEditable(editableBox.isSelected()); pane.revalidate(); pane.repaint(); } }); // Listen for page load to complete pane.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { if (evt.getPropertyName().equals("page")) { loadComplete(); displayLoadTime(); populateCombo(findLinks(pane.getDocument(), null)); TreeNode node = buildHeadingTree(pane.getDocument()); tree.setModel(new DefaultTreeModel(node)); createMenuBar(); enableMenuBar(true); getRootPane().revalidate(); enableInput(); loadingPage = false; } } }); // Listener for tree selection tree.addTreeSelectionListener(new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent evt) { TreePath path = evt.getNewLeadSelectionPath(); if (path != null) { DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent(); Object userObject = node.getUserObject(); if (userObject instanceof Heading) { Heading heading = (Heading) userObject; try { Rectangle textRect = pane.modelToView(heading.getOffset()); textRect.y += 3 * textRect.height; pane.scrollRectToVisible(textRect); } catch (BadLocationException e) { } } } } }); // Listener for hypertext events pane.addHyperlinkListener(new HyperlinkListener() { public void hyperlinkUpdate(HyperlinkEvent evt) { // Ignore hyperlink events if the frame is busy if (loadingPage == true) { return; } if (evt.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { JEditorPane sp = (JEditorPane) evt.getSource(); if (evt instanceof HTMLFrameHyperlinkEvent) { HTMLDocument doc = (HTMLDocument) sp.getDocument(); doc.processHTMLFrameHyperlinkEvent((HTMLFrameHyperlinkEvent) evt); } else { loadNewPage(evt.getURL()); } } else if (evt.getEventType() == HyperlinkEvent.EventType.ENTERED) { pane.setCursor(handCursor); } else if (evt.getEventType() == HyperlinkEvent.EventType.EXITED) { pane.setCursor(defaultCursor); } } }); }
From source file:com.centurylink.mdw.designer.pages.ExportHelper.java
private void printHtmlParagraphsPdf(Section section, String content, int parentLevel) throws Exception { if (content == null || content.length() == 0) return;//from w ww . ja va2 s . co m if (isBase64Encoded(content) || "true".equals(System.getProperty("mdw.designer.force.msword"))) { byte[] docBytes = decodeBase64(content); content = new DocxBuilder(docBytes).toHtml(); content = content.replaceAll(" ", " "); } JEditorPane documentation = new JEditorPane(); documentation.setContentType("text/html"); documentation.setText(content); javax.swing.text.Document swingdoc = documentation.getDocument(); Element[] elements = swingdoc.getRootElements(); boolean useGenerate = true; if (useGenerate) { for (Element e : elements) { Object gen = generateElementHtml(e, 0, normalFont); addSectionContentPdf(section, gen, parentLevel); } } else { // use print for (Element e : elements) { printElementHtml(e, section, 0, normalFont, parentLevel); } } }
From source file:net.java.sip.communicator.impl.gui.main.chat.ChatPanel.java
/** * Checks if the editor contains text./*from w w w. j a v a 2 s.c om*/ * * @return TRUE if editor contains text, FALSE otherwise. */ public boolean isWriteAreaEmpty() { JEditorPane editorPane = getChatWritePanel().getEditorPane(); Document doc = editorPane.getDocument(); try { String text = doc.getText(0, doc.getLength()); if (text == null || text.equals("")) return true; } catch (BadLocationException e) { logger.error("Failed to obtain document text.", e); } return false; }
From source file:com.hexidec.ekit.action.ListAutomationAction.java
public void actionPerformed(ActionEvent ae) { try {//from w w w. j a v a2 s .c o m JEditorPane jepEditor = (JEditorPane) (parentEkit.getTextPane()); String selTextBase = jepEditor.getSelectedText(); int textLength = -1; if (selTextBase != null) { textLength = selTextBase.length(); } if (selTextBase == null || textLength < 1) { int pos = parentEkit.getCaretPosition(); parentEkit.setCaretPosition(pos); if (ae.getActionCommand() != "newListPoint") { if (htmlUtilities.checkParentsTag(HTML.Tag.OL) || htmlUtilities.checkParentsTag(HTML.Tag.UL)) { revertList(htmlUtilities.getListItemContainer()); return; } } String sListType = (baseTag == HTML.Tag.OL ? "ol" : "ul"); StringBuffer sbNew = new StringBuffer(); if (htmlUtilities.checkParentsTag(baseTag)) { sbNew.append("<li></li>"); insertHTML(parentEkit.getTextPane(), parentEkit.getExtendedHtmlDoc(), parentEkit.getTextPane().getCaretPosition(), sbNew.toString(), 0, 0, HTML.Tag.LI); } else { boolean isLast = false; int caretPos = parentEkit.getCaretPosition(); if (caretPos == parentEkit.getExtendedHtmlDoc().getLength()) { isLast = true; } sbNew.append("<" + sListType + "><li></li></" + sListType + ">" + (isLast ? "<p style=\"margin-top: 0\"> </p>" : "")); insertHTML(parentEkit.getTextPane(), parentEkit.getExtendedHtmlDoc(), parentEkit.getTextPane().getCaretPosition(), sbNew.toString(), 0, 0, (sListType.equals("ol") ? HTML.Tag.OL : HTML.Tag.UL)); if (true) { parentEkit.setCaretPosition(caretPos + 1); } } parentEkit.refreshOnUpdate(); } else { if (htmlUtilities.checkParentsTag(HTML.Tag.OL) || htmlUtilities.checkParentsTag(HTML.Tag.UL)) { revertList(htmlUtilities.getListItemContainer()); return; } else { String sListType = (baseTag == HTML.Tag.OL ? "ol" : "ul"); HTMLDocument htmlDoc = (HTMLDocument) (jepEditor.getDocument()); int iStart = jepEditor.getSelectionStart(); int iEnd = jepEditor.getSelectionEnd(); String selText = htmlDoc.getText(iStart, iEnd - iStart); /* for(int ch = 0; ch < selText.length(); ch++) { Element elem = htmlDoc.getCharacterElement(iStart + ch); log.debug("elem " + ch + ": " + elem.getName()); log.debug("char " + ch + ": " + selText.charAt(ch) + " [" + Character.getNumericValue(selText.charAt(ch)) + "]"); if(Character.getNumericValue(selText.charAt(ch)) < 0) { log.debug(" is space? " + ((selText.charAt(ch) == '\u0020') ? "YES" : "---")); log.debug(" is return? " + ((selText.charAt(ch) == '\r') ? "YES" : "---")); log.debug(" is newline? " + ((selText.charAt(ch) == '\n') ? "YES" : "---")); log.debug(" is nextline? " + ((selText.charAt(ch) == '\u0085') ? "YES" : "---")); log.debug(" is linesep? " + ((selText.charAt(ch) == '\u2028') ? "YES" : "---")); log.debug(" is parasep? " + ((selText.charAt(ch) == '\u2029') ? "YES" : "---")); log.debug(" is verttab? " + ((selText.charAt(ch) == '\u000B') ? "YES" : "---")); log.debug(" is formfeed? " + ((selText.charAt(ch) == '\u000C') ? "YES" : "---")); } } */ StringBuffer sbNew = new StringBuffer(); sbNew.append("<" + sListType + ">"); // tokenize on known linebreaks if present, otherwise manually parse on <br> break tags if ((selText.indexOf("\r") > -1) || (selText.indexOf("\n") > -1)) { String sToken = ((selText.indexOf("\r") > -1) ? "\r" : "\n"); StringTokenizer stTokenizer = new StringTokenizer(selText, sToken); while (stTokenizer.hasMoreTokens()) { sbNew.append("<li>"); sbNew.append(stTokenizer.nextToken()); sbNew.append("</li>"); } } else { StringBuffer sbItem = new StringBuffer(); for (int ch = 0; ch < selText.length(); ch++) { String elem = (htmlDoc.getCharacterElement(iStart + ch) != null ? htmlDoc.getCharacterElement(iStart + ch).getName().toLowerCase() : "[null]"); if (elem.equals("br") && sbItem.length() > 0) { sbNew.append("<li>"); sbNew.append(sbItem.toString()); sbNew.append("</li>"); sbItem.delete(0, sbItem.length()); } else { sbItem.append(selText.charAt(ch)); } } } sbNew.append("</" + sListType + ">"); htmlDoc.remove(iStart, iEnd - iStart); insertHTML(jepEditor, htmlDoc, iStart, sbNew.toString(), 1, 1, null); } } } catch (BadLocationException ble) { } }
From source file:org.docx4all.swing.text.WordMLEditorKit.java
private void refreshCaretElement(JEditorPane editor) { caretListener.caretElement = null;//from ww w .ja va 2s .co m int start = editor.getSelectionStart(); int end = editor.getSelectionEnd(); WordMLDocument doc = (WordMLDocument) editor.getDocument(); try { doc.readLock(); caretListener.updateCaretElement(start, end, editor); } finally { doc.readUnlock(); } }
From source file:org.docx4all.ui.menu.FileMenu.java
@Action public void printPreview() { WordMLEditor wmlEditor = WordMLEditor.getInstance(WordMLEditor.class); JEditorPane editor = wmlEditor.getCurrentEditor(); WordMLEditorKit kit = (WordMLEditorKit) editor.getEditorKit(); kit.saveCaretText();//from w w w .jav a 2s . c o m Document doc = editor.getDocument(); String filePath = (String) doc.getProperty(WordMLDocument.FILE_PATH_PROPERTY); DocumentElement elem = (DocumentElement) doc.getDefaultRootElement(); DocumentML rootML = (DocumentML) elem.getElementML(); //Do not include the last paragraph when saving or printing. //we'll put it back when the job is done. elem = (DocumentElement) elem.getElement(elem.getElementCount() - 1); ElementML paraML = elem.getElementML(); ElementML bodyML = paraML.getParent(); paraML.delete(); try { WordprocessingMLPackage wordMLPackage = rootML.getWordprocessingMLPackage(); // XmlPackage worker = new XmlPackage(wordMLPackage); // org.docx4j.xmlPackage.Package result = worker.get(); // boolean suppressDeclaration = true; // boolean prettyprint = true; // System.out.println( // org.docx4j.XmlUtils. // marshaltoString(result, suppressDeclaration, prettyprint, // org.docx4j.jaxb.Context.jcXmlPackage) ); //Create temporary .pdf file. //Remember that filePath is in Commons-VFS format which //uses '/' as separator char. String tmpName = filePath.substring(filePath.lastIndexOf("/"), filePath.lastIndexOf(Constants.DOT)); File tmpFile = File.createTempFile(tmpName + ".tmp", ".pdf"); // Delete the temporary file when program exits. tmpFile.deleteOnExit(); OutputStream os = new java.io.FileOutputStream(tmpFile); // Could write to a ByteBuffer and avoid the temp file if: // 1. com.sun.pdfview.PDFViewer had an appropriate open method // 2. We knew how big to make the buffer // java.nio.ByteBuffer buf = java.nio.ByteBuffer.allocate(15000); // //15kb // OutputStream os = newOutputStream(buf); PdfConversion c = new org.docx4j.convert.out.pdf.viaXSLFO.Conversion(wordMLPackage); // can change from viaHTML to viaIText or viaXSLFO PdfSettings settings = new PdfSettings(); c.output(os, settings); os.close(); PDFViewer pv = new PDFViewer(true); // pv.openFile(buf, "some name"); // requires modified // com.sun.pdfview.PDFViewer pv.openFile(tmpFile); } catch (Exception exc) { exc.printStackTrace(); ResourceMap rm = wmlEditor.getContext().getResourceMap(getClass()); String title = rm.getString(PRINT_PREVIEW_ACTION_NAME + ".Action.text"); String message = rm.getString(PRINT_PREVIEW_ACTION_NAME + ".Action.errorMessage") + "\n" + VFSUtils.getFriendlyName(filePath); wmlEditor.showMessageDialog(title, message, JOptionPane.ERROR_MESSAGE); } finally { //Remember to put 'paraML' as last paragraph bodyML.addChild(paraML); } }
From source file:org.docx4all.ui.menu.FileMenu.java
/** * Saves editor documents to a file./*from w w w. j a v a 2s . co m*/ * * Internal frame may have two editors for presenting two different views * to user namely editor view and source view. WordMLTextPane is used for * editor view and JEditorPane for source view. * The contents of these two editors are synchronized when user switches * from one view to the other. Therefore, there will be ONLY ONE editor * that is dirty and has to be saved by this method. * * @param iframe * @param saveAsFilePath * @param callerActionName * @return */ public boolean save(JInternalFrame iframe, String saveAsFilePath, String callerActionName) { boolean success = true; if (saveAsFilePath == null) { saveAsFilePath = (String) iframe.getClientProperty(WordMLDocument.FILE_PATH_PROPERTY); } if (log.isDebugEnabled()) { log.debug("save(): filePath=" + VFSUtils.getFriendlyName(saveAsFilePath)); } WordMLTextPane editorView = SwingUtil.getWordMLTextPane(iframe); JEditorPane sourceView = SwingUtil.getSourceEditor(iframe); if (sourceView != null && !((Boolean) sourceView.getClientProperty(Constants.LOCAL_VIEWS_SYNCHRONIZED_FLAG)) .booleanValue()) { //signifies that Source View is not synchronised with Editor View yet. //Therefore, it is dirty and has to be saved. if (editorView != null && editorView.getWordMLEditorKit().getPlutextClient() != null) { //Document has to be saved from editor view //by committing local edits success = false; } else { EditorKit kit = sourceView.getEditorKit(); Document doc = sourceView.getDocument(); WordprocessingMLPackage wmlPackage = (WordprocessingMLPackage) doc .getProperty(WordMLDocument.WML_PACKAGE_PROPERTY); DocUtil.write(kit, doc, wmlPackage); success = save(wmlPackage, saveAsFilePath, callerActionName); if (success) { if (saveAsFilePath.endsWith(Constants.DOCX_STRING) || saveAsFilePath.endsWith(Constants.FLAT_OPC_STRING)) { doc.putProperty(WordMLDocument.FILE_PATH_PROPERTY, saveAsFilePath); iframe.putClientProperty(WordMLDocument.FILE_PATH_PROPERTY, saveAsFilePath); } } } return success; } sourceView = null; if (editorView == null) { ;//pass } else if (editorView.getWordMLEditorKit().getPlutextClient() != null) { if (saveAsFilePath.equals(editorView.getDocument().getProperty(WordMLDocument.FILE_PATH_PROPERTY))) { success = commitLocalChanges(editorView, callerActionName); } else { //TODO: Enable saving Plutext document as a new file. WordMLEditor wmlEditor = WordMLEditor.getInstance(WordMLEditor.class); ResourceMap rm = wmlEditor.getContext().getResourceMap(getClass()); String title = rm.getString(callerActionName + ".Action.text"); StringBuilder message = new StringBuilder(); message.append("File "); message.append(saveAsFilePath); message.append(Constants.NEWLINE); message.append(rm.getString(callerActionName + ".Action.wrong.fileName.infoMessage")); wmlEditor.showMessageDialog(title, message.toString(), JOptionPane.INFORMATION_MESSAGE); success = false; } } else { WordMLEditorKit kit = (WordMLEditorKit) editorView.getEditorKit(); kit.saveCaretText(); Document doc = editorView.getDocument(); DocumentElement elem = (DocumentElement) doc.getDefaultRootElement(); DocumentML rootML = (DocumentML) elem.getElementML(); //Do not include the last paragraph when saving. //After saving we put it back. elem = (DocumentElement) elem.getElement(elem.getElementCount() - 1); ElementML paraML = elem.getElementML(); ElementML bodyML = paraML.getParent(); paraML.delete(); success = save(rootML.getWordprocessingMLPackage(), saveAsFilePath, callerActionName); //Remember to put 'paraML' as last paragraph bodyML.addChild(paraML); if (success) { if (saveAsFilePath.endsWith(Constants.DOCX_STRING)) { doc.putProperty(WordMLDocument.FILE_PATH_PROPERTY, saveAsFilePath); iframe.putClientProperty(WordMLDocument.FILE_PATH_PROPERTY, saveAsFilePath); } } } return success; }
From source file:org.docx4all.ui.menu.FileMenu.java
public boolean export(JInternalFrame iframe, String saveAsFilePath, String callerActionName) { log.debug("export(): filePath=" + VFSUtils.getFriendlyName(saveAsFilePath)); WordprocessingMLPackage srcPackage = null; WordMLTextPane editorView = SwingUtil.getWordMLTextPane(iframe); JEditorPane sourceView = SwingUtil.getSourceEditor(iframe); if (sourceView != null && !((Boolean) sourceView.getClientProperty(Constants.LOCAL_VIEWS_SYNCHRONIZED_FLAG)) .booleanValue()) {//from ww w .java 2s . c o m //signifies that Source View is not synchronised with Editor View yet. //Therefore, export from Source View. EditorKit kit = sourceView.getEditorKit(); Document doc = sourceView.getDocument(); srcPackage = DocUtil.write(kit, doc, null); editorView = null; } sourceView = null; if (editorView == null) { ;//pass } else { WordMLDocument doc = (WordMLDocument) editorView.getDocument(); DocumentElement root = (DocumentElement) doc.getDefaultRootElement(); DocumentML docML = (DocumentML) root.getElementML(); srcPackage = docML.getWordprocessingMLPackage(); } boolean success = save(XmlUtil.export(srcPackage), saveAsFilePath, callerActionName); log.debug("export(): success=" + success + " filePath=" + VFSUtils.getFriendlyName(saveAsFilePath)); return success; }