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 61KB

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