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.

embedding.xml 36KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752
  1. <?xml version="1.0" encoding="UTF-8" standalone="no"?>
  2. <!--
  3. Licensed to the Apache Software Foundation (ASF) under one or more
  4. contributor license agreements. See the NOTICE file distributed with
  5. this work for additional information regarding copyright ownership.
  6. The ASF licenses this file to You under the Apache License, Version 2.0
  7. (the "License"); you may not use this file except in compliance with
  8. the License. You may obtain a copy of the License at
  9. http://www.apache.org/licenses/LICENSE-2.0
  10. Unless required by applicable law or agreed to in writing, software
  11. distributed under the License is distributed on an "AS IS" BASIS,
  12. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. See the License for the specific language governing permissions and
  14. limitations under the License.
  15. -->
  16. <!-- $Id$ -->
  17. <!DOCTYPE document PUBLIC "-//APACHE//DTD Documentation V2.0//EN" "http://forrest.apache.org/dtd/document-v20.dtd">
  18. <!-- Embedding FOP -->
  19. <document>
  20. <header>
  21. <title>Apache™ FOP: Embedding</title>
  22. <subtitle>How to Embed FOP in a Java application</subtitle>
  23. <version>$Revision$</version>
  24. </header>
  25. <body>
  26. <section id="overview">
  27. <title>Overview</title>
  28. <p>
  29. Review <a href="running.html">Running Apache™ FOP</a> for important information that applies
  30. to embedded applications as well as command-line use, such as options and performance.
  31. </p>
  32. <p>
  33. To embed Apache™ FOP in your application, first create a new
  34. org.apache.fop.apps.FopFactory instance. This object can be used to launch multiple
  35. rendering runs. For each run, create a new org.apache.fop.apps.Fop instance through
  36. one of the factory methods of FopFactory. In the method call you specify which output
  37. format (i.e. MIME type) to use and, if the selected output format requires an
  38. OutputStream, which OutputStream to use for the results of the rendering. You can
  39. customize FOP's behaviour in a rendering run by supplying your own FOUserAgent
  40. instance. The FOUserAgent can, for example, be used to set your own document handler
  41. instance (details below). Finally, you retrieve a SAX DefaultHandler instance from
  42. the Fop object and use that as the SAXResult of your transformation.
  43. </p>
  44. </section>
  45. <section id="API">
  46. <title>The API</title>
  47. <p>
  48. FOP has many classes which express the "public" access modifier, however, this is not
  49. indicative of their inclusion into the public API. Every attempt will be made to keep the
  50. public API static, to minimize regressions for existing users, however, since the API is not
  51. clearly defined, the list of classes below are the generally agreed public API:
  52. <source><![CDATA[
  53. org.apache.fop.apps.*
  54. org.apache.fop.fo.FOEventHandler
  55. org.apache.fop.fo.ElementMappingRegistry
  56. org.apache.fop.fonts.FontManager
  57. org.apache.fop.events.EventListener
  58. org.apache.fop.events.Event
  59. org.apache.fop.events.model.EventSeverity
  60. org.apache.fop.render.ImageHandlerRegistry
  61. org.apache.fop.render.RendererFactory
  62. org.apache.fop.render.intermediate.IFContext
  63. org.apache.fop.render.intermediate.IFDocumentHandler
  64. org.apache.fop.render.intermediate.IFException
  65. org.apache.fop.render.intermediate.IFParser
  66. org.apache.fop.render.intermediate.IFSerializer
  67. org.apache.fop.render.intermediate.IFUtil
  68. org.apache.fop.render.intermediate.util.IFConcatenator]]></source>
  69. </p>
  70. </section>
  71. <section id="basics">
  72. <title>Basic Usage Pattern</title>
  73. <p>
  74. Apache FOP relies heavily on JAXP. It uses SAX events exclusively to receive the XSL-FO
  75. input document. It is therefore a good idea that you know a few things about JAXP (which
  76. is a good skill anyway). Let's look at the basic usage pattern for FOP...
  77. </p>
  78. <p>Here is the basic pattern to render an XSL-FO file to PDF:
  79. </p>
  80. <source><![CDATA[
  81. import org.apache.fop.apps.FopFactory;
  82. import org.apache.fop.apps.Fop;
  83. import org.apache.fop.apps.MimeConstants;
  84. /*..*/
  85. // Step 1: Construct a FopFactory
  86. // (reuse if you plan to render multiple documents!)
  87. FopFactory fopFactory = FopFactory.newInstance();
  88. // Step 2: Set up output stream.
  89. // Note: Using BufferedOutputStream for performance reasons (helpful with FileOutputStreams).
  90. OutputStream out = new BufferedOutputStream(new FileOutputStream(new File("C:/Temp/myfile.pdf")));
  91. try {
  92. // Step 3: Construct fop with desired output format
  93. Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, out);
  94. // Step 4: Setup JAXP using identity transformer
  95. TransformerFactory factory = TransformerFactory.newInstance();
  96. Transformer transformer = factory.newTransformer(); // identity transformer
  97. // Step 5: Setup input and output for XSLT transformation
  98. // Setup input stream
  99. Source src = new StreamSource(new File("C:/Temp/myfile.fo"));
  100. // Resulting SAX events (the generated FO) must be piped through to FOP
  101. Result res = new SAXResult(fop.getDefaultHandler());
  102. // Step 6: Start XSLT transformation and FOP processing
  103. transformer.transform(src, res);
  104. } finally {
  105. //Clean-up
  106. out.close();
  107. }]]></source>
  108. <p>
  109. Let's discuss these 5 steps in detail:
  110. </p>
  111. <ul>
  112. <li>
  113. <strong>Step 1:</strong> You create a new FopFactory instance. The FopFactory instance holds
  114. references to configuration information and cached data. It's important to reuse this
  115. instance if you plan to render multiple documents during a JVM's lifetime.
  116. </li>
  117. <li>
  118. <strong>Step 2:</strong> You set up an OutputStream that the generated document
  119. will be written to. It's a good idea to buffer the OutputStream as demonstrated
  120. to improve performance.
  121. </li>
  122. <li>
  123. <strong>Step 3:</strong> You create a new Fop instance through one of the factory
  124. methods on the FopFactory. You tell the FopFactory what your desired output format
  125. is. This is done by using the MIME type of the desired output format (ex. "application/pdf").
  126. You can use one of the MimeConstants.* constants. The second parameter is the
  127. OutputStream you've setup up in step 2.
  128. </li>
  129. <li>
  130. <strong>Step 4</strong> We recommend that you use JAXP Transformers even
  131. if you don't do XSLT transformations to generate the XSL-FO file. This way
  132. you can always use the same basic pattern. The example here sets up an
  133. "identity transformer" which just passes the input (Source) unchanged to the
  134. output (Result). You don't have to work with a SAXParser if you don't do any
  135. XSLT transformations.
  136. </li>
  137. <li>
  138. <strong>Step 5:</strong> Here you set up the input and output for the XSLT
  139. transformation. The Source object is set up to load the "myfile.fo" file.
  140. The Result is set up so the output of the XSLT transformation is sent to FOP.
  141. The FO file is sent to FOP in the form of SAX events which is the most efficient
  142. way. Please always avoid saving intermediate results to a file or a memory buffer
  143. because that affects performance negatively.
  144. </li>
  145. <li>
  146. <strong>Step 6:</strong> Finally, we start the XSLT transformation by starting
  147. the JAXP Transformer. As soon as the JAXP Transformer starts to send its output
  148. to FOP, FOP itself starts its processing in the background. When the
  149. <code>transform()</code> method returns FOP will also have finished converting
  150. the FO file to a PDF file and you can close the OutputStream.
  151. <note label="Tip!">
  152. It's a good idea to enclose the whole conversion in a try..finally statement. If
  153. you close the OutputStream in the finally section, this will make sure that the
  154. OutputStream is properly closed even if an exception occurs during the conversion.
  155. </note>
  156. </li>
  157. </ul>
  158. <p>
  159. If you're not totally familiar with JAXP Transformers, please have a look at the
  160. <a href="#examples">Embedding examples</a> below. The section contains examples
  161. for all sorts of use cases. If you look at all of them in turn you should be able
  162. to see the patterns in use and the flexibility this approach offers without adding
  163. too much complexity.
  164. </p>
  165. <p>
  166. This may look complicated at first, but it's really just the combination of an
  167. XSL transformation and a FOP run. It's also easy to comment out the FOP part
  168. for debugging purposes, for example when you're tracking down a bug in your
  169. stylesheet. You can easily write the XSL-FO output from the XSL transformation
  170. to a file to check if that part generates the expected output. An example for that
  171. can be found in the <a href="#examples">Embedding examples</a> (See "ExampleXML2FO").
  172. </p>
  173. <section id="basic-logging">
  174. <title>Logging</title>
  175. <p>
  176. Logging is now a little different than it was in FOP 0.20.5. We've switched from
  177. Avalon Logging to <a href="ext:commons-logging">Jakarta Commons Logging</a>.
  178. While with Avalon Logging the loggers were directly given to FOP, FOP now retrieves
  179. its logger(s) through a statically available LogFactory. This is similar to the
  180. general pattern that you use when you work with Apache Log4J directly, for example.
  181. We call this "static logging" (Commons Logging, Log4J) as opposed to "instance logging"
  182. (Avalon Logging). This has a consequence: You can't give FOP a logger for each
  183. processing run anymore. The log output of multiple, simultaneously running FOP instances
  184. is sent to the same logger.
  185. </p>
  186. <p>
  187. By default, <a href="ext:commons-logging">Jakarta Commons Logging</a> uses
  188. JDK logging (available in JDKs 1.4 or higher) as its backend. You can configure Commons
  189. Logging to use an alternative backend, for example Log4J. Please consult the
  190. <a href="ext:commons-logging">documentation for Jakarta Commons Logging</a> on
  191. how to configure alternative backends.
  192. </p>
  193. <p>
  194. As a result of the above we differentiate between two kinds of "logging":
  195. </p>
  196. <ul>
  197. <li>(FOP-)Developer-oriented logging</li>
  198. <li><a href="events.html">User/Integrator-oriented feedback</a> (NEW!)</li>
  199. </ul>
  200. <p>
  201. The use of "feedback" instead of "logging" is intentional. Most people were using
  202. log output as a means to get feedback from events within FOP. Therefore, FOP now
  203. includes an <code>event</code> package which can be used to receive feedback from
  204. the layout engine and other components within FOP <strong>per rendering run</strong>.
  205. This feedback is not just some
  206. text but event objects with parameters so these events can be interpreted by code.
  207. Of course, there is a facility to turn these events into normal human-readable
  208. messages. For details, please read on on the <a href="events.html">Events page</a>.
  209. This leaves normal logging to be mostly a thing used by the FOP developers
  210. although anyone can surely activate certain logging categories but the feedback
  211. from the loggers won't be separated by processing runs. If this is required,
  212. the <a href="events.html">Events subsystem</a> is the right approach.
  213. </p>
  214. </section>
  215. <section id="render">
  216. <title>Processing XSL-FO</title>
  217. <p>
  218. Once the Fop instance is set up, call <code>getDefaultHandler()</code> to obtain a SAX
  219. DefaultHandler instance to which you can send the SAX events making up the XSL-FO
  220. document you'd like to render. FOP processing starts as soon as the DefaultHandler's
  221. <code>startDocument()</code> method is called. Processing stops again when the
  222. DefaultHandler's <code>endDocument()</code> method is called. Please refer to the basic
  223. usage pattern shown above to render a simple XSL-FO document.
  224. </p>
  225. </section>
  226. <section id="render-with-xslt">
  227. <title>Processing XSL-FO generated from XML+XSLT</title>
  228. <p>
  229. If you want to process XSL-FO generated from XML using XSLT we recommend
  230. again using standard JAXP to do the XSLT part and piping the generated SAX
  231. events directly through to FOP. The only thing you'd change to do that
  232. on the basic usage pattern above is to set up the Transformer differently:
  233. </p>
  234. <source><![CDATA[
  235. //without XSLT:
  236. //Transformer transformer = factory.newTransformer(); // identity transformer
  237. //with XSLT:
  238. Source xslt = new StreamSource(new File("mystylesheet.xsl"));
  239. Transformer transformer = factory.newTransformer(xslt);]]></source>
  240. </section>
  241. </section>
  242. <section id="input">
  243. <title>Input Sources</title>
  244. <p>
  245. The input XSL-FO document is always received by FOP as a SAX stream (see the
  246. <a href="../dev/design/parsing.html">Parsing Design Document</a> for the rationale).
  247. </p>
  248. <p>
  249. However, you may not always have your input document available as a SAX stream.
  250. But with JAXP it's easy to convert different input sources to a SAX stream so you
  251. can pipe it into FOP. That sounds more difficult than it is. You simply have
  252. to set up the right Source instance as input for the JAXP transformation.
  253. A few examples:
  254. </p>
  255. <ul>
  256. <li>
  257. <strong>URL:</strong> <code>Source src = new StreamSource("http://localhost:8080/testfile.xml");</code>
  258. </li>
  259. <li>
  260. <strong>File:</strong> <code>Source src = new StreamSource(new File("C:/Temp/myinputfile.xml"));</code>
  261. </li>
  262. <li>
  263. <strong>String:</strong> <code>Source src = new StreamSource(new StringReader(myString)); // myString is a String</code>
  264. </li>
  265. <li>
  266. <strong>InputStream:</strong> <code>Source src = new StreamSource(new MyInputStream(something));</code>
  267. </li>
  268. <li>
  269. <strong>Byte Array:</strong> <code>Source src = new StreamSource(new ByteArrayInputStream(myBuffer)); // myBuffer is a byte[] here</code>
  270. </li>
  271. <li>
  272. <strong>DOM:</strong> <code>Source src = new DOMSource(myDocument); // myDocument is a Document or a Node</code>
  273. </li>
  274. <li>
  275. <strong>Java Objects:</strong> Please have a look at the <a href="#examples">Embedding examples</a> which contain an example for this.
  276. </li>
  277. </ul>
  278. <p>
  279. There are a variety of upstream data manipulations possible.
  280. For example, you may have a DOM and an XSL stylesheet; or you may want to
  281. set variables in the stylesheet. Interface documentation and some cookbook
  282. solutions to these situations are provided in
  283. <a href="http://xml.apache.org/xalan-j/usagepatterns.html">Xalan Basic Usage Patterns</a>.
  284. </p>
  285. </section>
  286. <section id="config-internal">
  287. <title>Configuring Apache FOP Programmatically</title>
  288. <p>
  289. Apache FOP provides two levels on which you can customize FOP's
  290. behaviour: the FopFactory and the user agent.
  291. </p>
  292. <section id="fop-factory">
  293. <title>Customizing the FopFactory</title>
  294. <p>
  295. The FopFactory holds configuration data and references to objects which are reusable over
  296. multiple rendering runs. It's important to instantiate it only once (except in special
  297. environments) and reuse it every time to create new FOUserAgent and Fop instances.
  298. </p>
  299. <p>
  300. You can set all sorts of things on the FopFactory:
  301. </p>
  302. <ul>
  303. <li>
  304. <p>
  305. The <strong>font base URL</strong> to use when resolving relative URLs for fonts. Example:
  306. </p>
  307. <source>fopFactory.getFontManager().setFontBaseURL("file:///C:/Temp/fonts");</source>
  308. </li>
  309. <li>
  310. <p>
  311. The <strong>hyphenation base URL</strong> to use when resolving relative URLs for
  312. hyphenation patterns. Example:
  313. </p>
  314. <source>fopFactory.setHyphenBaseURL("file:///C:/Temp/hyph");</source>
  315. </li>
  316. <li>
  317. <p>
  318. Disable <strong>strict validation</strong>. When disabled FOP is less strict about the rules
  319. established by the XSL-FO specification. Example:
  320. </p>
  321. <source>fopFactory.setStrictValidation(false);</source>
  322. </li>
  323. <li>
  324. <p>
  325. Enable an <strong>alternative set of rules for text indents</strong> that tries to mimic the behaviour of many commercial
  326. FO implementations, that chose to break the specification in this respect. The default of this option is
  327. 'false', which causes Apache FOP to behave exactly as described in the specification. To enable the
  328. alternative behaviour, call:
  329. </p>
  330. <source>fopFactory.setBreakIndentInheritanceOnReferenceAreaBoundary(true);</source>
  331. </li>
  332. <li>
  333. <p>
  334. Set the <strong>source resolution</strong> for the document. This is used internally to determine the pixel
  335. size for SVG images and bitmap images without resolution information. Default: 72 dpi. Example:
  336. </p>
  337. <source>fopFactory.setSourceResolution(96); // =96dpi (dots/pixels per Inch)</source>
  338. </li>
  339. <li>
  340. <p>
  341. Manually add an <strong>ElementMapping instance</strong>. If you want to supply a special FOP extension
  342. you can give the instance to the FOUserAgent. Normally, the FOP extensions can be automatically detected
  343. (see the documentation on extension for more info). Example:
  344. </p>
  345. <source>fopFactory.addElementMapping(myElementMapping); // myElementMapping is a org.apache.fop.fo.ElementMapping</source>
  346. </li>
  347. <li>
  348. <p>
  349. Set a <strong>URIResolver</strong> for custom URI resolution. By supplying a JAXP URIResolver you can add
  350. custom URI resolution functionality to FOP. For example, you can use
  351. <a href="ext:xml.apache.org/commons/resolver">Apache XML Commons Resolver</a> to make use of XCatalogs. Example:
  352. </p>
  353. <source>fopFactory.setURIResolver(myResolver); // myResolver is a javax.xml.transform.URIResolver</source>
  354. <note>
  355. Both the FopFactory and the FOUserAgent have a method to set a URIResolver. The URIResolver on the FopFactory
  356. is primarily used to resolve URIs on factory-level (hyphenation patterns, for example) and it is always used
  357. if no other URIResolver (for example on the FOUserAgent) resolved the URI first.
  358. </note>
  359. </li>
  360. </ul>
  361. </section>
  362. <section id="user-agent">
  363. <title>Customizing the User Agent</title>
  364. <p>
  365. The user agent is the entity that allows you to interact with a single rendering run, i.e. the processing of a single
  366. document. If you wish to customize the user agent's behaviour, the first step is to create your own instance
  367. of FOUserAgent using the appropriate factory method on FopFactory and pass that
  368. to the factory method that will create a new Fop instance:
  369. </p>
  370. <source><![CDATA[
  371. FopFactory fopFactory = FopFactory.newInstance(); // Reuse the FopFactory if possible!
  372. // do the following for each new rendering run
  373. FOUserAgent userAgent = fopFactory.newFOUserAgent();
  374. // customize userAgent
  375. Fop fop = fopFactory.newFop(MimeConstants.MIME_POSTSCRIPT, userAgent, out);]]></source>
  376. <p>
  377. You can do all sorts of things on the user agent:
  378. </p>
  379. <ul>
  380. <li>
  381. <p>
  382. The <strong>base URL</strong> to use when resolving relative URLs. Example:
  383. </p>
  384. <source>userAgent.setBaseURL("file:///C:/Temp/");</source>
  385. </li>
  386. <li>
  387. <p>
  388. Set the <strong>producer</strong> of the document. This is metadata information that can be used for certain output formats such as PDF. The default producer is "Apache FOP". Example:
  389. </p>
  390. <source>userAgent.setProducer("MyKillerApplication");</source>
  391. </li>
  392. <li>
  393. <p>
  394. Set the <strong>creating user</strong> of the document. This is metadata information that can be used for certain output formats such as PDF. Example:
  395. </p>
  396. <source>userAgent.setCreator("John Doe");</source>
  397. </li>
  398. <li>
  399. <p>
  400. Set the <strong>author</strong> of the document. This is metadata information that can be used for certain output formats such as PDF. Example:
  401. </p>
  402. <source>userAgent.setAuthor("John Doe");</source>
  403. </li>
  404. <li>
  405. <p>
  406. Override the <strong>creation date and time</strong> of the document. This is metadata information that can be used for certain output formats such as PDF. Example:
  407. </p>
  408. <source>userAgent.setCreationDate(new Date());</source>
  409. </li>
  410. <li>
  411. <p>
  412. Set the <strong>title</strong> of the document. This is metadata information that can be used for certain output formats such as PDF. Example:
  413. </p>
  414. <source>userAgent.setTitle("Invoice No 138716847");</source>
  415. </li>
  416. <li>
  417. <p>
  418. Set the <strong>keywords</strong> of the document. This is metadata information that can be used for certain output formats such as PDF. Example:
  419. </p>
  420. <source>userAgent.setKeywords("XML XSL-FO");</source>
  421. </li>
  422. <li>
  423. <p>
  424. Set the <strong>target resolution</strong> for the document. This is used to
  425. specify the output resolution for bitmap images generated by bitmap renderers
  426. (such as the TIFF renderer) and by bitmaps generated by Apache Batik for filter
  427. effects and such. Default: 72 dpi. Example:
  428. </p>
  429. <source>userAgent.setTargetResolution(300); // =300dpi (dots/pixels per Inch)</source>
  430. </li>
  431. <li>
  432. <p>
  433. Set <strong>your own Document Handler</strong>. This feature can be used for several purposes, the most likey usage of which would probably be
  434. binding a MIME type when the output is Intermediate Format (see <a href="#documenthandlers">Document Handlers</a>). This also allows advanced
  435. users to create their own implementation of the document handler.
  436. </p>
  437. <source>userAgent.setDocumentHandlerOverride(documentHandler) // documentHandler is an instance of org.apache.fop.render.intermediate.IFDocumentHandler</source>
  438. </li>
  439. <li>
  440. <p>
  441. Set <strong>your own FOEventHandler instance</strong>. If you want to supply your own FOEventHandler or
  442. configure an FOEventHandler subclass in a special way you can give the instance to the FOUserAgent. Normally,
  443. the FOEventHandler instance is created by FOP. Example:
  444. </p>
  445. <source>userAgent.setFOEventHandlerOverride(myFOEventHandler); // myFOEventHandler is an org.apache.fop.fo.FOEventHandler</source>
  446. </li>
  447. <li>
  448. <p>
  449. Set a <strong>URIResolver</strong> for custom URI resolution. By supplying a JAXP URIResolver you can add
  450. custom URI resolution functionality to FOP. For example, you can use
  451. <a href="ext:xml.apache.org/commons/resolver">Apache XML Commons Resolver</a> to make use of XCatalogs. Example:
  452. </p>
  453. <source>userAgent.setURIResolver(myResolver); // myResolver is a javax.xml.transform.URIResolver</source>
  454. <note>
  455. Both the FopFactory and the FOUserAgent have a method to set a URIResolver. The URIResolver on the FOUserAgent is
  456. used for resolving URIs which are document-related. If it's not set or cannot resolve a URI, the URIResolver
  457. from the FopFactory is used.
  458. </note>
  459. </li>
  460. </ul>
  461. <note>
  462. You should not reuse an FOUserAgent instance between FOP rendering runs although you can. Especially
  463. in multi-threaded environment, this is a bad idea.
  464. </note>
  465. </section>
  466. </section>
  467. <section id="config-external">
  468. <title>Using a Configuration File</title>
  469. <p>
  470. Instead of setting the parameters manually in code as shown above you can also set
  471. many values from an XML configuration file:
  472. </p>
  473. <source><![CDATA[
  474. import org.apache.avalon.framework.configuration.Configuration;
  475. import org.apache.avalon.framework.configuration.DefaultConfigurationBuilder;
  476. /*..*/
  477. DefaultConfigurationBuilder cfgBuilder = new DefaultConfigurationBuilder();
  478. Configuration cfg = cfgBuilder.buildFromFile(new File("C:/Temp/mycfg.xml"));
  479. fopFactory.setUserConfig(cfg);
  480. /* ..or.. */
  481. fopFactory.setUserConfig(new File("C:/Temp/mycfg.xml"));]]></source>
  482. <p>
  483. The layout of the configuration file is described on the <a href="configuration.html">Configuration page</a>.
  484. </p>
  485. </section>
  486. <section id="documenthandlers">
  487. <title>Document Handlers</title>
  488. <p>
  489. The document handlers are classes that inherit from <code>org.apache.fop.render.intermediate.IFDocumentHandler</code>. This
  490. is an interface for which a MIME type specific implementation can be created. This same handler is used either when XSL-FO
  491. is used as the input or when Intermediate Format is used. Since IF is output format agnostic, if custom fonts or other
  492. configuration information that affect layout (specific to a particular MIME type) are given then FOP needs that contextual
  493. information. The document handler provides that context so that when the IF is rendered, it is more visually consistent with
  494. FO rendering. The code below shows an example of how a document handler can be used to provide PDF configuration data to the
  495. IFSerializer.
  496. <source><![CDATA[
  497. IFDocumentHandler targetHandler = userAgent.getRendererFactory().createDocumentHandler(userAgent, MimeConstants.MIME_PDF);
  498. IFSerializer ifSerializer = new IFSerializer(); //Create the IFSerializer to write the intermediate format
  499. ifSerializer.setContext(new IFContext(userAgent));
  500. ifSerializer.mimicDocumentHandler(targetHandler); //Tell the IFSerializer to mimic the target format
  501. userAgent.setDocumentHandlerOverride(ifSerializer); //Make sure the prepared document handler is used
  502. ]]></source>
  503. The rest of the code is the same as in <a href="#basics">Basic Usage Patterns</a>.
  504. </p>
  505. </section>
  506. <section id="hints">
  507. <title>Hints</title>
  508. <section id="object-reuse">
  509. <title>Object reuse</title>
  510. <p>
  511. Fop instances shouldn't (and can't) be reused. Please recreate
  512. Fop and FOUserAgent instances for each rendering run using the FopFactory.
  513. This is a cheap operation as all reusable information is held in the
  514. FopFactory. That's why it's so important to reuse the FopFactory instance.
  515. </p>
  516. </section>
  517. <section id="awt">
  518. <title>AWT issues</title>
  519. <p>
  520. If your XSL-FO files contain SVG then Apache Batik will be used. When Batik is
  521. initialised it uses certain classes in <code>java.awt</code> that
  522. intialise the Java AWT classes. This means that a daemon thread
  523. is created by the JVM and on Unix it will need to connect to a
  524. DISPLAY.
  525. </p>
  526. <p>
  527. The thread means that the Java application may not automatically quit
  528. when finished, you will need to call <code>System.exit()</code>. These
  529. issues should be fixed in the JDK 1.4.
  530. </p>
  531. <p>
  532. If you run into trouble running FOP on a head-less server, please see the
  533. <a href="graphics.html#batik">notes on Batik</a>.
  534. </p>
  535. </section>
  536. <section id="render-info">
  537. <title>Getting information on the rendering process</title>
  538. <p>
  539. To get the number of pages that were rendered by FOP you can call
  540. <code>Fop.getResults()</code>. This returns a <code>FormattingResults</code> object
  541. where you can look up the number of pages produced. It also gives you the
  542. page-sequences that were produced along with their id attribute and their
  543. numbers of pages. This is particularly useful if you render multiple
  544. documents (each enclosed by a page-sequence) and have to know the number of
  545. pages of each document.
  546. </p>
  547. </section>
  548. </section>
  549. <section id="performance">
  550. <title>Improving performance</title>
  551. <p>
  552. There are several options to consider:
  553. </p>
  554. <ul>
  555. <li>
  556. Whenever possible, try to use SAX to couple the individual components involved
  557. (parser, XSL transformer, SQL datasource etc.).
  558. </li>
  559. <li>
  560. Depending on the target OutputStream (in case of a FileOutputStream, but not
  561. for a ByteArrayOutputStream, for example) it may improve performance considerably
  562. if you buffer the OutputStream using a BufferedOutputStream:
  563. <code>out = new java.io.BufferedOutputStream(out);</code>
  564. <br/>
  565. Make sure you properly close the OutputStream when FOP is finished.
  566. </li>
  567. <li>
  568. Cache the stylesheet. If you use the same stylesheet multiple times
  569. you can set up a JAXP <code>Templates</code> object and reuse it each time you do
  570. the XSL transformation. (More information can be found
  571. <a class="fork" href="http://www.javaworld.com/javaworld/jw-05-2003/jw-0502-xsl.html">here</a>.)
  572. </li>
  573. <li>
  574. Use an XSLT compiler like <a class="fork" href="http://xml.apache.org/xalan-j/xsltc_usage.html">XSLTC</a>
  575. that comes with Xalan-J.
  576. </li>
  577. <li>
  578. Fine-tune your stylesheet to make the XSLT process more efficient and to create XSL-FO that can
  579. be processed by FOP more efficiently. Less is more: Try to make use of property inheritance where possible.
  580. </li>
  581. <li>
  582. You may also wish to consider trying to reduce <a href="http://xmlgraphics.apache.org/fop/trunk/running.html#memory">memory usage</a>.
  583. </li>
  584. </ul>
  585. </section>
  586. <section id="multithreading">
  587. <title>Multithreading FOP</title>
  588. <p>
  589. Apache FOP may currently not be completely thread safe.
  590. The code has not been fully tested for multi-threading issues, yet.
  591. If you encounter any suspicious behaviour, please notify us.
  592. </p>
  593. <p>
  594. There is also a known issue with fonts being jumbled between threads when using
  595. the Java2D/AWT renderer (which is used by the -awt and -print output options).
  596. In general, you cannot safely run multiple threads through the AWT renderer.
  597. </p>
  598. </section>
  599. <section id="examples">
  600. <title>Examples</title>
  601. <p>
  602. The directory "{fop-dir}/examples/embedding" contains several working examples.
  603. </p>
  604. <section id="ExampleFO2PDF">
  605. <title>ExampleFO2PDF.java</title>
  606. <p>This
  607. <a href="http://svn.apache.org/viewcvs.cgi/xmlgraphics/fop/trunk/examples/embedding/java/embedding/ExampleFO2PDF.java?view=markup">
  608. example</a>
  609. demonstrates the basic usage pattern to transform an XSL-FO
  610. file to PDF using FOP.
  611. </p>
  612. <figure src="images/EmbeddingExampleFO2PDF.png" alt="Example XSL-FO to PDF"/>
  613. </section>
  614. <section id="ExampleXML2FO">
  615. <title>ExampleXML2FO.java</title>
  616. <p>This
  617. <a href="http://svn.apache.org/viewcvs.cgi/xmlgraphics/fop/trunk/examples/embedding/java/embedding/ExampleXML2FO.java?view=markup">
  618. example</a>
  619. has nothing to do with FOP. It is there to show you how an XML
  620. file can be converted to XSL-FO using XSLT. The JAXP API is used to do the
  621. transformation. Make sure you've got a JAXP-compliant XSLT processor in your
  622. classpath (ex. <a href="http://xml.apache.org/xalan-j">Xalan</a>).
  623. </p>
  624. <figure src="images/EmbeddingExampleXML2FO.png" alt="Example XML to XSL-FO"/>
  625. </section>
  626. <section id="ExampleXML2PDF">
  627. <title>ExampleXML2PDF.java</title>
  628. <p>This
  629. <a href="http://svn.apache.org/viewcvs.cgi/xmlgraphics/fop/trunk/examples/embedding/java/embedding/ExampleXML2PDF.java?view=markup">
  630. example</a>
  631. demonstrates how you can convert an arbitrary XML file to PDF
  632. using XSLT and XSL-FO/FOP. It is a combination of the first two examples
  633. above. The example uses JAXP to transform the XML file to XSL-FO and FOP to
  634. transform the XSL-FO to PDF.
  635. </p>
  636. <figure src="images/EmbeddingExampleXML2PDF.png" alt="Example XML to PDF (via XSL-FO)"/>
  637. <p>
  638. The output (XSL-FO) from the XSL transformation is piped through to FOP using
  639. SAX events. This is the most efficient way to do this because the
  640. intermediate result doesn't have to be saved somewhere. Often, novice users
  641. save the intermediate result in a file, a byte array or a DOM tree. We
  642. strongly discourage you to do this if it isn't absolutely necessary. The
  643. performance is significantly higher with SAX.
  644. </p>
  645. </section>
  646. <section id="ExampleObj2XML">
  647. <title>ExampleObj2XML.java</title>
  648. <p>This
  649. <a href="http://svn.apache.org/viewcvs.cgi/xmlgraphics/fop/trunk/examples/embedding/java/embedding/ExampleObj2XML.java?view=markup">
  650. example</a>
  651. is a preparatory example for the next one. It's an example that
  652. shows how an arbitrary Java object can be converted to XML. It's an often
  653. needed task to do this. Often people create a DOM tree from a Java object and
  654. use that. This is pretty straightforward. The example here, however, shows how
  655. to do this using SAX, which will probably be faster and not even more
  656. complicated once you know how this works.
  657. </p>
  658. <figure src="images/EmbeddingExampleObj2XML.png" alt="Example Java object to XML"/>
  659. <p>
  660. For this example we've created two classes: ProjectTeam and ProjectMember
  661. (found in xml-fop/examples/embedding/java/embedding/model). They represent
  662. the same data structure found in
  663. xml-fop/examples/embedding/xml/xml/projectteam.xml. We want to serialize to XML a
  664. project team with several members which exist as Java objects.
  665. Therefore we created the two classes: ProjectTeamInputSource and
  666. ProjectTeamXMLReader (in the same place as ProjectTeam above).
  667. </p>
  668. <p>
  669. The XMLReader implementation (regard it as a special kind of XML parser) is
  670. responsible for creating SAX events from the Java object. The InputSource
  671. class is only used to hold the ProjectTeam object to be used.
  672. </p>
  673. <p>
  674. Have a look at the source of ExampleObj2XML.java to find out how this is
  675. used. For more detailed information see other resources on JAXP (ex.
  676. <a class="fork" href="http://java.sun.com/xml/jaxp/dist/1.1/docs/tutorial/xslt/3_generate.html">An older JAXP tutorial</a>).
  677. </p>
  678. </section>
  679. <section id="ExampleObj2PDF">
  680. <title>ExampleObj2PDF.java</title>
  681. <p>This
  682. <a href="http://svn.apache.org/viewcvs.cgi/xmlgraphics/fop/trunk/examples/embedding/java/embedding/ExampleObj2PDF.java?view=markup">
  683. example</a>
  684. combines the previous and the third to demonstrate
  685. how you can transform a Java object to a PDF directly in one smooth run
  686. by generating SAX events from the Java object that get fed to an XSL
  687. transformation. The result of the transformation is then converted to PDF
  688. using FOP as before.
  689. </p>
  690. <figure src="images/EmbeddingExampleObj2PDF.png" alt="Example Java object to PDF (via XML and XSL-FO)"/>
  691. </section>
  692. <section id="ExampleDOM2PDF">
  693. <title>ExampleDOM2PDF.java</title>
  694. <p>This
  695. <a href="http://svn.apache.org/viewcvs.cgi/xmlgraphics/fop/trunk/examples/embedding/java/embedding/ExampleDOM2PDF.java?view=markup">
  696. example</a>
  697. has FOP use a DOMSource instead of a StreamSource in order to
  698. use a DOM tree as input for an XSL transformation.
  699. </p>
  700. </section>
  701. <section id="ExampleSVG2PDF">
  702. <title>ExampleSVG2PDF.java (PDF Transcoder example)</title>
  703. <p>This
  704. <a href="http://svn.apache.org/viewcvs.cgi/xmlgraphics/fop/trunk/examples/embedding/java/embedding/ExampleSVG2PDF.java?view=markup">
  705. example</a>
  706. shows the usage of the PDF Transcoder, a sub-application within FOP.
  707. It is used to generate a PDF document from an SVG file.
  708. </p>
  709. </section>
  710. <section id="ExampleConcat">
  711. <title>ExampleConcat.java (IF Concatenation example)</title>
  712. <p>
  713. This can be found in the <code>embedding.intermediate</code> package within the
  714. examples and describes how IF can be concatenated to produce a document. Because
  715. IF has been through FOPs layout engine, it should be visually consistent with FO
  716. rendered documents while allowing the user to merge numerous documents together.
  717. </p>
  718. </section>
  719. <section id="example-notes">
  720. <title>Final notes</title>
  721. <p>
  722. These examples should give you an idea of what's possible. It should be easy
  723. to adjust these examples to your needs. Also, if you have other examples that you
  724. think should be added here, please let us know via either the fop-users or fop-dev
  725. mailing lists. Finally, for more help please send your questions to the fop-users
  726. mailing list.
  727. </p>
  728. </section>
  729. </section>
  730. </body>
  731. </document>