public static final String RTF2TXT(String Str) throws IOException, BadLocationException { if (Str != null && Str.startsWith("{\\rtf1") == true) { // There is a "questionable" bug in the RTF-to-Text routine in the Java library. With tables, text in // adjacent cells are concatenated without any // spacing. So, for example, a table with a cell containing "abc" followed by another call containing "123", // after conversion, you'll get "abc123". // With this hack, we capture the RTF cell delimiter "\cell$" and replace it with ". \cell$". This will // separate text in cells from other text and will // allow text processing to give better results. Str = RTF_CELL_PATTERN.matcher(Str).replaceAll(". $0"); RTFEditorKit RTF = new RTFEditorKit(); Document doc = RTF.createDefaultDocument(); RTF.read(new StringReader(Str), doc, 0); Str = doc.getText(0, doc.getLength()); } return Str; }
public static void main(String[] args) throws Exception{ rtfEditorKit = new RTFEditorKit(); robot = new Robot(); SwingUtilities.invokeAndWait(() -> { frame = new JFrame(); frame.setUndecorated(true); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setSize(600, 200); jTextPane = new JTextPane(); frame.getContentPane().add(jTextPane); frame.setVisible(true); }); test(StyleConstants.ALIGN_LEFT); test(StyleConstants.ALIGN_CENTER); test(StyleConstants.ALIGN_RIGHT); test(StyleConstants.ALIGN_JUSTIFIED); SwingUtilities.invokeAndWait(()->frame.dispose()); System.out.println("ok"); }
/** * {@inheritDoc} */ public String extractText(InputStream stream, String type, String encoding) throws IOException { try { RTFEditorKit rek = new RTFEditorKit(); DefaultStyledDocument doc = new DefaultStyledDocument(); rek.read(stream, doc, 0); String text = doc.getText(0, doc.getLength()); return text; } catch (Throwable e) { logger.warn("Failed to extract RTF text content", e); throw new IOException(e.getMessage(), e); } finally { stream.close(); } }
/** * @param db The {@link Dragboard} containing the dragged data. * @param selection_tracker Used to get the grid steps from its model to be * used in offsetting multiple widgets. * @param widgets The container of the created widgets. */ private static void installWidgetsFromRTF ( final DragEvent event, final SelectedWidgetUITracker selection_tracker, final List<Widget> widgets ) { final Dragboard db = event.getDragboard(); final String rtf = db.getRtf(); final RTFEditorKit rtfParser = new RTFEditorKit(); final Document document = rtfParser.createDefaultDocument(); try { rtfParser.read(new ByteArrayInputStream(rtf.getBytes()), document, 0); installWidgetsFromString(event, document.getText(0, document.getLength()), selection_tracker, widgets); } catch ( Exception ex ) { logger.log(Level.WARNING, "Invalid RTF string", ex); } }
@Override public void actionPerformed(ActionEvent event) { try { boolean b = sysCaller.isPastingAllowed(); System.out.println("Pasting allowed: " + b); if (!b) { JOptionPane.showMessageDialog(null, sysCaller.getLastError()); return; } RTFEditorKit myEditorKit = (RTFEditorKit) myEditorPane.getEditorKit(); Action edKitPasteAct = getActionByName(RTFEditorKit.pasteAction); edKitPasteAct.actionPerformed(event); } catch (Exception e) { e.printStackTrace(); JOptionPane.showMessageDialog(RTFEditor.this, "Exception while copying selected text: " + e.getMessage()); } }
public void testTextRtfEditorKits() { JEditorPane pane = new JEditorPane(); setContentTypeInAwt(pane, "text/rtf"); // Test JDK kit EditorKit kitFromJdk = pane.getEditorKit(); assertNotNull("Can't find JDK kit for text/rtf", kitFromJdk); assertTrue("Wrong JDK kit for application/rtf", kitFromJdk instanceof RTFEditorKit); }
public void testApplicationRtfEditorKits() { JEditorPane pane = new JEditorPane(); setContentTypeInAwt(pane, "application/rtf"); // Test JDK kit EditorKit kitFromJdk = pane.getEditorKit(); assertNotNull("Can't find JDK kit for application/rtf", kitFromJdk); assertTrue("Wrong JDK kit for application/rtf", kitFromJdk instanceof RTFEditorKit); }
/** * Constructor for RTFFileExport. */ public RTFFileExport(File f, Document doc) { RTFEditorKit kit = new RTFEditorKit(); try { kit.write(new FileOutputStream(f), (DefaultStyledDocument)doc, 0, doc.getLength()); } catch (Exception ex) { ex.printStackTrace(); } }
public RTFDocsSwingDisplayer(String heading, String filename, String jarName) { super(heading); setSize(650, 550); // Initialize String which will go into the JTextPane String display_me = readFile(filename, jarName); // Buttons b1 = new JButton("Back"); b1.setActionCommand("back"); b1.addActionListener(this); // Initializing JTextPane() JTextPane textPane = new JTextPane(); RTFEditorKit rtfkit = new RTFEditorKit(); // HTMLEditorKit htmlkit = new HTMLEditorKit(); textPane.setEditorKit(rtfkit); // set Kit which will read RTF Doc // textPane.setEditorKit(htmlkit); textPane.setEditable(false); // make uneditable textPane.setText(display_me); // set the Text textPane.setCaretPosition(0); // set Cret position to 0 // Panels and addition to container p1 = new JPanel(); Container contentPane = getContentPane(); contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS)); p1.setLayout(new BoxLayout(this.p1, BoxLayout.Y_AXIS)); p1.add(new JScrollPane(textPane)); p1.add(b1); contentPane.add(p1); setVisible(true); }
public HyperCardTextField(ToolEditablePart toolEditablePart) { this.toolEditablePart = toolEditablePart; // Create the editor component textPane = new HyperCardTextPane(new DefaultStyledDocument()); textPane.setEditorKit(new RTFEditorKit()); this.setViewportView(textPane); getViewport().addChangeListener(e -> { textPane.invalidateViewport(getViewport()); }); }
private byte[] convertDocumentToRtf(StyledDocument doc) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { new RTFEditorKit().write(baos, doc, 0, doc.getLength()); baos.close(); return baos.toByteArray(); } catch (IOException | BadLocationException e) { throw new RuntimeException("An error occurred while saving field contents.", e); } }
public static void parse( String rtfString, RTFDocumentHandler handler ) throws IOException, BadLocationException { RTFEditorKit rtfeditorkit = new RTFEditorKit( ); DefaultStyledDocument document = new DefaultStyledDocument( ); ByteArrayInputStream bytearrayinputstream = new ByteArrayInputStream( rtfString.getBytes( ) ); rtfeditorkit.read( bytearrayinputstream, document, 0 ); Element element = document.getDefaultRootElement( ); parseElement( document, element, handler, true ); }
public String toHtml(String s2) { RTFEditorKit rtfeditorkit = new RTFEditorKit(); DefaultStyledDocument defaultstyleddocument = new DefaultStyledDocument(); readString(s2, defaultstyleddocument, rtfeditorkit); scanDocument(defaultstyleddocument); // Parse all rtf elements for (RtfElementParser r : parserItems) { r.parseDocElements(entries.entrySet().iterator()); } // Parse all textnodes for (Map.Entry<TextNode, Element> entry : entries.entrySet()) { TextNode txtNode = entry.getKey(); // Replace \n an element node while (txtNode.getWholeText().contains("\n")){ int pos = txtNode.getWholeText().indexOf("\n"); String txt = txtNode.getWholeText(); txtNode.before(new TextNode(txt.substring(0, pos), "")); txtNode.before(new org.jsoup.nodes.Element(Tag.valueOf("br"), "")); txtNode.text(txt.substring(pos + 1)); } } return removeEmptyNodes(body).toString(); }
private void readString(String s, Document document, RTFEditorKit rtfeditorkit) { try { ByteArrayInputStream bytearrayinputstream = new ByteArrayInputStream( s.getBytes()); rtfeditorkit.read(bytearrayinputstream, document, 0); } catch (Exception exception) { return; // exception.printStackTrace(); } }
@Override protected void parseContent(StreamLimiter streamLimiter, LanguageEnum lang) throws IOException { RTFEditorKit rtf = new RTFEditorKit(); Document doc = rtf.createDefaultDocument(); try { ParserResultItem result = getNewParserResultItem(); rtf.read(streamLimiter.getNewInputStream(), doc, 0); result.addField(ParserFieldEnum.content, doc.getText(0, doc.getLength()).trim()); } catch (BadLocationException e) { throw new IOException(e); } }
/** * The paste method used for DnD and clipboard. */ @Override public boolean importData(JComponent c, Transferable t) { if (canImport(new TransferSupport(c, t))) { JTextComponent textField = (JTextComponent) c; String rtfText = getTextFromTransferable(t, TransferableRichText.RTF_FLAVOR); if (rtfText != null && !asTextOnly) { addRichtText(rtfText, textField, new RTFEditorKit()); return true; } String htmlText = getTextFromTransferable(t, TransferableRichText.HTML_FLAVOR); if (htmlText != null && !asTextOnly) { addRichtText(rtfText, textField, new HTMLEditorKit()); return true; } String plainText = getTextFromTransferable(t, DataFlavor.stringFlavor); if (plainText != null) { try { textField.getDocument().insertString(textField.getSelectionStart(), plainText, null); return true; } catch (BadLocationException ex) { Exceptions.printStackTrace(ex); } } ImageIcon image = getImageFromTransferable(t); if (image != null) { ((DocxDocument) textField.getDocument()).insertPicture(image, textField.getSelectionStart()); return true; } } return false; }
@Override public synchronized Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException { if (flavor.equals(DataFlavor.stringFlavor)) { if (cachedPlainText != null) { return cachedPlainText; } try { cachedPlainText = doc.getText(start, length); return cachedPlainText; } catch (BadLocationException ex) { Exceptions.printStackTrace(ex); return ""; } } else if (flavor.equals(RTF_FLAVOR)) { if (cachedRtfText != null) { return getTransferableText(cachedRtfText, flavor); } EditorKit rtfKit = new RTFEditorKit(); cachedRtfText = convertWithKit(rtfKit); return getTransferableText(cachedRtfText, flavor); } else if (flavor.equals(HTML_FLAVOR)) { if (cachedHtmlText != null) { return getTransferableText(cachedHtmlText, flavor); } EditorKit htmlKit = new HTMLEditorKit(); cachedHtmlText = convertWithKit(htmlKit); return getTransferableText(cachedHtmlText, flavor); } else { throw new UnsupportedFlavorException(flavor); } }
/** * Method for saving text as an RTF document */ public void writeOutRTF(StyledDocument doc, File rtfFile) throws IOException, BadLocationException { FileOutputStream fos = new FileOutputStream(rtfFile); RTFEditorKit rtfKit = new RTFEditorKit(); rtfKit.write(fos, doc, 0, doc.getLength()); fos.flush(); fos.close(); refreshOnUpdate(); }
public String getRTFDocument() throws IOException, BadLocationException { StyledDocument doc = (StyledDocument) (jtpMain.getStyledDocument()); StringWriter strwriter = new StringWriter(); RTFEditorKit rtfKit = new RTFEditorKit(); rtfKit.write(strwriter, doc, 0, doc.getLength()); return strwriter.toString(); }
public static String readFile(String url) { try { byte[] array = new byte[4096]; RTFEditorKit rtfParser = new RTFEditorKit(); Document document = rtfParser.createDefaultDocument(); rtfParser.read(new URL(url).openStream(), document, 0); return document.getText(0, document.getLength()); } catch (Exception e) { } return null; }
private void printEditorKit() { EditorKit ek = myEditorPane.getEditorKit(); if (ek instanceof RTFEditorKit) { System.out.println("RTFEditorKit"); } else if (ek instanceof HTMLEditorKit) { System.out.println("HTMLEditorKit"); } else if (ek instanceof StyledEditorKit) { System.out.println("StyledEditorKit"); } else if (ek instanceof DefaultEditorKit) { System.out.println("DefaultEditorKit"); } else { System.out.println("None"); } }
public String rtf2text(InputStream is) throws Exception { DefaultStyledDocument styledDoc = new DefaultStyledDocument(); new RTFEditorKit().read(is, styledDoc, 0); return styledDoc.getText(0, styledDoc.getLength()); }
/** * Extract text from the Rich text file document * @throws Exception * * @see edu.ur.ir.index.FileTextExtractor#getText(java.io.File) */ public String getText(File f) throws Exception { String text = null; // don't even try if the file is too large if( isFileTooLarge(f) || f.length() <= 0l) { return text; } DefaultStyledDocument styledDoc = new DefaultStyledDocument(); RTFEditorKit editorKit = new RTFEditorKit(); FileInputStream inputStream = null; try { inputStream = new FileInputStream(f); editorKit.read(inputStream, styledDoc, 0); String myText = styledDoc.getText(0, styledDoc.getLength()); if( myText != null && !myText.trim().equals("")) { text = myText; } } catch(OutOfMemoryError oome) { text = null; log.error("could not extract text", oome); throw(oome); } catch(Exception e) { text = null; log.error("could not get text for rich text document " + f.getAbsolutePath(), e); throw(e); } finally { closeInputStream(inputStream); editorKit = null; } return text; }
private LockFrameEditor(PswDialogEditor _dialog) { frame = this; dialog = _dialog; this.setIconImage( PswDialogView.getImage() ); this.addWindowListener(this);// for windowClosing JPanel contentPane = new JPanel(); contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.PAGE_AXIS)); this.setContentPane(contentPane); LockFrameEditorMenu menu = new LockFrameEditorMenu(); contentPane.add(menu); textPane = new JTextPane(); kit = new RTFEditorKit(); textPane.setEditorKit(kit); textPane.setEditable(true); textPane.setBackground(new Color(231, 231, 231) ); textPane.setDragEnabled(true); textPane.setToolTipText("CTRL + ... R (undo), W (redo), X (cut), C (copy), V (paste)"); textPane.setText("äöü"); // Cut-Copy-Paste.Menue: textPane.addMouseListener(this); // Undo/Redo: key and menu manager = new UndoManager(); UndoAction undoAction = new UndoAction(manager); RedoAction redoAction = new RedoAction(manager); textPane.getDocument().addUndoableEditListener(manager); //keyStroke: STRG + R, STRG + W textPane.registerKeyboardAction(undoAction, KeyStroke.getKeyStroke( KeyEvent.VK_R, InputEvent.CTRL_MASK), JComponent.WHEN_FOCUSED); textPane.registerKeyboardAction(redoAction, KeyStroke.getKeyStroke( KeyEvent.VK_W, InputEvent.CTRL_MASK), JComponent.WHEN_FOCUSED); JScrollPane editorScrollPane = new JScrollPane(textPane); //editorScrollPane.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); editorScrollPane.setPreferredSize(new Dimension(350, 250)); editorScrollPane.setMinimumSize(new Dimension(50, 30)); contentPane.add(editorScrollPane); this.setLocation(100, 100); this.setMinimumSize(new Dimension(450, 500)); }