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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641
  1. /*
  2. * $Id$
  3. * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
  4. * For details on use and redistribution please refer to the
  5. * LICENSE file included with these sources.
  6. */
  7. package org.apache.fop.apps;
  8. // FOP
  9. import org.apache.fop.fo.FOUserAgent;
  10. import org.apache.fop.fo.FOTreeBuilder;
  11. import org.apache.fop.fo.ElementMapping;
  12. import org.apache.fop.layout.AreaTree;
  13. import org.apache.fop.render.Renderer;
  14. import org.apache.fop.configuration.ConfigurationReader;
  15. import org.apache.fop.configuration.Configuration;
  16. import org.apache.fop.tools.DocumentInputSource;
  17. import org.apache.fop.tools.DocumentReader;
  18. import org.apache.fop.render.pdf.PDFRenderer;
  19. import org.apache.log.*;
  20. import org.apache.log.format.*;
  21. import org.apache.log.output.io.*;
  22. import org.apache.log.output.*;
  23. // DOM
  24. import org.w3c.dom.Document;
  25. import org.w3c.dom.Node;
  26. import org.w3c.dom.NamedNodeMap;
  27. import org.w3c.dom.Attr;
  28. // SAX
  29. import org.xml.sax.ContentHandler;
  30. import org.xml.sax.InputSource;
  31. import org.xml.sax.XMLReader;
  32. import org.xml.sax.SAXException;
  33. import org.xml.sax.helpers.AttributesImpl;
  34. // Java
  35. import java.io.*;
  36. import java.util.*;
  37. /**
  38. * Primary class that drives overall FOP process.
  39. * <P>
  40. * The simplest way to use this is to instantiate it with the
  41. * InputSource and OutputStream, then set the renderer desired, and
  42. * calling run();
  43. * <P>
  44. * Here is an example use of Driver which outputs PDF:
  45. *
  46. * <PRE>
  47. * Driver driver = new Driver(new InputSource (args[0]),
  48. * new FileOutputStream(args[1]));
  49. * driver.setRenderer(RENDER_PDF);
  50. * driver.run();
  51. * </PRE>
  52. * If neccessary, calling classes can call into the lower level
  53. * methods to setup and
  54. * render. Methods can be called to set the
  55. * Renderer to use, the (possibly multiple) ElementMapping(s) to
  56. * use and the OutputStream to use to output the results of the
  57. * rendering (where applicable). In the case of the Renderer and
  58. * ElementMapping(s), the Driver may be supplied either with the
  59. * object itself, or the name of the class, in which case Driver will
  60. * instantiate the class itself. The advantage of the latter is it
  61. * enables runtime determination of Renderer and ElementMapping(s).
  62. * <P>
  63. * Once the Driver is set up, the render method
  64. * is called. Depending on whether DOM or SAX is being used, the
  65. * invocation of the method is either render(Document) or
  66. * buildFOTree(Parser, InputSource) respectively.
  67. * <P>
  68. * A third possibility may be used to build the FO Tree, namely
  69. * calling getContentHandler() and firing the SAX events yourself.
  70. * <P>
  71. * Once the FO Tree is built, the format() and render() methods may be
  72. * called in that order.
  73. * <P>
  74. * Here is an example use of Driver which outputs to AWT:
  75. *
  76. * <PRE>
  77. * Driver driver = new Driver();
  78. * driver.setRenderer(new org.apache.fop.render.awt.AWTRenderer(translator));
  79. * driver.render(parser, fileInputSource(args[0]));
  80. * </PRE>
  81. */
  82. public class Driver {
  83. /**
  84. * Render to PDF. OutputStream must be set
  85. */
  86. public static final int RENDER_PDF = 1;
  87. /**
  88. * Render to a GUI window. No OutputStream neccessary
  89. */
  90. public static final int RENDER_AWT = 2;
  91. /**
  92. * Render to MIF. OutputStream must be set
  93. */
  94. public static final int RENDER_MIF = 3;
  95. /**
  96. * Render to XML. OutputStream must be set
  97. */
  98. public static final int RENDER_XML = 4;
  99. /**
  100. * Render to PRINT. No OutputStream neccessary
  101. */
  102. public static final int RENDER_PRINT = 5;
  103. /**
  104. * Render to PCL. OutputStream must be set
  105. */
  106. public static final int RENDER_PCL = 6;
  107. /**
  108. * Render to Postscript. OutputStream must be set
  109. */
  110. public static final int RENDER_PS = 7;
  111. /**
  112. * Render to Text. OutputStream must be set
  113. */
  114. public static final int RENDER_TXT = 8;
  115. /**
  116. * Render to SVG. OutputStream must be set
  117. */
  118. public static final int RENDER_SVG = 9;
  119. /**
  120. * the FO tree builder
  121. */
  122. private FOTreeBuilder _treeBuilder;
  123. /**
  124. * the area tree that is the result of formatting the FO tree
  125. */
  126. private AreaTree _areaTree;
  127. /**
  128. * the renderer to use to output the area tree
  129. */
  130. private Renderer _renderer;
  131. /**
  132. * the source of the FO file
  133. */
  134. private InputSource _source;
  135. /**
  136. * the stream to use to output the results of the renderer
  137. */
  138. private OutputStream _stream;
  139. /**
  140. * The XML parser to use when building the FO tree
  141. */
  142. private XMLReader _reader;
  143. /**
  144. * If true, full error stacks are reported
  145. */
  146. private boolean _errorDump = false;
  147. /**
  148. * the system resources that FOP will use
  149. */
  150. private Logger log;
  151. public static final String getParserClassName() {
  152. String parserClassName = null;
  153. try {
  154. parserClassName = System.getProperty("org.xml.sax.parser");
  155. } catch (SecurityException se) {}
  156. if (parserClassName == null) {
  157. parserClassName = "org.apache.xerces.parsers.SAXParser";
  158. }
  159. return parserClassName;
  160. }
  161. /**
  162. * create a new Driver
  163. */
  164. public Driver() {
  165. _stream = null;
  166. _treeBuilder = new FOTreeBuilder();
  167. setupDefaultMappings();
  168. }
  169. public Driver(InputSource source, OutputStream stream) {
  170. this();
  171. _source = source;
  172. _stream = stream;
  173. }
  174. public void setUserAgent(FOUserAgent agent) {
  175. }
  176. private FOUserAgent getUserAgent() {
  177. FOUserAgent ua = new FOUserAgent();
  178. ua.setLogger(log);
  179. return ua;
  180. }
  181. public void setLogger(Logger logger) {
  182. log = logger;
  183. }
  184. private Logger getLogger() {
  185. if(log == null) {
  186. Hierarchy hierarchy = Hierarchy.getDefaultHierarchy();
  187. PatternFormatter formatter = new PatternFormatter(
  188. "[%{priority}]: %{message}\n%{throwable}" );
  189. LogTarget target = null;
  190. target = new StreamTarget(System.out, formatter);
  191. hierarchy.setDefaultLogTarget(target);
  192. log = hierarchy.getLoggerFor("fop");
  193. log.setPriority(Priority.INFO);
  194. log.error("Logger not set");
  195. }
  196. return log;
  197. }
  198. /**
  199. * Resets the Driver so it can be reused. Property and element
  200. * mappings are reset to defaults.
  201. * The output stream is cleared. The renderer is cleared.
  202. */
  203. public synchronized void reset() {
  204. _areaTree = null;
  205. _source = null;
  206. _stream = null;
  207. _reader = null;
  208. _treeBuilder.reset();
  209. }
  210. public boolean hasData() {
  211. return (_treeBuilder.hasData());
  212. }
  213. /**
  214. * Set the error dump option
  215. * @param dump if true, full stacks will be reported to the error log
  216. */
  217. public void setErrorDump(boolean dump) {
  218. _errorDump = dump;
  219. }
  220. /**
  221. * Set the OutputStream to use to output the result of the Renderer
  222. * (if applicable)
  223. * @param stream the stream to output the result of rendering to
  224. *
  225. */
  226. public void setOutputStream(OutputStream stream) {
  227. _stream = stream;
  228. }
  229. /**
  230. * Set the source for the FO document. This can be a normal SAX
  231. * InputSource, or an DocumentInputSource containing a DOM document.
  232. * @see DocumentInputSource
  233. */
  234. public void setInputSource(InputSource source) {
  235. _source = source;
  236. }
  237. /**
  238. * Sets the reader used when reading in the source. If not set,
  239. * this defaults to a basic SAX parser.
  240. */
  241. public void setXMLReader(XMLReader reader) {
  242. _reader = reader;
  243. }
  244. /**
  245. * Sets all the element and property list mappings to their default values.
  246. *
  247. */
  248. public void setupDefaultMappings() {
  249. addElementMapping("org.apache.fop.fo.FOElementMapping");
  250. addElementMapping("org.apache.fop.svg.SVGElementMapping");
  251. addElementMapping("org.apache.fop.extensions.ExtensionElementMapping");
  252. // add mappings from available services
  253. Enumeration providers =
  254. Service.providers(org.apache.fop.fo.ElementMapping.class);
  255. if (providers != null) {
  256. while (providers.hasMoreElements()) {
  257. String str = (String)providers.nextElement();
  258. try {
  259. addElementMapping(str);
  260. } catch (IllegalArgumentException e) {}
  261. }
  262. }
  263. }
  264. /**
  265. * Set the rendering type to use. Must be one of
  266. * <ul>
  267. * <li>RENDER_PDF
  268. * <li>RENDER_AWT
  269. * <li>RENDER_MIF
  270. * <li>RENDER_XML
  271. * <li>RENDER_PCL
  272. * <li>RENDER_PS
  273. * <li>RENDER_TXT
  274. * <li>RENDER_SVG
  275. * </ul>
  276. * @param renderer the type of renderer to use
  277. */
  278. public void setRenderer(int renderer) throws IllegalArgumentException {
  279. switch (renderer) {
  280. case RENDER_PDF:
  281. setRenderer(new org.apache.fop.render.pdf.PDFRenderer());
  282. break;
  283. case RENDER_AWT:
  284. throw new IllegalArgumentException("Use renderer form of setRenderer() for AWT");
  285. case RENDER_PRINT:
  286. throw new IllegalArgumentException("Use renderer form of setRenderer() for PRINT");
  287. case RENDER_PCL:
  288. setRenderer(new org.apache.fop.render.pcl.PCLRenderer());
  289. break;
  290. case RENDER_PS:
  291. setRenderer(new org.apache.fop.render.ps.PSRenderer());
  292. break;
  293. case RENDER_TXT:
  294. setRenderer(new org.apache.fop.render.txt.TXTRenderer());
  295. break;
  296. case RENDER_MIF:
  297. setRenderer(new org.apache.fop.render.mif.MIFRenderer());
  298. break;
  299. case RENDER_XML:
  300. setRenderer(new org.apache.fop.render.xml.XMLRenderer());
  301. break;
  302. case RENDER_SVG:
  303. setRenderer(new org.apache.fop.render.svg.SVGRenderer());
  304. break;
  305. default:
  306. throw new IllegalArgumentException("Unknown renderer type");
  307. }
  308. }
  309. /**
  310. * Set the Renderer to use
  311. * @param renderer the renderer instance to use
  312. */
  313. public void setRenderer(Renderer renderer) {
  314. renderer.setLogger(getLogger());
  315. renderer.setUserAgent(getUserAgent());
  316. _renderer = renderer;
  317. }
  318. public Renderer getRenderer() {
  319. return _renderer;
  320. }
  321. /**
  322. * @deprecated use renderer.setProducer(version) + setRenderer(renderer) or just setRenderer(renderer_type) which will use the default producer string.
  323. * @see #setRenderer(int)
  324. * @see #setRenderer(Renderer)
  325. */
  326. public void setRenderer(String rendererClassName, String version) {
  327. setRenderer(rendererClassName);
  328. }
  329. /**
  330. * Set the class name of the Renderer to use as well as the
  331. * producer string for those renderers that can make use of it.
  332. * @param rendererClassName classname of the renderer to use such as
  333. * "org.apache.fop.render.pdf.PDFRenderer"
  334. * @exception IllegalArgumentException if the classname was invalid.
  335. * @see #setRenderer(int)
  336. */
  337. public void setRenderer(String rendererClassName)
  338. throws IllegalArgumentException {
  339. try {
  340. _renderer =
  341. (Renderer)Class.forName(rendererClassName).newInstance();
  342. _renderer.setProducer(Version.getVersion());
  343. } catch (ClassNotFoundException e) {
  344. throw new IllegalArgumentException("Could not find "
  345. + rendererClassName);
  346. }
  347. catch (InstantiationException e) {
  348. throw new IllegalArgumentException("Could not instantiate "
  349. + rendererClassName);
  350. }
  351. catch (IllegalAccessException e) {
  352. throw new IllegalArgumentException("Could not access "
  353. + rendererClassName);
  354. }
  355. catch (ClassCastException e) {
  356. throw new IllegalArgumentException(rendererClassName
  357. + " is not a renderer");
  358. }
  359. }
  360. /**
  361. * Add the given element mapping.
  362. * An element mapping maps element names to Java classes.
  363. *
  364. * @param mapping the element mappingto add
  365. */
  366. public void addElementMapping(ElementMapping mapping) {
  367. mapping.addToBuilder(_treeBuilder);
  368. }
  369. /**
  370. * add the element mapping with the given class name
  371. */
  372. public void addElementMapping(String mappingClassName)
  373. throws IllegalArgumentException {
  374. try {
  375. ElementMapping mapping =
  376. (ElementMapping)Class.forName(mappingClassName).newInstance();
  377. addElementMapping(mapping);
  378. } catch (ClassNotFoundException e) {
  379. throw new IllegalArgumentException("Could not find "
  380. + mappingClassName);
  381. }
  382. catch (InstantiationException e) {
  383. throw new IllegalArgumentException("Could not instantiate "
  384. + mappingClassName);
  385. }
  386. catch (IllegalAccessException e) {
  387. throw new IllegalArgumentException("Could not access "
  388. + mappingClassName);
  389. }
  390. catch (ClassCastException e) {
  391. throw new IllegalArgumentException(mappingClassName
  392. + " is not an ElementMapping");
  393. }
  394. }
  395. /**
  396. * Returns the tree builder (a SAX ContentHandler).
  397. *
  398. * Used in situations where SAX is used but not via a FOP-invoked
  399. * SAX parser. A good example is an XSLT engine that fires SAX
  400. * events but isn't a SAX Parser itself.
  401. */
  402. public ContentHandler getContentHandler() {
  403. StreamRenderer streamRenderer = new StreamRenderer(_stream, _renderer);
  404. streamRenderer.setLogger(getLogger());
  405. _treeBuilder.setLogger(getLogger());
  406. _treeBuilder.setStreamRenderer(streamRenderer);
  407. return _treeBuilder;
  408. }
  409. /**
  410. * Build the formatting object tree using the given SAX Parser and
  411. * SAX InputSource
  412. */
  413. public synchronized void render(XMLReader parser, InputSource source)
  414. throws FOPException {
  415. parser.setContentHandler(getContentHandler());
  416. try {
  417. parser.parse(source);
  418. } catch (SAXException e) {
  419. if (e.getException() instanceof FOPException) {
  420. throw (FOPException)e.getException();
  421. } else {
  422. throw new FOPException(e);
  423. }
  424. }
  425. catch (IOException e) {
  426. throw new FOPException(e);
  427. }
  428. }
  429. /**
  430. * Build the formatting object tree using the given DOM Document
  431. */
  432. public synchronized void render(Document document)
  433. throws FOPException {
  434. try {
  435. DocumentInputSource source = new DocumentInputSource(document);
  436. DocumentReader reader = new DocumentReader();
  437. reader.setContentHandler(getContentHandler());
  438. reader.parse(source);
  439. } catch (SAXException e) {
  440. throw new FOPException(e);
  441. }
  442. catch (IOException e) {
  443. throw new FOPException(e);
  444. }
  445. }
  446. /**
  447. * Dumps an error
  448. */
  449. public void dumpError(Exception e) {
  450. if (_errorDump) {
  451. Logger log = getLogger();
  452. if (e instanceof SAXException) {
  453. log.error("", e);
  454. if (((SAXException)e).getException() != null) {
  455. log.error("", ((SAXException)e).getException());
  456. }
  457. } else if (e instanceof FOPException) {
  458. e.printStackTrace();
  459. if (((FOPException)e).getException() != null) {
  460. log.error("", ((FOPException)e).getException());
  461. }
  462. } else {
  463. log.error("", e);
  464. }
  465. }
  466. }
  467. /* Set up the system buffers */
  468. public void setBufferFile(File bufferFile) {
  469. }
  470. /**
  471. * Runs the formatting and renderering process using the previously set
  472. * inputsource and outputstream
  473. */
  474. public synchronized void run() throws IOException, FOPException {
  475. if (_renderer == null) {
  476. setRenderer(RENDER_PDF);
  477. }
  478. if (_source == null) {
  479. throw new FOPException("InputSource is not set.");
  480. }
  481. if (_reader == null) {
  482. if (!(_source instanceof DocumentInputSource)) {
  483. _reader = ConfigurationReader.createParser();
  484. }
  485. }
  486. if (_source instanceof DocumentInputSource) {
  487. render(((DocumentInputSource)_source).getDocument());
  488. } else {
  489. render(_reader, _source);
  490. }
  491. }
  492. }
  493. // code stolen from org.apache.batik.util and modified slightly
  494. // does what sun.misc.Service probably does, but it cannot be relied on.
  495. // hopefully will be part of standard jdk sometime.
  496. /**
  497. * This class loads services present in the class path.
  498. */
  499. class Service {
  500. static Hashtable providerMap = new Hashtable();
  501. public static synchronized Enumeration providers(Class cls) {
  502. ClassLoader cl = cls.getClassLoader();
  503. // null if loaded by bootstrap class loader
  504. if(cl == null) {
  505. cl = ClassLoader.getSystemClassLoader();
  506. }
  507. String serviceFile = "META-INF/services/" + cls.getName();
  508. // System.out.println("File: " + serviceFile);
  509. Vector v = (Vector)providerMap.get(serviceFile);
  510. if (v != null)
  511. return v.elements();
  512. v = new Vector();
  513. providerMap.put(serviceFile, v);
  514. Enumeration e;
  515. try {
  516. e = cl.getResources(serviceFile);
  517. } catch (IOException ioe) {
  518. return v.elements();
  519. }
  520. while (e.hasMoreElements()) {
  521. try {
  522. java.net.URL u = (java.net.URL)e.nextElement();
  523. // System.out.println("URL: " + u);
  524. InputStream is = u.openStream();
  525. Reader r = new InputStreamReader(is, "UTF-8");
  526. BufferedReader br = new BufferedReader(r);
  527. String line = br.readLine();
  528. while (line != null) {
  529. try {
  530. // First strip any comment...
  531. int idx = line.indexOf('#');
  532. if (idx != -1)
  533. line = line.substring(0, idx);
  534. // Trim whitespace.
  535. line = line.trim();
  536. // If nothing left then loop around...
  537. if (line.length() == 0) {
  538. line = br.readLine();
  539. continue;
  540. }
  541. // System.out.println("Line: " + line);
  542. // Try and load the class
  543. // Object obj = cl.loadClass(line).newInstance();
  544. // stick it into our vector...
  545. v.add(line);
  546. } catch (Exception ex) {
  547. // Just try the next line
  548. }
  549. line = br.readLine();
  550. }
  551. } catch (Exception ex) {
  552. // Just try the next file...
  553. }
  554. }
  555. return v.elements();
  556. }
  557. }