You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

RTFHandler.java 63KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778
  1. /*
  2. * Licensed to the Apache Software Foundation (ASF) under one or more
  3. * contributor license agreements. See the NOTICE file distributed with
  4. * this work for additional information regarding copyright ownership.
  5. * The ASF licenses this file to You under the Apache License, Version 2.0
  6. * (the "License"); you may not use this file except in compliance with
  7. * the License. You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. /* $Id$ */
  18. package org.apache.fop.render.rtf;
  19. // Java
  20. import java.awt.Dimension;
  21. import java.awt.Rectangle;
  22. import java.awt.geom.Point2D;
  23. import java.io.FileNotFoundException;
  24. import java.io.IOException;
  25. import java.io.InputStream;
  26. import java.io.OutputStream;
  27. import java.io.OutputStreamWriter;
  28. import java.util.Iterator;
  29. import java.util.Map;
  30. import org.w3c.dom.Document;
  31. import org.xml.sax.SAXException;
  32. import org.apache.commons.io.IOUtils;
  33. import org.apache.commons.logging.Log;
  34. import org.apache.commons.logging.LogFactory;
  35. import org.apache.xmlgraphics.image.loader.Image;
  36. import org.apache.xmlgraphics.image.loader.ImageException;
  37. import org.apache.xmlgraphics.image.loader.ImageFlavor;
  38. import org.apache.xmlgraphics.image.loader.ImageInfo;
  39. import org.apache.xmlgraphics.image.loader.ImageManager;
  40. import org.apache.xmlgraphics.image.loader.ImageSessionContext;
  41. import org.apache.xmlgraphics.image.loader.ImageSize;
  42. import org.apache.xmlgraphics.image.loader.impl.ImageRawStream;
  43. import org.apache.xmlgraphics.image.loader.impl.ImageXMLDOM;
  44. import org.apache.xmlgraphics.image.loader.util.ImageUtil;
  45. import org.apache.fop.ResourceEventProducer;
  46. import org.apache.fop.apps.FOPException;
  47. import org.apache.fop.apps.FOUserAgent;
  48. import org.apache.fop.datatypes.LengthBase;
  49. import org.apache.fop.datatypes.PercentBaseContext;
  50. import org.apache.fop.fo.Constants;
  51. import org.apache.fop.fo.FOEventHandler;
  52. import org.apache.fop.fo.FONode;
  53. import org.apache.fop.fo.FOText;
  54. import org.apache.fop.fo.FObj;
  55. import org.apache.fop.fo.XMLObj;
  56. import org.apache.fop.fo.flow.AbstractGraphics;
  57. import org.apache.fop.fo.flow.BasicLink;
  58. import org.apache.fop.fo.flow.Block;
  59. import org.apache.fop.fo.flow.BlockContainer;
  60. import org.apache.fop.fo.flow.Character;
  61. import org.apache.fop.fo.flow.ExternalGraphic;
  62. import org.apache.fop.fo.flow.Footnote;
  63. import org.apache.fop.fo.flow.FootnoteBody;
  64. import org.apache.fop.fo.flow.Inline;
  65. import org.apache.fop.fo.flow.InstreamForeignObject;
  66. import org.apache.fop.fo.flow.Leader;
  67. import org.apache.fop.fo.flow.ListBlock;
  68. import org.apache.fop.fo.flow.ListItem;
  69. import org.apache.fop.fo.flow.ListItemBody;
  70. import org.apache.fop.fo.flow.ListItemLabel;
  71. import org.apache.fop.fo.flow.PageNumber;
  72. import org.apache.fop.fo.flow.PageNumberCitation;
  73. import org.apache.fop.fo.flow.PageNumberCitationLast;
  74. import org.apache.fop.fo.flow.table.Table;
  75. import org.apache.fop.fo.flow.table.TableBody;
  76. import org.apache.fop.fo.flow.table.TableCell;
  77. import org.apache.fop.fo.flow.table.TableColumn;
  78. import org.apache.fop.fo.flow.table.TableFooter;
  79. import org.apache.fop.fo.flow.table.TableHeader;
  80. import org.apache.fop.fo.flow.table.TablePart;
  81. import org.apache.fop.fo.flow.table.TableRow;
  82. import org.apache.fop.fo.pagination.Flow;
  83. import org.apache.fop.fo.pagination.PageSequence;
  84. import org.apache.fop.fo.pagination.PageSequenceMaster;
  85. import org.apache.fop.fo.pagination.Region;
  86. import org.apache.fop.fo.pagination.SimplePageMaster;
  87. import org.apache.fop.fo.pagination.StaticContent;
  88. import org.apache.fop.fo.properties.CommonBorderPaddingBackground;
  89. import org.apache.fop.fo.properties.EnumLength;
  90. import org.apache.fop.fonts.FontSetup;
  91. import org.apache.fop.layoutmgr.inline.ImageLayout;
  92. import org.apache.fop.layoutmgr.table.ColumnSetup;
  93. import org.apache.fop.render.RendererEventProducer;
  94. import org.apache.fop.render.rtf.rtflib.exceptions.RtfException;
  95. import org.apache.fop.render.rtf.rtflib.rtfdoc.IRtfAfterContainer;
  96. import org.apache.fop.render.rtf.rtflib.rtfdoc.IRtfBeforeContainer;
  97. import org.apache.fop.render.rtf.rtflib.rtfdoc.IRtfListContainer;
  98. import org.apache.fop.render.rtf.rtflib.rtfdoc.IRtfTableContainer;
  99. import org.apache.fop.render.rtf.rtflib.rtfdoc.IRtfTextrunContainer;
  100. import org.apache.fop.render.rtf.rtflib.rtfdoc.ITableAttributes;
  101. import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfAfter;
  102. import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfAttributes;
  103. import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfBefore;
  104. import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfDocumentArea;
  105. import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfElement;
  106. import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfExternalGraphic;
  107. import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfFile;
  108. import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfFootnote;
  109. import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfHyperLink;
  110. import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfList;
  111. import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfListItem;
  112. import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfListItem.RtfListItemLabel;
  113. import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfPage;
  114. import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfParagraphBreak;
  115. import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfSection;
  116. import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfTable;
  117. import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfTableCell;
  118. import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfTableRow;
  119. import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfTextrun;
  120. import org.apache.fop.render.rtf.rtflib.tools.BuilderContext;
  121. import org.apache.fop.render.rtf.rtflib.tools.PercentContext;
  122. import org.apache.fop.render.rtf.rtflib.tools.TableContext;
  123. /**
  124. * RTF Handler: generates RTF output using the structure events from
  125. * the FO Tree sent to this structure handler.
  126. */
  127. public class RTFHandler extends FOEventHandler {
  128. private RtfFile rtfFile;
  129. private final OutputStream os;
  130. private static Log log = LogFactory.getLog(RTFHandler.class);
  131. private RtfSection sect;
  132. private RtfDocumentArea docArea;
  133. private boolean bDefer; //true, if each called handler shall be
  134. //processed at later time.
  135. private boolean bPrevHeaderSpecified = false; //true, if there has been a
  136. //header in any page-sequence
  137. private boolean bPrevFooterSpecified = false; //true, if there has been a
  138. //footer in any page-sequence
  139. private boolean bHeaderSpecified = false; //true, if there is a header
  140. //in current page-sequence
  141. private boolean bFooterSpecified = false; //true, if there is a footer
  142. //in current page-sequence
  143. private BuilderContext builderContext = new BuilderContext(null);
  144. private SimplePageMaster pagemaster;
  145. private int nestedTableDepth = 1;
  146. private PercentContext percentManager = new PercentContext();
  147. /**
  148. * Creates a new RTF structure handler.
  149. * @param userAgent the FOUserAgent for this process
  150. * @param os OutputStream to write to
  151. */
  152. public RTFHandler(FOUserAgent userAgent, OutputStream os) {
  153. super(userAgent);
  154. this.os = os;
  155. bDefer = true;
  156. boolean base14Kerning = false;
  157. FontSetup.setup(fontInfo, null, userAgent.getResourceResolver(), base14Kerning);
  158. }
  159. /**
  160. * Central exception handler for I/O exceptions.
  161. * @param ioe IOException to handle
  162. */
  163. protected void handleIOTrouble(IOException ioe) {
  164. RendererEventProducer eventProducer = RendererEventProducer.Provider.get(
  165. getUserAgent().getEventBroadcaster());
  166. eventProducer.ioError(this, ioe);
  167. }
  168. /** {@inheritDoc} */
  169. public void startDocument() throws SAXException {
  170. // TODO sections should be created
  171. try {
  172. rtfFile = new RtfFile(new OutputStreamWriter(os));
  173. docArea = rtfFile.startDocumentArea();
  174. } catch (IOException ioe) {
  175. // TODO could we throw Exception in all FOEventHandler events?
  176. throw new SAXException(ioe);
  177. }
  178. }
  179. /** {@inheritDoc} */
  180. public void endDocument() throws SAXException {
  181. try {
  182. rtfFile.flush();
  183. } catch (IOException ioe) {
  184. // TODO could we throw Exception in all FOEventHandler events?
  185. throw new SAXException(ioe);
  186. }
  187. }
  188. /** {@inheritDoc} */
  189. public void startPageSequence(PageSequence pageSeq) {
  190. try {
  191. //This is needed for region handling
  192. if (this.pagemaster == null) {
  193. String reference = pageSeq.getMasterReference();
  194. this.pagemaster
  195. = pageSeq.getRoot().getLayoutMasterSet().getSimplePageMaster(reference);
  196. if (this.pagemaster == null) {
  197. RTFEventProducer eventProducer = RTFEventProducer.Provider.get(
  198. getUserAgent().getEventBroadcaster());
  199. eventProducer.onlySPMSupported(this, reference, pageSeq.getLocator());
  200. PageSequenceMaster master
  201. = pageSeq.getRoot().getLayoutMasterSet().getPageSequenceMaster(reference);
  202. this.pagemaster = master.getNextSimplePageMaster(
  203. false, false, false, false, pageSeq.getMainFlow().getFlowName());
  204. }
  205. }
  206. if (bDefer) {
  207. return;
  208. }
  209. sect = docArea.newSection();
  210. //read page size and margins, if specified
  211. //only simple-page-master supported, so pagemaster may be null
  212. if (pagemaster != null) {
  213. sect.getRtfAttributes().set(
  214. PageAttributesConverter.convertPageAttributes(
  215. pagemaster));
  216. } else {
  217. RTFEventProducer eventProducer = RTFEventProducer.Provider.get(
  218. getUserAgent().getEventBroadcaster());
  219. eventProducer.noSPMFound(this, pageSeq.getLocator());
  220. }
  221. builderContext.pushContainer(sect);
  222. //Calculate usable page width for this flow
  223. int useAblePageWidth = pagemaster.getPageWidth().getValue()
  224. - pagemaster.getCommonMarginBlock().marginLeft.getValue()
  225. - pagemaster.getCommonMarginBlock().marginRight.getValue()
  226. - sect.getRtfAttributes().getValueAsInteger(RtfPage.MARGIN_LEFT).intValue()
  227. - sect.getRtfAttributes().getValueAsInteger(RtfPage.MARGIN_RIGHT).intValue();
  228. percentManager.setDimension(pageSeq, useAblePageWidth);
  229. bHeaderSpecified = false;
  230. bFooterSpecified = false;
  231. } catch (IOException ioe) {
  232. handleIOTrouble(ioe);
  233. }
  234. }
  235. /** {@inheritDoc} */
  236. public void endPageSequence(PageSequence pageSeq) {
  237. if (bDefer) {
  238. //If endBlock was called while SAX parsing, and the passed FO is Block
  239. //nested within another Block, stop deferring.
  240. //Now process all deferred FOs.
  241. bDefer = false;
  242. recurseFONode(pageSeq);
  243. this.pagemaster = null;
  244. bDefer = true;
  245. return;
  246. } else {
  247. builderContext.popContainer();
  248. this.pagemaster = null;
  249. }
  250. }
  251. /** {@inheritDoc} */
  252. public void startFlow(Flow fl) {
  253. if (bDefer) {
  254. return;
  255. }
  256. try {
  257. log.debug("starting flow: " + fl.getFlowName());
  258. boolean handled = false;
  259. Region regionBody = pagemaster.getRegion(Constants.FO_REGION_BODY);
  260. Region regionBefore = pagemaster.getRegion(Constants.FO_REGION_BEFORE);
  261. Region regionAfter = pagemaster.getRegion(Constants.FO_REGION_AFTER);
  262. if (fl.getFlowName().equals(regionBody.getRegionName())) {
  263. // if there is no header in current page-sequence but there has been
  264. // a header in a previous page-sequence, insert an empty header.
  265. if (bPrevHeaderSpecified && !bHeaderSpecified) {
  266. RtfAttributes attr = new RtfAttributes();
  267. attr.set(RtfBefore.HEADER);
  268. final IRtfBeforeContainer contBefore
  269. = (IRtfBeforeContainer)builderContext.getContainer
  270. (IRtfBeforeContainer.class, true, this);
  271. contBefore.newBefore(attr);
  272. }
  273. // if there is no footer in current page-sequence but there has been
  274. // a footer in a previous page-sequence, insert an empty footer.
  275. if (bPrevFooterSpecified && !bFooterSpecified) {
  276. RtfAttributes attr = new RtfAttributes();
  277. attr.set(RtfAfter.FOOTER);
  278. final IRtfAfterContainer contAfter
  279. = (IRtfAfterContainer)builderContext.getContainer
  280. (IRtfAfterContainer.class, true, this);
  281. contAfter.newAfter(attr);
  282. }
  283. handled = true;
  284. } else if (regionBefore != null
  285. && fl.getFlowName().equals(regionBefore.getRegionName())) {
  286. bHeaderSpecified = true;
  287. bPrevHeaderSpecified = true;
  288. final IRtfBeforeContainer c
  289. = (IRtfBeforeContainer)builderContext.getContainer(
  290. IRtfBeforeContainer.class,
  291. true, this);
  292. RtfAttributes beforeAttributes = ((RtfElement)c).getRtfAttributes();
  293. if (beforeAttributes == null) {
  294. beforeAttributes = new RtfAttributes();
  295. }
  296. beforeAttributes.set(RtfBefore.HEADER);
  297. RtfBefore before = c.newBefore(beforeAttributes);
  298. builderContext.pushContainer(before);
  299. handled = true;
  300. } else if (regionAfter != null
  301. && fl.getFlowName().equals(regionAfter.getRegionName())) {
  302. bFooterSpecified = true;
  303. bPrevFooterSpecified = true;
  304. final IRtfAfterContainer c
  305. = (IRtfAfterContainer)builderContext.getContainer(
  306. IRtfAfterContainer.class,
  307. true, this);
  308. RtfAttributes afterAttributes = ((RtfElement)c).getRtfAttributes();
  309. if (afterAttributes == null) {
  310. afterAttributes = new RtfAttributes();
  311. }
  312. afterAttributes.set(RtfAfter.FOOTER);
  313. RtfAfter after = c.newAfter(afterAttributes);
  314. builderContext.pushContainer(after);
  315. handled = true;
  316. }
  317. if (!handled) {
  318. log.warn("A " + fl.getLocalName() + " has been skipped: " + fl.getFlowName());
  319. }
  320. } catch (IOException ioe) {
  321. handleIOTrouble(ioe);
  322. } catch (Exception e) {
  323. log.error("startFlow: " + e.getMessage());
  324. throw new RuntimeException(e.getMessage());
  325. }
  326. }
  327. /** {@inheritDoc} */
  328. public void endFlow(Flow fl) {
  329. if (bDefer) {
  330. return;
  331. }
  332. try {
  333. Region regionBody = pagemaster.getRegion(Constants.FO_REGION_BODY);
  334. Region regionBefore = pagemaster.getRegion(Constants.FO_REGION_BEFORE);
  335. Region regionAfter = pagemaster.getRegion(Constants.FO_REGION_AFTER);
  336. if (fl.getFlowName().equals(regionBody.getRegionName())) {
  337. //just do nothing
  338. } else if (regionBefore != null
  339. && fl.getFlowName().equals(regionBefore.getRegionName())) {
  340. builderContext.popContainer();
  341. } else if (regionAfter != null
  342. && fl.getFlowName().equals(regionAfter.getRegionName())) {
  343. builderContext.popContainer();
  344. }
  345. } catch (Exception e) {
  346. log.error("endFlow: " + e.getMessage());
  347. throw new RuntimeException(e.getMessage());
  348. }
  349. }
  350. /** {@inheritDoc} */
  351. public void startBlock(Block bl) {
  352. if (bDefer) {
  353. return;
  354. }
  355. try {
  356. RtfAttributes rtfAttr
  357. = TextAttributesConverter.convertAttributes(bl);
  358. IRtfTextrunContainer container
  359. = (IRtfTextrunContainer)builderContext.getContainer(
  360. IRtfTextrunContainer.class,
  361. true, this);
  362. RtfTextrun textrun = container.getTextrun();
  363. textrun.addParagraphBreak();
  364. textrun.pushBlockAttributes(rtfAttr);
  365. textrun.addBookmark(bl.getId());
  366. } catch (IOException ioe) {
  367. handleIOTrouble(ioe);
  368. } catch (Exception e) {
  369. log.error("startBlock: " + e.getMessage());
  370. throw new RuntimeException("Exception: " + e);
  371. }
  372. }
  373. /** {@inheritDoc} */
  374. public void endBlock(Block bl) {
  375. if (bDefer) {
  376. return;
  377. }
  378. try {
  379. IRtfTextrunContainer container
  380. = (IRtfTextrunContainer)builderContext.getContainer(
  381. IRtfTextrunContainer.class,
  382. true, this);
  383. RtfTextrun textrun = container.getTextrun();
  384. RtfParagraphBreak par = textrun.addParagraphBreak();
  385. RtfTableCell cellParent = (RtfTableCell)textrun.getParentOfClass(RtfTableCell.class);
  386. if (cellParent != null && par != null) {
  387. int iDepth = cellParent.findChildren(textrun);
  388. cellParent.setLastParagraph(par, iDepth);
  389. }
  390. int breakValue = toRtfBreakValue(bl.getBreakAfter());
  391. textrun.popBlockAttributes(breakValue);
  392. } catch (IOException ioe) {
  393. handleIOTrouble(ioe);
  394. } catch (Exception e) {
  395. log.error("startBlock:" + e.getMessage());
  396. throw new RuntimeException(e.getMessage());
  397. }
  398. }
  399. /** {@inheritDoc} */
  400. public void startBlockContainer(BlockContainer blc) {
  401. if (bDefer) {
  402. return;
  403. }
  404. try {
  405. RtfAttributes rtfAttr
  406. = TextAttributesConverter.convertBlockContainerAttributes(blc);
  407. IRtfTextrunContainer container
  408. = (IRtfTextrunContainer)builderContext.getContainer(
  409. IRtfTextrunContainer.class,
  410. true, this);
  411. RtfTextrun textrun = container.getTextrun();
  412. textrun.addParagraphBreak();
  413. textrun.pushBlockAttributes(rtfAttr);
  414. } catch (IOException ioe) {
  415. handleIOTrouble(ioe);
  416. } catch (Exception e) {
  417. log.error("startBlock: " + e.getMessage());
  418. throw new RuntimeException("Exception: " + e);
  419. }
  420. }
  421. /** {@inheritDoc} */
  422. public void endBlockContainer(BlockContainer bl) {
  423. if (bDefer) {
  424. return;
  425. }
  426. try {
  427. IRtfTextrunContainer container
  428. = (IRtfTextrunContainer)builderContext.getContainer(
  429. IRtfTextrunContainer.class,
  430. true, this);
  431. RtfTextrun textrun = container.getTextrun();
  432. textrun.addParagraphBreak();
  433. int breakValue = toRtfBreakValue(bl.getBreakAfter());
  434. textrun.popBlockAttributes(breakValue);
  435. } catch (IOException ioe) {
  436. handleIOTrouble(ioe);
  437. } catch (Exception e) {
  438. log.error("startBlock:" + e.getMessage());
  439. throw new RuntimeException(e.getMessage());
  440. }
  441. }
  442. private int toRtfBreakValue(int foBreakValue) {
  443. switch (foBreakValue) {
  444. case Constants.EN_PAGE:
  445. return RtfTextrun.BREAK_PAGE;
  446. case Constants.EN_EVEN_PAGE:
  447. return RtfTextrun.BREAK_EVEN_PAGE;
  448. case Constants.EN_ODD_PAGE:
  449. return RtfTextrun.BREAK_ODD_PAGE;
  450. case Constants.EN_COLUMN:
  451. return RtfTextrun.BREAK_COLUMN;
  452. default:
  453. return RtfTextrun.BREAK_NONE;
  454. }
  455. }
  456. /** {@inheritDoc} */
  457. public void startTable(Table tbl) {
  458. if (bDefer) {
  459. return;
  460. }
  461. // create an RtfTable in the current table container
  462. TableContext tableContext = new TableContext(builderContext);
  463. try {
  464. final IRtfTableContainer tc
  465. = (IRtfTableContainer)builderContext.getContainer(
  466. IRtfTableContainer.class, true, null);
  467. RtfAttributes atts
  468. = TableAttributesConverter.convertTableAttributes(tbl);
  469. RtfTable table = tc.newTable(atts, tableContext);
  470. table.setNestedTableDepth(nestedTableDepth);
  471. nestedTableDepth++;
  472. CommonBorderPaddingBackground border = tbl.getCommonBorderPaddingBackground();
  473. RtfAttributes borderAttributes = new RtfAttributes();
  474. BorderAttributesConverter.makeBorder(border, CommonBorderPaddingBackground.BEFORE,
  475. borderAttributes, ITableAttributes.CELL_BORDER_TOP);
  476. BorderAttributesConverter.makeBorder(border, CommonBorderPaddingBackground.AFTER,
  477. borderAttributes, ITableAttributes.CELL_BORDER_BOTTOM);
  478. BorderAttributesConverter.makeBorder(border, CommonBorderPaddingBackground.START,
  479. borderAttributes, ITableAttributes.CELL_BORDER_LEFT);
  480. BorderAttributesConverter.makeBorder(border, CommonBorderPaddingBackground.END,
  481. borderAttributes, ITableAttributes.CELL_BORDER_RIGHT);
  482. table.setBorderAttributes(borderAttributes);
  483. builderContext.pushContainer(table);
  484. } catch (IOException ioe) {
  485. handleIOTrouble(ioe);
  486. } catch (Exception e) {
  487. log.error("startTable:" + e.getMessage());
  488. throw new RuntimeException(e.getMessage());
  489. }
  490. builderContext.pushTableContext(tableContext);
  491. }
  492. /** {@inheritDoc} */
  493. public void endTable(Table tbl) {
  494. if (bDefer) {
  495. return;
  496. }
  497. nestedTableDepth--;
  498. builderContext.popTableContext();
  499. builderContext.popContainer();
  500. }
  501. /** {@inheritDoc} */
  502. public void startColumn(TableColumn tc) {
  503. if (bDefer) {
  504. return;
  505. }
  506. try {
  507. int iWidth = tc.getColumnWidth().getValue(percentManager);
  508. percentManager.setDimension(tc, iWidth);
  509. //convert to twips
  510. Float width = new Float(FoUnitsConverter.getInstance().convertMptToTwips(iWidth));
  511. builderContext.getTableContext().setNextColumnWidth(width);
  512. builderContext.getTableContext().setNextColumnRowSpanning(
  513. new Integer(0), null);
  514. builderContext.getTableContext().setNextFirstSpanningCol(false);
  515. } catch (Exception e) {
  516. log.error("startColumn: " + e.getMessage());
  517. throw new RuntimeException(e.getMessage());
  518. }
  519. }
  520. /** {@inheritDoc} */
  521. public void endColumn(TableColumn tc) {
  522. if (bDefer) {
  523. return;
  524. }
  525. }
  526. /** {@inheritDoc} */
  527. public void startHeader(TableHeader header) {
  528. startPart(header);
  529. }
  530. /** {@inheritDoc} */
  531. public void endHeader(TableHeader header) {
  532. endPart(header);
  533. }
  534. /** {@inheritDoc} */
  535. public void startFooter(TableFooter footer) {
  536. startPart(footer);
  537. }
  538. /** {@inheritDoc} */
  539. public void endFooter(TableFooter footer) {
  540. endPart(footer);
  541. }
  542. /** {@inheritDoc} */
  543. public void startInline(Inline inl) {
  544. if (bDefer) {
  545. return;
  546. }
  547. try {
  548. RtfAttributes rtfAttr
  549. = TextAttributesConverter.convertCharacterAttributes(inl);
  550. IRtfTextrunContainer container
  551. = (IRtfTextrunContainer)builderContext.getContainer(
  552. IRtfTextrunContainer.class, true, this);
  553. RtfTextrun textrun = container.getTextrun();
  554. textrun.pushInlineAttributes(rtfAttr);
  555. textrun.addBookmark(inl.getId());
  556. } catch (IOException ioe) {
  557. handleIOTrouble(ioe);
  558. } catch (FOPException fe) {
  559. log.error("startInline:" + fe.getMessage());
  560. throw new RuntimeException(fe.getMessage());
  561. } catch (Exception e) {
  562. log.error("startInline:" + e.getMessage());
  563. throw new RuntimeException(e.getMessage());
  564. }
  565. }
  566. /** {@inheritDoc} */
  567. public void endInline(Inline inl) {
  568. if (bDefer) {
  569. return;
  570. }
  571. try {
  572. IRtfTextrunContainer container
  573. = (IRtfTextrunContainer)builderContext.getContainer(
  574. IRtfTextrunContainer.class, true, this);
  575. RtfTextrun textrun = container.getTextrun();
  576. textrun.popInlineAttributes();
  577. } catch (IOException ioe) {
  578. handleIOTrouble(ioe);
  579. } catch (Exception e) {
  580. log.error("startInline:" + e.getMessage());
  581. throw new RuntimeException(e.getMessage());
  582. }
  583. }
  584. private void startPart(TablePart part) {
  585. if (bDefer) {
  586. return;
  587. }
  588. try {
  589. RtfAttributes atts = TableAttributesConverter.convertTablePartAttributes(part);
  590. RtfTable tbl = (RtfTable)builderContext.getContainer(RtfTable.class, true, this);
  591. tbl.setHeaderAttribs(atts);
  592. } catch (IOException ioe) {
  593. handleIOTrouble(ioe);
  594. } catch (Exception e) {
  595. log.error("startPart: " + e.getMessage());
  596. throw new RuntimeException(e.getMessage());
  597. }
  598. }
  599. private void endPart(TablePart tb) {
  600. if (bDefer) {
  601. return;
  602. }
  603. try {
  604. RtfTable tbl = (RtfTable)builderContext.getContainer(RtfTable.class, true, this);
  605. tbl.setHeaderAttribs(null);
  606. } catch (IOException ioe) {
  607. handleIOTrouble(ioe);
  608. } catch (Exception e) {
  609. log.error("endPart: " + e.getMessage());
  610. throw new RuntimeException(e.getMessage());
  611. }
  612. }
  613. /**
  614. * {@inheritDoc}
  615. */
  616. public void startBody(TableBody body) {
  617. startPart(body);
  618. }
  619. /** {@inheritDoc} */
  620. public void endBody(TableBody body) {
  621. endPart(body);
  622. }
  623. /**
  624. * {@inheritDoc}
  625. */
  626. public void startRow(TableRow tr) {
  627. if (bDefer) {
  628. return;
  629. }
  630. try {
  631. // create an RtfTableRow in the current RtfTable
  632. final RtfTable tbl = (RtfTable)builderContext.getContainer(RtfTable.class,
  633. true, null);
  634. RtfAttributes atts = TableAttributesConverter.convertRowAttributes(tr,
  635. tbl.getHeaderAttribs());
  636. if (tr.getParent() instanceof TableHeader) {
  637. atts.set(ITableAttributes.ATTR_HEADER);
  638. }
  639. builderContext.pushContainer(tbl.newTableRow(atts));
  640. // reset column iteration index to correctly access column widths
  641. builderContext.getTableContext().selectFirstColumn();
  642. } catch (IOException ioe) {
  643. handleIOTrouble(ioe);
  644. } catch (Exception e) {
  645. log.error("startRow: " + e.getMessage());
  646. throw new RuntimeException(e.getMessage());
  647. }
  648. }
  649. /** {@inheritDoc} */
  650. public void endRow(TableRow tr) {
  651. if (bDefer) {
  652. return;
  653. }
  654. try {
  655. TableContext tctx = builderContext.getTableContext();
  656. final RtfTableRow row = (RtfTableRow)builderContext.getContainer(RtfTableRow.class,
  657. true, null);
  658. //while the current column is in row-spanning, act as if
  659. //a vertical merged cell would have been specified.
  660. while (tctx.getNumberOfColumns() > tctx.getColumnIndex()
  661. && tctx.getColumnRowSpanningNumber().intValue() > 0) {
  662. RtfTableCell vCell = row.newTableCellMergedVertically(
  663. (int)tctx.getColumnWidth(),
  664. tctx.getColumnRowSpanningAttrs());
  665. if (!tctx.getFirstSpanningCol()) {
  666. vCell.setHMerge(RtfTableCell.MERGE_WITH_PREVIOUS);
  667. }
  668. tctx.selectNextColumn();
  669. }
  670. } catch (IOException ioe) {
  671. handleIOTrouble(ioe);
  672. } catch (Exception e) {
  673. log.error("endRow: " + e.getMessage());
  674. throw new RuntimeException(e.getMessage());
  675. }
  676. builderContext.popContainer();
  677. builderContext.getTableContext().decreaseRowSpannings();
  678. }
  679. /** {@inheritDoc} */
  680. public void startCell(TableCell tc) {
  681. if (bDefer) {
  682. return;
  683. }
  684. try {
  685. TableContext tctx = builderContext.getTableContext();
  686. final RtfTableRow row = (RtfTableRow)builderContext.getContainer(RtfTableRow.class,
  687. true, null);
  688. int numberRowsSpanned = tc.getNumberRowsSpanned();
  689. int numberColumnsSpanned = tc.getNumberColumnsSpanned();
  690. //while the current column is in row-spanning, act as if
  691. //a vertical merged cell would have been specified.
  692. while (tctx.getNumberOfColumns() > tctx.getColumnIndex()
  693. && tctx.getColumnRowSpanningNumber().intValue() > 0) {
  694. RtfTableCell vCell = row.newTableCellMergedVertically(
  695. (int)tctx.getColumnWidth(),
  696. tctx.getColumnRowSpanningAttrs());
  697. if (!tctx.getFirstSpanningCol()) {
  698. vCell.setHMerge(RtfTableCell.MERGE_WITH_PREVIOUS);
  699. }
  700. tctx.selectNextColumn();
  701. }
  702. //get the width of the currently started cell
  703. float width = tctx.getColumnWidth();
  704. // create an RtfTableCell in the current RtfTableRow
  705. RtfAttributes atts = TableAttributesConverter.convertCellAttributes(tc);
  706. RtfTableCell cell = row.newTableCell((int)width, atts);
  707. //process number-rows-spanned attribute
  708. if (numberRowsSpanned > 1) {
  709. // Start vertical merge
  710. cell.setVMerge(RtfTableCell.MERGE_START);
  711. // set the number of rows spanned
  712. tctx.setCurrentColumnRowSpanning(new Integer(numberRowsSpanned),
  713. cell.getRtfAttributes());
  714. } else {
  715. tctx.setCurrentColumnRowSpanning(
  716. new Integer(numberRowsSpanned), null);
  717. }
  718. //process number-columns-spanned attribute
  719. if (numberColumnsSpanned > 0) {
  720. // Get the number of columns spanned
  721. tctx.setCurrentFirstSpanningCol(true);
  722. // We widthdraw one cell because the first cell is already created
  723. // (it's the current cell) !
  724. for (int i = 0; i < numberColumnsSpanned - 1; ++i) {
  725. tctx.selectNextColumn();
  726. //aggregate width for further elements
  727. width += tctx.getColumnWidth();
  728. tctx.setCurrentFirstSpanningCol(false);
  729. RtfTableCell hCell = row.newTableCellMergedHorizontally(
  730. 0, null);
  731. if (numberRowsSpanned > 1) {
  732. // Start vertical merge
  733. hCell.setVMerge(RtfTableCell.MERGE_START);
  734. // set the number of rows spanned
  735. tctx.setCurrentColumnRowSpanning(
  736. new Integer(numberRowsSpanned),
  737. cell.getRtfAttributes());
  738. } else {
  739. tctx.setCurrentColumnRowSpanning(
  740. new Integer(numberRowsSpanned), cell.getRtfAttributes());
  741. }
  742. }
  743. }
  744. //save width of the cell, convert from twips to mpt
  745. percentManager.setDimension(tc, (int)width * 50);
  746. builderContext.pushContainer(cell);
  747. } catch (IOException ioe) {
  748. handleIOTrouble(ioe);
  749. } catch (Exception e) {
  750. log.error("startCell: " + e.getMessage());
  751. throw new RuntimeException(e.getMessage());
  752. }
  753. }
  754. /** {@inheritDoc} */
  755. public void endCell(TableCell tc) {
  756. if (bDefer) {
  757. return;
  758. }
  759. try {
  760. RtfTableCell cell = (RtfTableCell)builderContext.getContainer(RtfTableCell.class, false, this);
  761. cell.finish();
  762. } catch (Exception e) {
  763. log.error("endCell: " + e.getMessage());
  764. throw new RuntimeException(e.getMessage());
  765. }
  766. builderContext.popContainer();
  767. builderContext.getTableContext().selectNextColumn();
  768. }
  769. // Lists
  770. /** {@inheritDoc} */
  771. public void startList(ListBlock lb) {
  772. if (bDefer) {
  773. return;
  774. }
  775. try {
  776. // create an RtfList in the current list container
  777. final IRtfListContainer c
  778. = (IRtfListContainer)builderContext.getContainer(
  779. IRtfListContainer.class, true, this);
  780. final RtfList newList = c.newList(
  781. ListAttributesConverter.convertAttributes(lb));
  782. builderContext.pushContainer(newList);
  783. } catch (IOException ioe) {
  784. handleIOTrouble(ioe);
  785. } catch (FOPException fe) {
  786. log.error("startList: " + fe.getMessage());
  787. throw new RuntimeException(fe.getMessage());
  788. } catch (Exception e) {
  789. log.error("startList: " + e.getMessage());
  790. throw new RuntimeException(e.getMessage());
  791. }
  792. }
  793. /** {@inheritDoc} */
  794. public void endList(ListBlock lb) {
  795. if (bDefer) {
  796. return;
  797. }
  798. builderContext.popContainer();
  799. }
  800. /** {@inheritDoc} */
  801. public void startListItem(ListItem li) {
  802. if (bDefer) {
  803. return;
  804. }
  805. // create an RtfListItem in the current RtfList
  806. try {
  807. RtfList list = (RtfList)builderContext.getContainer(
  808. RtfList.class, true, this);
  809. /**
  810. * If the current list already contains a list item, then close the
  811. * list and open a new one, so every single list item gets its own
  812. * list. This allows every item to have a different list label.
  813. * If all the items would be in the same list, they had all the
  814. * same label.
  815. */
  816. //TODO: do this only, if the labels content <> previous labels content
  817. if (list.getChildCount() > 0) {
  818. this.endListBody(null);
  819. this.endList((ListBlock) li.getParent());
  820. this.startList((ListBlock) li.getParent());
  821. this.startListBody(null);
  822. list = (RtfList)builderContext.getContainer(
  823. RtfList.class, true, this);
  824. }
  825. builderContext.pushContainer(list.newListItem());
  826. } catch (IOException ioe) {
  827. handleIOTrouble(ioe);
  828. } catch (Exception e) {
  829. log.error("startList: " + e.getMessage());
  830. throw new RuntimeException(e.getMessage());
  831. }
  832. }
  833. /** {@inheritDoc} */
  834. public void endListItem(ListItem li) {
  835. if (bDefer) {
  836. return;
  837. }
  838. builderContext.popContainer();
  839. }
  840. /** {@inheritDoc} */
  841. public void startListLabel(ListItemLabel listItemLabel) {
  842. if (bDefer) {
  843. return;
  844. }
  845. try {
  846. RtfListItem item
  847. = (RtfListItem)builderContext.getContainer(RtfListItem.class, true, this);
  848. RtfListItemLabel label = item.new RtfListItemLabel(item);
  849. builderContext.pushContainer(label);
  850. } catch (IOException ioe) {
  851. handleIOTrouble(ioe);
  852. } catch (Exception e) {
  853. log.error("startPageNumber: " + e.getMessage());
  854. throw new RuntimeException(e.getMessage());
  855. }
  856. }
  857. /** {@inheritDoc} */
  858. public void endListLabel(ListItemLabel listItemLabel) {
  859. if (bDefer) {
  860. return;
  861. }
  862. builderContext.popContainer();
  863. }
  864. /** {@inheritDoc} */
  865. public void startListBody(ListItemBody listItemBody) {
  866. }
  867. /** {@inheritDoc} */
  868. public void endListBody(ListItemBody listItemBody) {
  869. }
  870. // Static Regions
  871. /** {@inheritDoc} */
  872. public void startStatic(StaticContent staticContent) {
  873. }
  874. /** {@inheritDoc} */
  875. public void endStatic(StaticContent statisContent) {
  876. }
  877. /** {@inheritDoc} */
  878. public void startMarkup() {
  879. }
  880. /** {@inheritDoc} */
  881. public void endMarkup() {
  882. }
  883. /** {@inheritDoc} */
  884. public void startLink(BasicLink basicLink) {
  885. if (bDefer) {
  886. return;
  887. }
  888. try {
  889. IRtfTextrunContainer container
  890. = (IRtfTextrunContainer)builderContext.getContainer(
  891. IRtfTextrunContainer.class, true, this);
  892. RtfTextrun textrun = container.getTextrun();
  893. RtfHyperLink link = textrun.addHyperlink(new RtfAttributes());
  894. if (basicLink.hasExternalDestination()) {
  895. link.setExternalURL(basicLink.getExternalDestination());
  896. } else {
  897. link.setInternalURL(basicLink.getInternalDestination());
  898. }
  899. builderContext.pushContainer(link);
  900. } catch (IOException ioe) {
  901. handleIOTrouble(ioe);
  902. } catch (Exception e) {
  903. log.error("startLink: " + e.getMessage());
  904. throw new RuntimeException(e.getMessage());
  905. }
  906. }
  907. /** {@inheritDoc} */
  908. public void endLink(BasicLink basicLink) {
  909. if (bDefer) {
  910. return;
  911. }
  912. builderContext.popContainer();
  913. }
  914. /** {@inheritDoc} */
  915. public void image(ExternalGraphic eg) {
  916. if (bDefer) {
  917. return;
  918. }
  919. String uri = eg.getURL();
  920. ImageInfo info = null;
  921. try {
  922. //set image data
  923. FOUserAgent userAgent = eg.getUserAgent();
  924. ImageManager manager = userAgent.getImageManager();
  925. info = manager.getImageInfo(uri, userAgent.getImageSessionContext());
  926. putGraphic(eg, info);
  927. } catch (ImageException ie) {
  928. ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get(
  929. getUserAgent().getEventBroadcaster());
  930. eventProducer.imageError(this, (info != null ? info.toString() : uri), ie, null);
  931. } catch (FileNotFoundException fe) {
  932. ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get(
  933. getUserAgent().getEventBroadcaster());
  934. eventProducer.imageNotFound(this, (info != null ? info.toString() : uri), fe, null);
  935. } catch (IOException ioe) {
  936. ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get(
  937. getUserAgent().getEventBroadcaster());
  938. eventProducer.imageIOError(this, (info != null ? info.toString() : uri), ioe, null);
  939. }
  940. }
  941. /** {@inheritDoc} */
  942. public void endInstreamForeignObject(InstreamForeignObject ifo) {
  943. if (bDefer) {
  944. return;
  945. }
  946. try {
  947. XMLObj child = ifo.getChildXMLObj();
  948. Document doc = child.getDOMDocument();
  949. String ns = child.getNamespaceURI();
  950. ImageInfo info = new ImageInfo(null, null);
  951. // Set the resolution to that of the FOUserAgent
  952. FOUserAgent ua = ifo.getUserAgent();
  953. ImageSize size = new ImageSize();
  954. size.setResolution(ua.getSourceResolution());
  955. // Set the image size to the size of the svg.
  956. Point2D csize = new Point2D.Float(-1, -1);
  957. Point2D intrinsicDimensions = child.getDimension(csize);
  958. if (intrinsicDimensions == null) {
  959. ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get(
  960. getUserAgent().getEventBroadcaster());
  961. eventProducer.ifoNoIntrinsicSize(this, child.getLocator());
  962. return;
  963. }
  964. size.setSizeInMillipoints(
  965. (int)Math.round(intrinsicDimensions.getX() * 1000),
  966. (int)Math.round(intrinsicDimensions.getY() * 1000));
  967. size.calcPixelsFromSize();
  968. info.setSize(size);
  969. ImageXMLDOM image = new ImageXMLDOM(info, doc, ns);
  970. FOUserAgent userAgent = ifo.getUserAgent();
  971. ImageManager manager = userAgent.getImageManager();
  972. Map hints = ImageUtil.getDefaultHints(ua.getImageSessionContext());
  973. Image converted = manager.convertImage(image, FLAVORS, hints);
  974. putGraphic(ifo, converted);
  975. } catch (ImageException ie) {
  976. ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get(
  977. getUserAgent().getEventBroadcaster());
  978. eventProducer.imageError(this, null, ie, null);
  979. } catch (IOException ioe) {
  980. ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get(
  981. getUserAgent().getEventBroadcaster());
  982. eventProducer.imageIOError(this, null, ioe, null);
  983. }
  984. }
  985. private static final ImageFlavor[] FLAVORS = new ImageFlavor[] {
  986. ImageFlavor.RAW_EMF, ImageFlavor.RAW_PNG, ImageFlavor.RAW_JPEG
  987. };
  988. /**
  989. * Puts a graphic/image into the generated RTF file.
  990. * @param abstractGraphic the graphic (external-graphic or instream-foreign-object)
  991. * @param info the image info object
  992. * @throws IOException In case of an I/O error
  993. */
  994. private void putGraphic(AbstractGraphics abstractGraphic, ImageInfo info)
  995. throws IOException {
  996. try {
  997. FOUserAgent userAgent = abstractGraphic.getUserAgent();
  998. ImageManager manager = userAgent.getImageManager();
  999. ImageSessionContext sessionContext = userAgent.getImageSessionContext();
  1000. Map hints = ImageUtil.getDefaultHints(sessionContext);
  1001. Image image = manager.getImage(info, FLAVORS, hints, sessionContext);
  1002. putGraphic(abstractGraphic, image);
  1003. } catch (ImageException ie) {
  1004. ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get(
  1005. getUserAgent().getEventBroadcaster());
  1006. eventProducer.imageError(this, null, ie, null);
  1007. }
  1008. }
  1009. /**
  1010. * Puts a graphic/image into the generated RTF file.
  1011. * @param abstractGraphic the graphic (external-graphic or instream-foreign-object)
  1012. * @param image the image
  1013. * @throws IOException In case of an I/O error
  1014. */
  1015. private void putGraphic(AbstractGraphics abstractGraphic, Image image)
  1016. throws IOException {
  1017. byte[] rawData = null;
  1018. final ImageInfo info = image.getInfo();
  1019. if (image instanceof ImageRawStream) {
  1020. ImageRawStream rawImage = (ImageRawStream)image;
  1021. InputStream in = rawImage.createInputStream();
  1022. try {
  1023. rawData = IOUtils.toByteArray(in);
  1024. } finally {
  1025. IOUtils.closeQuietly(in);
  1026. }
  1027. }
  1028. if (rawData == null) {
  1029. ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get(
  1030. getUserAgent().getEventBroadcaster());
  1031. eventProducer.imageWritingError(this, null);
  1032. return;
  1033. }
  1034. //Set up percentage calculations
  1035. this.percentManager.setDimension(abstractGraphic);
  1036. PercentBaseContext pContext = new PercentBaseContext() {
  1037. public int getBaseLength(int lengthBase, FObj fobj) {
  1038. switch (lengthBase) {
  1039. case LengthBase.IMAGE_INTRINSIC_WIDTH:
  1040. return info.getSize().getWidthMpt();
  1041. case LengthBase.IMAGE_INTRINSIC_HEIGHT:
  1042. return info.getSize().getHeightMpt();
  1043. default:
  1044. return percentManager.getBaseLength(lengthBase, fobj);
  1045. }
  1046. }
  1047. };
  1048. ImageLayout layout = new ImageLayout(abstractGraphic, pContext,
  1049. image.getInfo().getSize().getDimensionMpt());
  1050. final IRtfTextrunContainer c
  1051. = (IRtfTextrunContainer)builderContext.getContainer(
  1052. IRtfTextrunContainer.class, true, this);
  1053. final RtfExternalGraphic rtfGraphic = c.getTextrun().newImage();
  1054. //set URL
  1055. if (info.getOriginalURI() != null) {
  1056. rtfGraphic.setURL(info.getOriginalURI());
  1057. }
  1058. rtfGraphic.setImageData(rawData);
  1059. FoUnitsConverter converter = FoUnitsConverter.getInstance();
  1060. Dimension viewport = layout.getViewportSize();
  1061. Rectangle placement = layout.getPlacement();
  1062. int cropLeft = Math.round(converter.convertMptToTwips(-placement.x));
  1063. int cropTop = Math.round(converter.convertMptToTwips(-placement.y));
  1064. int cropRight = Math.round(converter.convertMptToTwips(
  1065. -1 * (viewport.width - placement.x - placement.width)));
  1066. int cropBottom = Math.round(converter.convertMptToTwips(
  1067. -1 * (viewport.height - placement.y - placement.height)));
  1068. rtfGraphic.setCropping(cropLeft, cropTop, cropRight, cropBottom);
  1069. int width = Math.round(converter.convertMptToTwips(viewport.width));
  1070. int height = Math.round(converter.convertMptToTwips(viewport.height));
  1071. width += cropLeft + cropRight;
  1072. height += cropTop + cropBottom;
  1073. rtfGraphic.setWidthTwips(width);
  1074. rtfGraphic.setHeightTwips(height);
  1075. //TODO: make this configurable:
  1076. // int compression = m_context.m_options.getRtfExternalGraphicCompressionRate ();
  1077. int compression = 0;
  1078. if (compression != 0) {
  1079. if (!rtfGraphic.setCompressionRate(compression)) {
  1080. log.warn("The compression rate " + compression
  1081. + " is invalid. The value has to be between 1 and 100 %.");
  1082. }
  1083. }
  1084. }
  1085. /** {@inheritDoc} */
  1086. public void pageRef() {
  1087. }
  1088. /** {@inheritDoc} */
  1089. public void startFootnote(Footnote footnote) {
  1090. if (bDefer) {
  1091. return;
  1092. }
  1093. try {
  1094. IRtfTextrunContainer container
  1095. = (IRtfTextrunContainer)builderContext.getContainer(
  1096. IRtfTextrunContainer.class,
  1097. true, this);
  1098. RtfTextrun textrun = container.getTextrun();
  1099. RtfFootnote rtfFootnote = textrun.addFootnote();
  1100. builderContext.pushContainer(rtfFootnote);
  1101. } catch (IOException ioe) {
  1102. handleIOTrouble(ioe);
  1103. } catch (Exception e) {
  1104. log.error("startFootnote: " + e.getMessage());
  1105. throw new RuntimeException("Exception: " + e);
  1106. }
  1107. }
  1108. /** {@inheritDoc} */
  1109. public void endFootnote(Footnote footnote) {
  1110. if (bDefer) {
  1111. return;
  1112. }
  1113. builderContext.popContainer();
  1114. }
  1115. /** {@inheritDoc} */
  1116. public void startFootnoteBody(FootnoteBody body) {
  1117. if (bDefer) {
  1118. return;
  1119. }
  1120. try {
  1121. RtfFootnote rtfFootnote
  1122. = (RtfFootnote)builderContext.getContainer(
  1123. RtfFootnote.class,
  1124. true, this);
  1125. rtfFootnote.startBody();
  1126. } catch (IOException ioe) {
  1127. handleIOTrouble(ioe);
  1128. } catch (Exception e) {
  1129. log.error("startFootnoteBody: " + e.getMessage());
  1130. throw new RuntimeException("Exception: " + e);
  1131. }
  1132. }
  1133. /** {@inheritDoc} */
  1134. public void endFootnoteBody(FootnoteBody body) {
  1135. if (bDefer) {
  1136. return;
  1137. }
  1138. try {
  1139. RtfFootnote rtfFootnote
  1140. = (RtfFootnote)builderContext.getContainer(
  1141. RtfFootnote.class,
  1142. true, this);
  1143. rtfFootnote.endBody();
  1144. } catch (IOException ioe) {
  1145. handleIOTrouble(ioe);
  1146. } catch (Exception e) {
  1147. log.error("endFootnoteBody: " + e.getMessage());
  1148. throw new RuntimeException("Exception: " + e);
  1149. }
  1150. }
  1151. /** {@inheritDoc} */
  1152. public void startLeader(Leader l) {
  1153. if (bDefer) {
  1154. return;
  1155. }
  1156. try {
  1157. percentManager.setDimension(l);
  1158. RtfAttributes rtfAttr = TextAttributesConverter.convertLeaderAttributes(
  1159. l, percentManager);
  1160. IRtfTextrunContainer container
  1161. = (IRtfTextrunContainer)builderContext.getContainer(
  1162. IRtfTextrunContainer.class, true, this);
  1163. RtfTextrun textrun = container.getTextrun();
  1164. textrun.addLeader(rtfAttr);
  1165. } catch (IOException e) {
  1166. log.error("startLeader: " + e.getMessage());
  1167. throw new RuntimeException(e.getMessage());
  1168. } catch (FOPException e) {
  1169. log.error("startLeader: " + e.getMessage());
  1170. throw new RuntimeException(e.getMessage());
  1171. }
  1172. }
  1173. /**
  1174. * @param text FOText object
  1175. * @param characters CharSequence of the characters to process.
  1176. */
  1177. public void text(FOText text, CharSequence characters) {
  1178. if (bDefer) {
  1179. return;
  1180. }
  1181. try {
  1182. IRtfTextrunContainer container
  1183. = (IRtfTextrunContainer)builderContext.getContainer(
  1184. IRtfTextrunContainer.class, true, this);
  1185. RtfTextrun textrun = container.getTextrun();
  1186. RtfAttributes rtfAttr
  1187. = TextAttributesConverter.convertCharacterAttributes(text);
  1188. textrun.pushInlineAttributes(rtfAttr);
  1189. textrun.addString(characters.toString());
  1190. textrun.popInlineAttributes();
  1191. } catch (IOException ioe) {
  1192. handleIOTrouble(ioe);
  1193. } catch (Exception e) {
  1194. log.error("characters:" + e.getMessage());
  1195. throw new RuntimeException(e.getMessage());
  1196. }
  1197. }
  1198. /** {@inheritDoc} */
  1199. public void startPageNumber(PageNumber pagenum) {
  1200. if (bDefer) {
  1201. return;
  1202. }
  1203. try {
  1204. RtfAttributes rtfAttr
  1205. = TextAttributesConverter.convertCharacterAttributes(
  1206. pagenum);
  1207. IRtfTextrunContainer container
  1208. = (IRtfTextrunContainer)builderContext.getContainer(
  1209. IRtfTextrunContainer.class, true, this);
  1210. RtfTextrun textrun = container.getTextrun();
  1211. textrun.addPageNumber(rtfAttr);
  1212. } catch (IOException ioe) {
  1213. handleIOTrouble(ioe);
  1214. } catch (Exception e) {
  1215. log.error("startPageNumber: " + e.getMessage());
  1216. throw new RuntimeException(e.getMessage());
  1217. }
  1218. }
  1219. /** {@inheritDoc} */
  1220. public void endPageNumber(PageNumber pagenum) {
  1221. if (bDefer) {
  1222. return;
  1223. }
  1224. }
  1225. /** {@inheritDoc} */
  1226. public void startPageNumberCitation(PageNumberCitation l) {
  1227. if (bDefer) {
  1228. return;
  1229. }
  1230. try {
  1231. IRtfTextrunContainer container
  1232. = (IRtfTextrunContainer)builderContext.getContainer(
  1233. IRtfTextrunContainer.class, true, this);
  1234. RtfTextrun textrun = container.getTextrun();
  1235. textrun.addPageNumberCitation(l.getRefId());
  1236. } catch (Exception e) {
  1237. log.error("startPageNumberCitation: " + e.getMessage());
  1238. throw new RuntimeException(e.getMessage());
  1239. }
  1240. }
  1241. /** {@inheritDoc} */
  1242. public void startPageNumberCitationLast(PageNumberCitationLast l) {
  1243. if (bDefer) {
  1244. return;
  1245. }
  1246. try {
  1247. IRtfTextrunContainer container
  1248. = (IRtfTextrunContainer)builderContext.getContainer(
  1249. IRtfTextrunContainer.class, true, this);
  1250. RtfTextrun textrun = container.getTextrun();
  1251. textrun.addPageNumberCitation(l.getRefId());
  1252. } catch (RtfException e) {
  1253. log.error("startPageNumberCitationLast: " + e.getMessage());
  1254. throw new RuntimeException(e.getMessage());
  1255. } catch (IOException e) {
  1256. log.error("startPageNumberCitationLast: " + e.getMessage());
  1257. throw new RuntimeException(e.getMessage());
  1258. }
  1259. }
  1260. private void prepareTable(Table tab) {
  1261. // Allows to receive the available width of the table
  1262. percentManager.setDimension(tab);
  1263. // Table gets expanded by half of the border on each side inside Word
  1264. // When using wide borders the table gets cut off
  1265. int tabDiff = tab.getCommonBorderPaddingBackground().getBorderStartWidth(false) / 2
  1266. + tab.getCommonBorderPaddingBackground().getBorderEndWidth(false);
  1267. // check for "auto" value
  1268. if (!(tab.getInlineProgressionDimension().getMaximum(null).getLength()
  1269. instanceof EnumLength)) {
  1270. // value specified
  1271. percentManager.setDimension(tab,
  1272. tab.getInlineProgressionDimension().getMaximum(null)
  1273. .getLength().getValue(percentManager)
  1274. - tabDiff);
  1275. } else {
  1276. // set table width again without border width
  1277. percentManager.setDimension(tab, percentManager.getBaseLength(
  1278. LengthBase.CONTAINING_BLOCK_WIDTH, tab) - tabDiff);
  1279. }
  1280. ColumnSetup columnSetup = new ColumnSetup(tab);
  1281. //int sumOfColumns = columnSetup.getSumOfColumnWidths(percentManager);
  1282. float tableWidth = percentManager.getBaseLength(LengthBase.CONTAINING_BLOCK_WIDTH, tab);
  1283. float tableUnit = columnSetup.computeTableUnit(percentManager, Math.round(tableWidth));
  1284. percentManager.setTableUnit(tab, Math.round(tableUnit));
  1285. }
  1286. /**
  1287. * Calls the appropriate event handler for the passed FObj.
  1288. *
  1289. * @param foNode FO node whose event is to be called
  1290. * @param bStart TRUE calls the start handler, FALSE the end handler
  1291. */
  1292. private void invokeDeferredEvent(FONode foNode, boolean bStart) { // CSOK: MethodLength
  1293. if (foNode instanceof PageSequence) {
  1294. if (bStart) {
  1295. startPageSequence( (PageSequence) foNode);
  1296. } else {
  1297. endPageSequence( (PageSequence) foNode);
  1298. }
  1299. } else if (foNode instanceof Flow) {
  1300. if (bStart) {
  1301. startFlow( (Flow) foNode);
  1302. } else {
  1303. endFlow( (Flow) foNode);
  1304. }
  1305. } else if (foNode instanceof StaticContent) {
  1306. if (bStart) {
  1307. startStatic(null);
  1308. } else {
  1309. endStatic(null);
  1310. }
  1311. } else if (foNode instanceof ExternalGraphic) {
  1312. if (bStart) {
  1313. image( (ExternalGraphic) foNode );
  1314. }
  1315. } else if (foNode instanceof InstreamForeignObject) {
  1316. if (bStart) {
  1317. endInstreamForeignObject( (InstreamForeignObject) foNode );
  1318. }
  1319. } else if (foNode instanceof Block) {
  1320. if (bStart) {
  1321. startBlock( (Block) foNode);
  1322. } else {
  1323. endBlock( (Block) foNode);
  1324. }
  1325. } else if (foNode instanceof BlockContainer) {
  1326. if (bStart) {
  1327. startBlockContainer( (BlockContainer) foNode);
  1328. } else {
  1329. endBlockContainer( (BlockContainer) foNode);
  1330. }
  1331. } else if (foNode instanceof BasicLink) {
  1332. //BasicLink must be placed before Inline
  1333. if (bStart) {
  1334. startLink( (BasicLink) foNode);
  1335. } else {
  1336. endLink(null);
  1337. }
  1338. } else if (foNode instanceof Inline) {
  1339. if (bStart) {
  1340. startInline( (Inline) foNode);
  1341. } else {
  1342. endInline( (Inline) foNode);
  1343. }
  1344. } else if (foNode instanceof FOText) {
  1345. if (bStart) {
  1346. FOText text = (FOText) foNode;
  1347. text(text, text.getCharSequence());
  1348. }
  1349. } else if (foNode instanceof Character) {
  1350. if (bStart) {
  1351. Character c = (Character) foNode;
  1352. character(c);
  1353. }
  1354. } else if (foNode instanceof PageNumber) {
  1355. if (bStart) {
  1356. startPageNumber( (PageNumber) foNode);
  1357. } else {
  1358. endPageNumber( (PageNumber) foNode);
  1359. }
  1360. } else if (foNode instanceof Footnote) {
  1361. if (bStart) {
  1362. startFootnote( (Footnote) foNode);
  1363. } else {
  1364. endFootnote( (Footnote) foNode);
  1365. }
  1366. } else if (foNode instanceof FootnoteBody) {
  1367. if (bStart) {
  1368. startFootnoteBody( (FootnoteBody) foNode);
  1369. } else {
  1370. endFootnoteBody( (FootnoteBody) foNode);
  1371. }
  1372. } else if (foNode instanceof ListBlock) {
  1373. if (bStart) {
  1374. startList( (ListBlock) foNode);
  1375. } else {
  1376. endList( (ListBlock) foNode);
  1377. }
  1378. } else if (foNode instanceof ListItemBody) {
  1379. if (bStart) {
  1380. startListBody(null);
  1381. } else {
  1382. endListBody(null);
  1383. }
  1384. } else if (foNode instanceof ListItem) {
  1385. if (bStart) {
  1386. startListItem( (ListItem) foNode);
  1387. } else {
  1388. endListItem( (ListItem) foNode);
  1389. }
  1390. } else if (foNode instanceof ListItemLabel) {
  1391. if (bStart) {
  1392. startListLabel(null);
  1393. } else {
  1394. endListLabel(null);
  1395. }
  1396. } else if (foNode instanceof Table) {
  1397. if (bStart) {
  1398. startTable( (Table) foNode);
  1399. } else {
  1400. endTable( (Table) foNode);
  1401. }
  1402. } else if (foNode instanceof TableHeader) {
  1403. if (bStart) {
  1404. startHeader( (TableHeader) foNode);
  1405. } else {
  1406. endHeader( (TableHeader) foNode);
  1407. }
  1408. } else if (foNode instanceof TableFooter) {
  1409. if (bStart) {
  1410. startFooter( (TableFooter) foNode);
  1411. } else {
  1412. endFooter( (TableFooter) foNode);
  1413. }
  1414. } else if (foNode instanceof TableBody) {
  1415. if (bStart) {
  1416. startBody( (TableBody) foNode);
  1417. } else {
  1418. endBody( (TableBody) foNode);
  1419. }
  1420. } else if (foNode instanceof TableColumn) {
  1421. if (bStart) {
  1422. startColumn( (TableColumn) foNode);
  1423. } else {
  1424. endColumn( (TableColumn) foNode);
  1425. }
  1426. } else if (foNode instanceof TableRow) {
  1427. if (bStart) {
  1428. startRow( (TableRow) foNode);
  1429. } else {
  1430. endRow( (TableRow) foNode);
  1431. }
  1432. } else if (foNode instanceof TableCell) {
  1433. if (bStart) {
  1434. startCell( (TableCell) foNode);
  1435. } else {
  1436. endCell( (TableCell) foNode);
  1437. }
  1438. } else if (foNode instanceof Leader) {
  1439. if (bStart) {
  1440. startLeader((Leader) foNode);
  1441. }
  1442. } else if (foNode instanceof PageNumberCitation) {
  1443. if (bStart) {
  1444. startPageNumberCitation((PageNumberCitation) foNode);
  1445. } else {
  1446. endPageNumberCitation((PageNumberCitation) foNode);
  1447. }
  1448. } else if (foNode instanceof PageNumberCitationLast) {
  1449. if (bStart) {
  1450. startPageNumberCitationLast((PageNumberCitationLast) foNode);
  1451. } else {
  1452. endPageNumberCitationLast((PageNumberCitationLast) foNode);
  1453. }
  1454. } else {
  1455. RTFEventProducer eventProducer = RTFEventProducer.Provider.get(
  1456. getUserAgent().getEventBroadcaster());
  1457. eventProducer.ignoredDeferredEvent(this, foNode, bStart, foNode.getLocator());
  1458. }
  1459. }
  1460. /**
  1461. * Calls the event handlers for the passed FONode and all its elements.
  1462. *
  1463. * @param foNode FONode object which shall be recursed
  1464. */
  1465. private void recurseFONode(FONode foNode) {
  1466. invokeDeferredEvent(foNode, true);
  1467. if (foNode instanceof PageSequence) {
  1468. PageSequence pageSequence = (PageSequence) foNode;
  1469. Region regionBefore = pagemaster.getRegion(Constants.FO_REGION_BEFORE);
  1470. if (regionBefore != null) {
  1471. FONode staticBefore = pageSequence.getFlowMap().get(
  1472. regionBefore.getRegionName());
  1473. if (staticBefore != null) {
  1474. recurseFONode(staticBefore);
  1475. }
  1476. }
  1477. Region regionAfter = pagemaster.getRegion(Constants.FO_REGION_AFTER);
  1478. if (regionAfter != null) {
  1479. FONode staticAfter = pageSequence.getFlowMap().get(
  1480. regionAfter.getRegionName());
  1481. if (staticAfter != null) {
  1482. recurseFONode(staticAfter);
  1483. }
  1484. }
  1485. recurseFONode( pageSequence.getMainFlow() );
  1486. } else if (foNode instanceof Table) {
  1487. Table table = (Table) foNode;
  1488. //recurse all table-columns
  1489. if (table.getColumns() != null) {
  1490. //Calculation for column-widths which are not set
  1491. prepareTable(table);
  1492. for (Iterator it = table.getColumns().iterator(); it.hasNext();) {
  1493. recurseFONode( (FONode) it.next() );
  1494. }
  1495. } else {
  1496. //TODO Implement implicit column setup handling!
  1497. RTFEventProducer eventProducer = RTFEventProducer.Provider.get(
  1498. getUserAgent().getEventBroadcaster());
  1499. eventProducer.explicitTableColumnsRequired(this, table.getLocator());
  1500. }
  1501. //recurse table-header
  1502. if (table.getTableHeader() != null) {
  1503. recurseFONode( table.getTableHeader() );
  1504. }
  1505. //recurse table-footer
  1506. if (table.getTableFooter() != null) {
  1507. recurseFONode( table.getTableFooter() );
  1508. }
  1509. if (foNode.getChildNodes() != null) {
  1510. for (Iterator it = foNode.getChildNodes(); it.hasNext();) {
  1511. recurseFONode( (FONode) it.next() );
  1512. }
  1513. }
  1514. } else if (foNode instanceof ListItem) {
  1515. ListItem item = (ListItem) foNode;
  1516. recurseFONode(item.getLabel());
  1517. recurseFONode(item.getBody());
  1518. } else if (foNode instanceof Footnote) {
  1519. Footnote fn = (Footnote)foNode;
  1520. recurseFONode(fn.getFootnoteCitation());
  1521. recurseFONode(fn.getFootnoteBody());
  1522. } else {
  1523. //Any other FO-Object: Simply recurse through all childNodes.
  1524. if (foNode.getChildNodes() != null) {
  1525. for (Iterator it = foNode.getChildNodes(); it.hasNext();) {
  1526. FONode fn = (FONode)it.next();
  1527. if (log.isTraceEnabled()) {
  1528. log.trace(" ChildNode for " + fn + " (" + fn.getName() + ")");
  1529. }
  1530. recurseFONode(fn);
  1531. }
  1532. }
  1533. }
  1534. invokeDeferredEvent(foNode, false);
  1535. }
  1536. }