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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665
  1. /*
  2. * $Id$
  3. * ============================================================================
  4. * The Apache Software License, Version 1.1
  5. * ============================================================================
  6. *
  7. * Copyright (C) 1999-2003 The Apache Software Foundation. All rights reserved.
  8. *
  9. * Redistribution and use in source and binary forms, with or without modifica-
  10. * tion, are permitted provided that the following conditions are met:
  11. *
  12. * 1. Redistributions of source code must retain the above copyright notice,
  13. * this list of conditions and the following disclaimer.
  14. *
  15. * 2. Redistributions in binary form must reproduce the above copyright notice,
  16. * this list of conditions and the following disclaimer in the documentation
  17. * and/or other materials provided with the distribution.
  18. *
  19. * 3. The end-user documentation included with the redistribution, if any, must
  20. * include the following acknowledgment: "This product includes software
  21. * developed by the Apache Software Foundation (http://www.apache.org/)."
  22. * Alternately, this acknowledgment may appear in the software itself, if
  23. * and wherever such third-party acknowledgments normally appear.
  24. *
  25. * 4. The names "FOP" and "Apache Software Foundation" must not be used to
  26. * endorse or promote products derived from this software without prior
  27. * written permission. For written permission, please contact
  28. * apache@apache.org.
  29. *
  30. * 5. Products derived from this software may not be called "Apache", nor may
  31. * "Apache" appear in their name, without prior written permission of the
  32. * Apache Software Foundation.
  33. *
  34. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
  35. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  36. * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
  37. * APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
  38. * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
  39. * DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
  40. * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
  41. * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  42. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  43. * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  44. * ============================================================================
  45. *
  46. * This software consists of voluntary contributions made by many individuals
  47. * on behalf of the Apache Software Foundation and was originally created by
  48. * James Tauber <jtauber@jtauber.com>. For more information on the Apache
  49. * Software Foundation, please see <http://www.apache.org/>.
  50. */
  51. package org.apache.fop.apps;
  52. // FOP
  53. import org.apache.fop.fo.ElementMapping;
  54. import org.apache.fop.fo.FOTreeBuilder;
  55. import org.apache.fop.fo.FOUserAgent;
  56. import org.apache.fop.fo.StructureHandler;
  57. import org.apache.fop.layoutmgr.LayoutHandler;
  58. import org.apache.fop.mif.MIFHandler;
  59. import org.apache.fop.render.Renderer;
  60. import org.apache.fop.rtf.renderer.RTFHandler;
  61. import org.apache.fop.tools.DocumentInputSource;
  62. import org.apache.fop.tools.DocumentReader;
  63. // Avalon
  64. import org.apache.avalon.framework.logger.ConsoleLogger;
  65. import org.apache.avalon.framework.logger.LogEnabled;
  66. import org.apache.avalon.framework.logger.Logger;
  67. // DOM
  68. import org.w3c.dom.Document;
  69. // SAX
  70. import org.xml.sax.ContentHandler;
  71. import org.xml.sax.InputSource;
  72. import org.xml.sax.SAXException;
  73. import org.xml.sax.XMLReader;
  74. import javax.xml.parsers.ParserConfigurationException;
  75. import javax.xml.parsers.SAXParserFactory;
  76. // Java
  77. import java.io.IOException;
  78. import java.io.OutputStream;
  79. /**
  80. * Primary class that drives overall FOP process.
  81. * <P>
  82. * The simplest way to use this is to instantiate it with the
  83. * InputSource and OutputStream, then set the renderer desired, and
  84. * calling run();
  85. * <P>
  86. * Here is an example use of Driver which outputs PDF:
  87. *
  88. * <PRE>
  89. * Driver driver = new Driver(new InputSource (args[0]),
  90. * new FileOutputStream(args[1]));
  91. * driver.enableLogging(myLogger); //optional
  92. * driver.setRenderer(RENDER_PDF);
  93. * driver.run();
  94. * </PRE>
  95. * If neccessary, calling classes can call into the lower level
  96. * methods to setup and
  97. * render. Methods can be called to set the
  98. * Renderer to use, the (possibly multiple) ElementMapping(s) to
  99. * use and the OutputStream to use to output the results of the
  100. * rendering (where applicable). In the case of the Renderer and
  101. * ElementMapping(s), the Driver may be supplied either with the
  102. * object itself, or the name of the class, in which case Driver will
  103. * instantiate the class itself. The advantage of the latter is it
  104. * enables runtime determination of Renderer and ElementMapping(s).
  105. * <P>
  106. * Once the Driver is set up, the render method
  107. * is called. Depending on whether DOM or SAX is being used, the
  108. * invocation of the method is either render(Document) or
  109. * buildFOTree(Parser, InputSource) respectively.
  110. * <P>
  111. * A third possibility may be used to build the FO Tree, namely
  112. * calling getContentHandler() and firing the SAX events yourself.
  113. * <P>
  114. * Once the FO Tree is built, the format() and render() methods may be
  115. * called in that order.
  116. * <P>
  117. * Here is an example use of Driver which outputs to AWT:
  118. *
  119. * <PRE>
  120. * Driver driver = new Driver();
  121. * driver.enableLogging(myLogger); //optional
  122. * driver.setRenderer(new org.apache.fop.render.awt.AWTRenderer(translator));
  123. * driver.render(parser, fileInputSource(args[0]));
  124. * </PRE>
  125. */
  126. public class Driver implements LogEnabled {
  127. /**
  128. * Render to PDF. OutputStream must be set
  129. */
  130. public static final int RENDER_PDF = 1;
  131. /**
  132. * Render to a GUI window. No OutputStream neccessary
  133. */
  134. public static final int RENDER_AWT = 2;
  135. /**
  136. * Render to MIF. OutputStream must be set
  137. */
  138. public static final int RENDER_MIF = 3;
  139. /**
  140. * Render to XML. OutputStream must be set
  141. */
  142. public static final int RENDER_XML = 4;
  143. /**
  144. * Render to PRINT. No OutputStream neccessary
  145. */
  146. public static final int RENDER_PRINT = 5;
  147. /**
  148. * Render to PCL. OutputStream must be set
  149. */
  150. public static final int RENDER_PCL = 6;
  151. /**
  152. * Render to Postscript. OutputStream must be set
  153. */
  154. public static final int RENDER_PS = 7;
  155. /**
  156. * Render to Text. OutputStream must be set
  157. */
  158. public static final int RENDER_TXT = 8;
  159. /**
  160. * Render to SVG. OutputStream must be set
  161. */
  162. public static final int RENDER_SVG = 9;
  163. /**
  164. * Render to RTF. OutputStream must be set
  165. */
  166. public static final int RENDER_RTF = 10;
  167. /**
  168. * the FO tree builder
  169. */
  170. private FOTreeBuilder treeBuilder;
  171. /**
  172. * the renderer type code given by setRenderer
  173. */
  174. private int rendererType;
  175. /**
  176. * the renderer to use to output the area tree
  177. */
  178. private Renderer renderer;
  179. /**
  180. * the structure handler
  181. */
  182. private StructureHandler structHandler;
  183. /**
  184. * the source of the FO file
  185. */
  186. private InputSource source;
  187. /**
  188. * the stream to use to output the results of the renderer
  189. */
  190. private OutputStream stream;
  191. /**
  192. * The XML parser to use when building the FO tree
  193. */
  194. private XMLReader reader;
  195. /**
  196. * the system resources that FOP will use
  197. */
  198. private Logger log = null;
  199. private FOUserAgent userAgent = null;
  200. /**
  201. * Returns the fully qualified classname of the standard XML parser for FOP
  202. * to use.
  203. * @return the XML parser classname
  204. */
  205. public static final String getParserClassName() {
  206. try {
  207. return javax.xml.parsers.SAXParserFactory.newInstance()
  208. .newSAXParser().getXMLReader().getClass().getName();
  209. } catch (javax.xml.parsers.ParserConfigurationException e) {
  210. return null;
  211. } catch (org.xml.sax.SAXException e) {
  212. return null;
  213. }
  214. }
  215. /**
  216. * Main constructor for the Driver class.
  217. */
  218. public Driver() {
  219. stream = null;
  220. }
  221. /**
  222. * Convenience constructor for directly setting input and output.
  223. * @param source InputSource to take the XSL-FO input from
  224. * @param stream Target output stream
  225. */
  226. public Driver(InputSource source, OutputStream stream) {
  227. this();
  228. this.source = source;
  229. this.stream = stream;
  230. }
  231. private boolean isInitialized() {
  232. return (treeBuilder != null);
  233. }
  234. /**
  235. * Initializes the Driver object.
  236. */
  237. public void initialize() {
  238. if (isInitialized()) {
  239. throw new IllegalStateException("Driver already initialized");
  240. }
  241. treeBuilder = new FOTreeBuilder();
  242. treeBuilder.setUserAgent(getUserAgent());
  243. }
  244. /**
  245. * Optionally sets the FOUserAgent instance for FOP to use. The Driver
  246. * class sets up its own FOUserAgent if none is set through this method.
  247. * @param agent FOUserAgent to use
  248. */
  249. public void setUserAgent(FOUserAgent agent) {
  250. userAgent = agent;
  251. }
  252. private FOUserAgent getUserAgent() {
  253. if (userAgent == null) {
  254. userAgent = new FOUserAgent();
  255. userAgent.enableLogging(getLogger());
  256. userAgent.setBaseURL("");
  257. }
  258. return userAgent;
  259. }
  260. /**
  261. * Provide the Driver instance with a logger. More information on Avalon
  262. * logging can be found at the
  263. * <a href="http://avalon.apache.org">Avalon site</a>.
  264. *
  265. * @param log the logger. Must not be <code>null</code>.
  266. * @see org.apache.avalon.framework.logger.LogEnabled#enableLogging(Logger)
  267. */
  268. public void enableLogging(Logger log) {
  269. if (this.log == null) {
  270. this.log = log;
  271. } else {
  272. getLogger().warn("Logger is already set! Won't use the new logger.");
  273. }
  274. }
  275. /**
  276. * Provide the Driver instance with a logger.
  277. * @param log the logger. Must not be <code>null</code>.
  278. * @deprecated Use #enableLogging(Logger) instead.
  279. */
  280. public void setLogger(Logger log) {
  281. enableLogging(log);
  282. }
  283. /**
  284. * Returns the logger for use by FOP.
  285. * @return the logger
  286. * @see #enableLogging(Logger)
  287. */
  288. protected Logger getLogger() {
  289. if (this.log == null) {
  290. this.log = new ConsoleLogger(ConsoleLogger.LEVEL_INFO);
  291. this.log.error("Logger not set. Using ConsoleLogger as default.");
  292. }
  293. return this.log;
  294. }
  295. /**
  296. * Resets the Driver so it can be reused. Property and element
  297. * mappings are reset to defaults.
  298. * The output stream is cleared. The renderer is cleared.
  299. */
  300. public synchronized void reset() {
  301. source = null;
  302. stream = null;
  303. reader = null;
  304. treeBuilder.reset();
  305. }
  306. /**
  307. * Indicates whether FOP has already received input data.
  308. * @return true, if input data was received
  309. */
  310. public boolean hasData() {
  311. return (treeBuilder.hasData());
  312. }
  313. /**
  314. * Set the OutputStream to use to output the result of the Renderer
  315. * (if applicable)
  316. * @param stream the stream to output the result of rendering to
  317. */
  318. public void setOutputStream(OutputStream stream) {
  319. this.stream = stream;
  320. }
  321. private void validateOutputStream() {
  322. if (this.stream == null) {
  323. throw new IllegalStateException("OutputStream has not been set");
  324. }
  325. }
  326. /**
  327. * Set the source for the FO document. This can be a normal SAX
  328. * InputSource, or an DocumentInputSource containing a DOM document.
  329. * @see DocumentInputSource
  330. */
  331. public void setInputSource(InputSource source) {
  332. this.source = source;
  333. }
  334. /**
  335. * Sets the reader used when reading in the source. If not set,
  336. * this defaults to a basic SAX parser.
  337. * @param reader the reader to use.
  338. */
  339. public void setXMLReader(XMLReader reader) {
  340. this.reader = reader;
  341. }
  342. /**
  343. * Shortcut to set the rendering type to use. Must be one of
  344. * <ul>
  345. * <li>RENDER_PDF</li>
  346. * <li>RENDER_AWT</li>
  347. * <li>RENDER_MIF</li>
  348. * <li>RENDER_XML</li>
  349. * <li>RENDER_PCL</li>
  350. * <li>RENDER_PS</li>
  351. * <li>RENDER_TXT</li>
  352. * <li>RENDER_SVG</li>
  353. * <li>RENDER_RTF</li>
  354. * </ul>
  355. * @param renderer the type of renderer to use
  356. * @throws IllegalArgumentException if an unsupported renderer type was required.
  357. */
  358. public void setRenderer(int renderer) throws IllegalArgumentException {
  359. rendererType = renderer;
  360. switch (renderer) {
  361. case RENDER_PDF:
  362. setRenderer("org.apache.fop.render.pdf.PDFRenderer");
  363. break;
  364. case RENDER_AWT:
  365. throw new IllegalArgumentException("Use renderer form of setRenderer() for AWT");
  366. case RENDER_PRINT:
  367. throw new IllegalArgumentException("Use renderer form of setRenderer() for PRINT");
  368. case RENDER_PCL:
  369. setRenderer("org.apache.fop.render.pcl.PCLRenderer");
  370. break;
  371. case RENDER_PS:
  372. setRenderer("org.apache.fop.render.ps.PSRenderer");
  373. break;
  374. case RENDER_TXT:
  375. setRenderer("org.apache.fop.render.txt.TXTRenderer()");
  376. break;
  377. case RENDER_MIF:
  378. //structHandler will be set later
  379. break;
  380. case RENDER_XML:
  381. setRenderer("org.apache.fop.render.xml.XMLRenderer");
  382. break;
  383. case RENDER_SVG:
  384. setRenderer("org.apache.fop.render.svg.SVGRenderer");
  385. break;
  386. case RENDER_RTF:
  387. //structHandler will be set later
  388. break;
  389. default:
  390. throw new IllegalArgumentException("Unknown renderer type");
  391. }
  392. }
  393. /**
  394. * Set the Renderer to use.
  395. * @param renderer the renderer instance to use (Note: Logger must be set at this point)
  396. */
  397. public void setRenderer(Renderer renderer) {
  398. renderer.setUserAgent(getUserAgent());
  399. this.renderer = renderer;
  400. }
  401. /**
  402. * Returns the currently active renderer.
  403. * @return the renderer
  404. */
  405. public Renderer getRenderer() {
  406. return renderer;
  407. }
  408. /**
  409. * Sets the renderer.
  410. * @param rendererClassName the fully qualified classname of the renderer
  411. * class to use.
  412. * @param version version number
  413. * @deprecated use renderer.setProducer(version) + setRenderer(renderer) or
  414. * just setRenderer(rendererType) which will use the default producer string.
  415. * @see #setRenderer(int)
  416. * @see #setRenderer(Renderer)
  417. */
  418. public void setRenderer(String rendererClassName, String version) {
  419. setRenderer(rendererClassName);
  420. }
  421. /**
  422. * Set the class name of the Renderer to use as well as the
  423. * producer string for those renderers that can make use of it.
  424. * @param rendererClassName classname of the renderer to use such as
  425. * "org.apache.fop.render.pdf.PDFRenderer"
  426. * @exception IllegalArgumentException if the classname was invalid.
  427. * @see #setRenderer(int)
  428. */
  429. public void setRenderer(String rendererClassName)
  430. throws IllegalArgumentException {
  431. try {
  432. renderer =
  433. (Renderer)Class.forName(rendererClassName).newInstance();
  434. if (renderer instanceof LogEnabled) {
  435. ((LogEnabled)renderer).enableLogging(getLogger());
  436. }
  437. renderer.setProducer(Version.getVersion());
  438. renderer.setUserAgent(getUserAgent());
  439. } catch (ClassNotFoundException e) {
  440. throw new IllegalArgumentException("Could not find "
  441. + rendererClassName);
  442. } catch (InstantiationException e) {
  443. throw new IllegalArgumentException("Could not instantiate "
  444. + rendererClassName);
  445. } catch (IllegalAccessException e) {
  446. throw new IllegalArgumentException("Could not access "
  447. + rendererClassName);
  448. } catch (ClassCastException e) {
  449. throw new IllegalArgumentException(rendererClassName
  450. + " is not a renderer");
  451. }
  452. }
  453. /**
  454. * Add the given element mapping.
  455. * An element mapping maps element names to Java classes.
  456. *
  457. * @param mapping the element mappingto add
  458. */
  459. public void addElementMapping(ElementMapping mapping) {
  460. treeBuilder.addElementMapping(mapping);
  461. }
  462. /**
  463. * Add the element mapping with the given class name.
  464. * @param mappingClassName the class name representing the element mapping.
  465. */
  466. public void addElementMapping(String mappingClassName) {
  467. treeBuilder.addElementMapping(mappingClassName);
  468. }
  469. /**
  470. * Returns the tree builder (a SAX ContentHandler).
  471. *
  472. * Used in situations where SAX is used but not via a FOP-invoked
  473. * SAX parser. A good example is an XSLT engine that fires SAX
  474. * events but isn't a SAX Parser itself.
  475. * @return a content handler for handling the SAX events.
  476. */
  477. public ContentHandler getContentHandler() {
  478. if (!isInitialized()) {
  479. initialize();
  480. }
  481. validateOutputStream();
  482. // TODO: - do this stuff in a better way
  483. // PIJ: I guess the structure handler should be created by the renderer.
  484. if (rendererType == RENDER_MIF) {
  485. structHandler = new MIFHandler(stream);
  486. } else if (rendererType == RENDER_RTF) {
  487. structHandler = new RTFHandler(stream);
  488. } else {
  489. if (renderer == null) {
  490. throw new IllegalStateException(
  491. "Renderer not set when using standard structHandler");
  492. }
  493. structHandler = new LayoutHandler(stream, renderer, true);
  494. }
  495. structHandler.enableLogging(getLogger());
  496. treeBuilder.setUserAgent(getUserAgent());
  497. treeBuilder.setStructHandler(structHandler);
  498. return treeBuilder;
  499. }
  500. /**
  501. * Render the FO document read by a SAX Parser from an InputHandler
  502. * @param InputHandler the input handler containing the source and
  503. * parser information.
  504. * @throws FOPException if anything goes wrong.
  505. */
  506. public synchronized void render(InputHandler inputHandler)
  507. throws FOPException {
  508. XMLReader parser = inputHandler.getParser();
  509. inputHandler.setParserFeatures(parser);
  510. render(parser, inputHandler.getInputSource());
  511. }
  512. /**
  513. * Render the FO document read by a SAX Parser from an InputSource.
  514. * @param parser the SAX parser.
  515. * @param source the input source the parser reads from.
  516. * @throws FOPException if anything goes wrong.
  517. */
  518. public synchronized void render(XMLReader parser, InputSource source)
  519. throws FOPException {
  520. if (!isInitialized()) {
  521. initialize();
  522. }
  523. parser.setContentHandler(getContentHandler());
  524. try {
  525. parser.parse(source);
  526. } catch (SAXException e) {
  527. if (e.getException() instanceof FOPException) {
  528. // Undo exception tunneling.
  529. throw (FOPException)e.getException();
  530. } else {
  531. throw new FOPException(e);
  532. }
  533. } catch (IOException e) {
  534. throw new FOPException(e);
  535. }
  536. }
  537. /**
  538. * Render the FO ducument represented by a DOM Document.
  539. * @param document the DOM document to read from
  540. * @throws FOPException if anything goes wrong.
  541. */
  542. public synchronized void render(Document document)
  543. throws FOPException {
  544. if (!isInitialized()) {
  545. initialize();
  546. }
  547. try {
  548. DocumentInputSource source = new DocumentInputSource(document);
  549. DocumentReader reader = new DocumentReader();
  550. reader.setContentHandler(getContentHandler());
  551. reader.parse(source);
  552. } catch (SAXException e) {
  553. if (e.getException() instanceof FOPException) {
  554. // Undo exception tunneling.
  555. throw (FOPException)e.getException();
  556. } else {
  557. throw new FOPException(e);
  558. }
  559. } catch (IOException e) {
  560. throw new FOPException(e);
  561. }
  562. }
  563. /**
  564. * Runs the formatting and renderering process using the previously set
  565. * parser, input source, renderer and output stream.
  566. * If the renderer was not set, default to PDF.
  567. * If no parser was set, and the input source is not a dom document,
  568. * get a default SAX parser.
  569. * @throws IOException in case of IO errors.
  570. * @throws FOPException if anything else goes wrong.
  571. */
  572. public synchronized void run() throws IOException, FOPException {
  573. if (!isInitialized()) {
  574. initialize();
  575. }
  576. if (renderer == null) {
  577. setRenderer(RENDER_PDF);
  578. }
  579. if (source == null) {
  580. throw new FOPException("InputSource is not set.");
  581. }
  582. if (reader == null) {
  583. if (!(source instanceof DocumentInputSource)) {
  584. try {
  585. SAXParserFactory spf = javax.xml.parsers.SAXParserFactory.newInstance();
  586. spf.setNamespaceAware(true);
  587. reader = spf.newSAXParser().getXMLReader();
  588. } catch (SAXException e) {
  589. throw new FOPException(e);
  590. } catch (ParserConfigurationException e) {
  591. throw new FOPException(e);
  592. }
  593. }
  594. }
  595. if (source instanceof DocumentInputSource) {
  596. render(((DocumentInputSource)source).getDocument());
  597. } else {
  598. render(reader, source);
  599. }
  600. }
  601. }