Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

FOUserAgent.java 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  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.apps;
  19. // Java
  20. import java.io.File;
  21. import java.util.Date;
  22. import java.util.Map;
  23. import javax.xml.transform.Source;
  24. import javax.xml.transform.TransformerException;
  25. import javax.xml.transform.URIResolver;
  26. import org.apache.commons.logging.Log;
  27. import org.apache.commons.logging.LogFactory;
  28. import org.apache.xmlgraphics.image.loader.ImageContext;
  29. import org.apache.xmlgraphics.image.loader.ImageSessionContext;
  30. import org.apache.xmlgraphics.image.loader.impl.AbstractImageSessionContext;
  31. import org.apache.fop.Version;
  32. import org.apache.fop.events.DefaultEventBroadcaster;
  33. import org.apache.fop.events.Event;
  34. import org.apache.fop.events.EventBroadcaster;
  35. import org.apache.fop.events.EventProducer;
  36. import org.apache.fop.events.FOPEventListenerProxy;
  37. import org.apache.fop.events.LoggingEventListener;
  38. import org.apache.fop.fo.FOEventHandler;
  39. import org.apache.fop.render.Renderer;
  40. import org.apache.fop.render.RendererFactory;
  41. import org.apache.fop.render.XMLHandlerRegistry;
  42. /**
  43. * This is the user agent for FOP.
  44. * It is the entity through which you can interact with the XSL-FO processing and is
  45. * used by the processing to obtain user configurable options.
  46. * <p>
  47. * Renderer specific extensions (that do not produce normal areas on
  48. * the output) will be done like so:
  49. * <br>
  50. * The extension will create an area, custom if necessary
  51. * <br>
  52. * this area will be added to the user agent with a key
  53. * <br>
  54. * the renderer will know keys for particular extensions
  55. * <br>
  56. * eg. bookmarks will be held in a special hierarchical area representing
  57. * the title and bookmark structure
  58. * <br>
  59. * These areas may contain resolvable areas that will be processed
  60. * with other resolvable areas
  61. */
  62. public class FOUserAgent {
  63. /** Defines the default target resolution (72dpi) for FOP */
  64. public static final float DEFAULT_TARGET_RESOLUTION
  65. = FopFactoryConfigurator.DEFAULT_TARGET_RESOLUTION;
  66. private static Log log = LogFactory.getLog("FOP");
  67. private FopFactory factory;
  68. /**
  69. * The base URL for all URL resolutions, especially for
  70. * external-graphics.
  71. */
  72. private String base = null;
  73. /** The base URL for all font URL resolutions. */
  74. private String fontBase = null;
  75. /** A user settable URI Resolver */
  76. private URIResolver uriResolver = null;
  77. private float targetResolution = FopFactoryConfigurator.DEFAULT_TARGET_RESOLUTION;
  78. private Map rendererOptions = new java.util.HashMap();
  79. private File outputFile = null;
  80. private Renderer rendererOverride = null;
  81. private FOEventHandler foEventHandlerOverride = null;
  82. private boolean locatorEnabled = true; // true by default (for error messages).
  83. private EventBroadcaster eventBroadcaster = new FOPEventBroadcaster();
  84. /** Producer: Metadata element for the system/software that produces
  85. * the document. (Some renderers can store this in the document.)
  86. */
  87. protected String producer = "Apache FOP Version " + Version.getVersion();
  88. /** Creator: Metadata element for the user that created the
  89. * document. (Some renderers can store this in the document.)
  90. */
  91. protected String creator = null;
  92. /** Creation Date: Override of the date the document was created.
  93. * (Some renderers can store this in the document.)
  94. */
  95. protected Date creationDate = null;
  96. /** Author of the content of the document. */
  97. protected String author = null;
  98. /** Title of the document. */
  99. protected String title = null;
  100. /** Set of keywords applicable to this document. */
  101. protected String keywords = null;
  102. private ImageSessionContext imageSessionContext = new AbstractImageSessionContext() {
  103. public ImageContext getParentContext() {
  104. return getFactory();
  105. }
  106. public float getTargetResolution() {
  107. return FOUserAgent.this.getTargetResolution();
  108. }
  109. public Source resolveURI(String uri) {
  110. return FOUserAgent.this.resolveURI(uri);
  111. }
  112. };
  113. /**
  114. * Main constructor. <b>This constructor should not be called directly. Please use the
  115. * methods from FopFactory to construct FOUserAgent instances!</b>
  116. * @param factory the factory that provides environment-level information
  117. * @see org.apache.fop.apps.FopFactory
  118. */
  119. public FOUserAgent(FopFactory factory) {
  120. if (factory == null) {
  121. throw new NullPointerException("The factory parameter must not be null");
  122. }
  123. this.factory = factory;
  124. setBaseURL(factory.getBaseURL());
  125. setFontBaseURL(factory.getFontBaseURL());
  126. setTargetResolution(factory.getTargetResolution());
  127. }
  128. /** @return the associated FopFactory instance */
  129. public FopFactory getFactory() {
  130. return this.factory;
  131. }
  132. // ---------------------------------------------- rendering-run dependent stuff
  133. /**
  134. * Sets an explicit renderer to use which overrides the one defined by the
  135. * render type setting.
  136. * @param renderer the Renderer instance to use
  137. */
  138. public void setRendererOverride(Renderer renderer) {
  139. this.rendererOverride = renderer;
  140. }
  141. /**
  142. * Returns the overriding Renderer instance, if any.
  143. * @return the overriding Renderer or null
  144. */
  145. public Renderer getRendererOverride() {
  146. return rendererOverride;
  147. }
  148. /**
  149. * Sets an explicit FOEventHandler instance which overrides the one
  150. * defined by the render type setting.
  151. * @param handler the FOEventHandler instance
  152. */
  153. public void setFOEventHandlerOverride(FOEventHandler handler) {
  154. this.foEventHandlerOverride = handler;
  155. }
  156. /**
  157. * Returns the overriding FOEventHandler instance, if any.
  158. * @return the overriding FOEventHandler or null
  159. */
  160. public FOEventHandler getFOEventHandlerOverride() {
  161. return this.foEventHandlerOverride;
  162. }
  163. /**
  164. * Sets the producer of the document.
  165. * @param producer source of document
  166. */
  167. public void setProducer(String producer) {
  168. this.producer = producer;
  169. }
  170. /**
  171. * Returns the producer of the document
  172. * @return producer name
  173. */
  174. public String getProducer() {
  175. return producer;
  176. }
  177. /**
  178. * Sets the creator of the document.
  179. * @param creator of document
  180. */
  181. public void setCreator(String creator) {
  182. this.creator = creator;
  183. }
  184. /**
  185. * Returns the creator of the document
  186. * @return creator name
  187. */
  188. public String getCreator() {
  189. return creator;
  190. }
  191. /**
  192. * Sets the creation date of the document.
  193. * @param creationDate date of document
  194. */
  195. public void setCreationDate(Date creationDate) {
  196. this.creationDate = creationDate;
  197. }
  198. /**
  199. * Returns the creation date of the document
  200. * @return creation date of document
  201. */
  202. public Date getCreationDate() {
  203. return creationDate;
  204. }
  205. /**
  206. * Sets the author of the document.
  207. * @param author of document
  208. */
  209. public void setAuthor(String author) {
  210. this.author = author;
  211. }
  212. /**
  213. * Returns the author of the document
  214. * @return author name
  215. */
  216. public String getAuthor() {
  217. return author;
  218. }
  219. /**
  220. * Sets the title of the document. This will override any title coming from
  221. * an fo:title element.
  222. * @param title of document
  223. */
  224. public void setTitle(String title) {
  225. this.title = title;
  226. }
  227. /**
  228. * Returns the title of the document
  229. * @return title name
  230. */
  231. public String getTitle() {
  232. return title;
  233. }
  234. /**
  235. * Sets the keywords for the document.
  236. * @param keywords for the document
  237. */
  238. public void setKeywords(String keywords) {
  239. this.keywords = keywords;
  240. }
  241. /**
  242. * Returns the keywords for the document
  243. * @return the keywords
  244. */
  245. public String getKeywords() {
  246. return keywords;
  247. }
  248. /**
  249. * Returns the renderer options
  250. * @return renderer options
  251. */
  252. public Map getRendererOptions() {
  253. return rendererOptions;
  254. }
  255. /**
  256. * Sets the base URL.
  257. * @param baseUrl base URL
  258. */
  259. public void setBaseURL(String baseUrl) {
  260. this.base = baseUrl;
  261. }
  262. /**
  263. * sets font base URL
  264. * @param fontBaseUrl font base URL
  265. */
  266. public void setFontBaseURL(String fontBaseUrl) {
  267. this.fontBase = fontBaseUrl;
  268. }
  269. /**
  270. * Returns the base URL.
  271. * @return the base URL
  272. */
  273. public String getBaseURL() {
  274. return this.base;
  275. }
  276. /**
  277. * Sets the URI Resolver.
  278. * @param resolver the new URI resolver
  279. */
  280. public void setURIResolver(URIResolver resolver) {
  281. this.uriResolver = resolver;
  282. }
  283. /**
  284. * Returns the URI Resolver.
  285. * @return the URI Resolver
  286. */
  287. public URIResolver getURIResolver() {
  288. return this.uriResolver;
  289. }
  290. /**
  291. * Attempts to resolve the given URI.
  292. * Will use the configured resolver and if not successful fall back
  293. * to the default resolver.
  294. * @param uri URI to access
  295. * @return A {@link javax.xml.transform.Source} object, or null if the URI
  296. * cannot be resolved.
  297. * @see org.apache.fop.apps.FOURIResolver
  298. */
  299. public Source resolveURI(String uri) {
  300. return resolveURI(uri, getBaseURL());
  301. }
  302. /**
  303. * Attempts to resolve the given URI.
  304. * Will use the configured resolver and if not successful fall back
  305. * to the default resolver.
  306. * @param href URI to access
  307. * @param base the base URI to resolve against
  308. * @return A {@link javax.xml.transform.Source} object, or null if the URI
  309. * cannot be resolved.
  310. * @see org.apache.fop.apps.FOURIResolver
  311. */
  312. public Source resolveURI(String href, String base) {
  313. Source source = null;
  314. //RFC 2397 data URLs don't need to be resolved, just decode them through FOP's default
  315. //URIResolver.
  316. boolean bypassURIResolution = href.startsWith("data:");
  317. if (!bypassURIResolution && uriResolver != null) {
  318. try {
  319. source = uriResolver.resolve(href, base);
  320. } catch (TransformerException te) {
  321. log.error("Attempt to resolve URI '" + href + "' failed: ", te);
  322. }
  323. }
  324. if (source == null) {
  325. // URI Resolver not configured or returned null, use default resolver from the factory
  326. source = getFactory().resolveURI(href, base);
  327. }
  328. return source;
  329. }
  330. /**
  331. * Sets the output File.
  332. * @param f the output File
  333. */
  334. public void setOutputFile(File f) {
  335. this.outputFile = f;
  336. }
  337. /**
  338. * Gets the output File.
  339. * @return the output File
  340. */
  341. public File getOutputFile() {
  342. return outputFile;
  343. }
  344. /**
  345. * Returns the conversion factor from pixel units to millimeters. This
  346. * depends on the desired target resolution.
  347. * @return float conversion factor
  348. * @see #getTargetResolution()
  349. */
  350. public float getTargetPixelUnitToMillimeter() {
  351. return 25.4f / this.targetResolution;
  352. }
  353. /** @return the resolution for resolution-dependant output */
  354. public float getTargetResolution() {
  355. return this.targetResolution;
  356. }
  357. /**
  358. * Sets the target resolution in dpi. This value defines the target resolution of
  359. * bitmap images generated by the bitmap renderers (such as the TIFF renderer) and of
  360. * bitmap images generated by filter effects in Apache Batik.
  361. * @param dpi resolution in dpi
  362. */
  363. public void setTargetResolution(float dpi) {
  364. this.targetResolution = dpi;
  365. if (log.isDebugEnabled()) {
  366. log.debug("target-resolution set to: " + targetResolution
  367. + "dpi (px2mm=" + getTargetPixelUnitToMillimeter() + ")");
  368. }
  369. }
  370. /**
  371. * Sets the target resolution in dpi. This value defines the target resolution of
  372. * bitmap images generated by the bitmap renderers (such as the TIFF renderer) and of
  373. * bitmap images generated by filter effects in Apache Batik.
  374. * @param dpi resolution in dpi
  375. */
  376. public void setTargetResolution(int dpi) {
  377. setTargetResolution((float)dpi);
  378. }
  379. /**
  380. * Returns the image session context for the image package.
  381. * @return the ImageSessionContext instance for this rendering run
  382. */
  383. public ImageSessionContext getImageSessionContext() {
  384. return this.imageSessionContext;
  385. }
  386. // ---------------------------------------------- environment-level stuff
  387. // (convenience access to FopFactory methods)
  388. /** @return the font base URL */
  389. public String getFontBaseURL() {
  390. return fontBase != null ? fontBase : getBaseURL();
  391. }
  392. /**
  393. * Returns the conversion factor from pixel units to millimeters. This
  394. * depends on the desired source resolution.
  395. * @return float conversion factor
  396. * @see #getSourceResolution()
  397. */
  398. public float getSourcePixelUnitToMillimeter() {
  399. return getFactory().getSourcePixelUnitToMillimeter();
  400. }
  401. /** @return the resolution for resolution-dependant input */
  402. public float getSourceResolution() {
  403. return getFactory().getSourceResolution();
  404. }
  405. /**
  406. * Gets the default page-height to use as fallback,
  407. * in case page-height="auto"
  408. *
  409. * @return the page-height, as a String
  410. * @see FopFactory#getPageHeight()
  411. */
  412. public String getPageHeight() {
  413. return getFactory().getPageHeight();
  414. }
  415. /**
  416. * Gets the default page-width to use as fallback,
  417. * in case page-width="auto"
  418. *
  419. * @return the page-width, as a String
  420. * @see FopFactory#getPageWidth()
  421. */
  422. public String getPageWidth() {
  423. return getFactory().getPageWidth();
  424. }
  425. /**
  426. * Returns whether FOP is strictly validating input XSL
  427. * @return true of strict validation turned on, false otherwise
  428. * @see FopFactory#validateStrictly()
  429. */
  430. public boolean validateStrictly() {
  431. return getFactory().validateStrictly();
  432. }
  433. /**
  434. * @return true if the indent inheritance should be broken when crossing reference area
  435. * boundaries (for more info, see the javadoc for the relative member variable)
  436. * @see FopFactory#isBreakIndentInheritanceOnReferenceAreaBoundary()
  437. */
  438. public boolean isBreakIndentInheritanceOnReferenceAreaBoundary() {
  439. return getFactory().isBreakIndentInheritanceOnReferenceAreaBoundary();
  440. }
  441. /**
  442. * @return the RendererFactory
  443. */
  444. public RendererFactory getRendererFactory() {
  445. return getFactory().getRendererFactory();
  446. }
  447. /**
  448. * @return the XML handler registry
  449. */
  450. public XMLHandlerRegistry getXMLHandlerRegistry() {
  451. return getFactory().getXMLHandlerRegistry();
  452. }
  453. /**
  454. * Controls the use of SAXLocators to provide location information in error
  455. * messages.
  456. *
  457. * @param enableLocator <code>false</code> if SAX Locators should be disabled
  458. */
  459. public void setLocatorEnabled(boolean enableLocator) {
  460. locatorEnabled = enableLocator;
  461. }
  462. /**
  463. * Checks if the use of Locators is enabled
  464. * @return true if context information should be stored on each node in the FO tree.
  465. */
  466. public boolean isLocatorEnabled() {
  467. return locatorEnabled;
  468. }
  469. /**
  470. * Returns the event broadcaster that control events sent inside a processing run. Clients
  471. * can register event listeners with the event broadcaster to listen for events that occur
  472. * while a document is being processed.
  473. * @return the event broadcaster.
  474. */
  475. public EventBroadcaster getEventBroadcaster() {
  476. return this.eventBroadcaster;
  477. }
  478. private class FOPEventBroadcaster extends DefaultEventBroadcaster {
  479. private FOPEventListenerProxy rootListener;
  480. public FOPEventBroadcaster() {
  481. this.rootListener = new FOPEventListenerProxy(
  482. this.listeners, FOUserAgent.this);
  483. }
  484. /** {@inheritDoc} */
  485. public void broadcastEvent(Event event) {
  486. rootListener.processEvent(event);
  487. }
  488. /** {@inheritDoc} */
  489. protected EventProducer createProxyFor(Class clazz) {
  490. if (!this.listeners.hasEventListeners()) {
  491. //Backwards-compatibility: Make sure at least the LoggingEventListener is plugged
  492. //in so no events are just silently swallowed.
  493. addEventListener(
  494. new LoggingEventListener(LogFactory.getLog(FOUserAgent.class)));
  495. }
  496. return super.createProxyFor(clazz);
  497. }
  498. }
  499. }