1
24 package net.sf.jasperreports.engine.util;
25
26 import java.text.AttributedCharacterIterator.Attribute;
27 import java.util.ArrayList;
28 import java.util.HashMap;
29 import java.util.List;
30
31 import javax.swing.JEditorPane;
32 import javax.swing.text.BadLocationException;
33 import javax.swing.text.Document;
34 import javax.swing.text.Element;
35 import javax.swing.text.AbstractDocument.LeafElement;
36
37 import org.apache.commons.logging.Log;
38 import org.apache.commons.logging.LogFactory;
39
40
41
44 public class JEditorPaneRtfMarkupProcessor extends JEditorPaneMarkupProcessor
45 {
46 private static final Log log = LogFactory.getLog(JEditorPaneRtfMarkupProcessor.class);
47
48 private static JEditorPaneRtfMarkupProcessor instance;
49
50
53 public static JEditorPaneRtfMarkupProcessor getInstance()
54 {
55 if (instance == null)
56 {
57 instance = new JEditorPaneRtfMarkupProcessor();
58 }
59 return instance;
60 }
61
62 @Override
63 public String convert(String srcText)
64 {
65 JEditorPane editorPane = new JEditorPane("text/rtf", srcText);
66 editorPane.setEditable(false);
67
68 List<Element> elements = new ArrayList<Element>();
69
70 Document document = editorPane.getDocument();
71
72 Element root = document.getDefaultRootElement();
73 if (root != null)
74 {
75 addElements(elements, root);
76 }
77
78 String chunk = null;
79 Element element = null;
80 int startOffset = 0;
81 int endOffset = 0;
82
83 JRStyledText styledText = new JRStyledText();
84 styledText.setGlobalAttributes(new HashMap<Attribute,Object>());
85 for(int i = 0; i < elements.size(); i++)
86 {
87 if (chunk != null)
88 {
89 styledText.append(chunk);
90 styledText.addRun(new JRStyledText.Run(getAttributes(element.getAttributes()), startOffset, endOffset));
91 }
92
93 chunk = null;
94 element = elements.get(i);
95 startOffset = element.getStartOffset();
96 endOffset = element.getEndOffset();
97
98 try
99 {
100 chunk = document.getText(startOffset, endOffset - startOffset);
101 }
102 catch(BadLocationException e)
103 {
104 if (log.isDebugEnabled())
105 {
106 log.debug("Error converting markup.", e);
107 }
108 }
109
110 }
111
112 if (chunk != null && !"\n".equals(chunk))
113 {
114 styledText.append(chunk);
115 styledText.addRun(new JRStyledText.Run(getAttributes(element.getAttributes()), startOffset, endOffset));
116 }
117
118 return JRStyledTextParser.getInstance().write(styledText);
119 }
120
121
124 protected void addElements(List<Element> elements, Element element)
125 {
126 if(element instanceof LeafElement)
127 {
128 elements.add(element);
129 }
130 for(int i = 0; i < element.getElementCount(); i++)
131 {
132 Element child = element.getElement(i);
133 addElements(elements, child);
134 }
135 }
136
137 }
138