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.

FOUserAgent.java 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621
  1. /*
  2. * Copyright 1999-2005 The Apache Software Foundation.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  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. package org.apache.fop.apps;
  18. // Java
  19. import java.io.File;
  20. import java.io.IOException;
  21. import java.net.URL;
  22. import java.net.MalformedURLException;
  23. import java.util.Date;
  24. import java.util.List;
  25. import java.util.Map;
  26. import javax.xml.transform.Source;
  27. import javax.xml.transform.TransformerException;
  28. import javax.xml.transform.URIResolver;
  29. // avalon configuration
  30. import org.apache.avalon.framework.configuration.Configuration;
  31. import org.apache.avalon.framework.configuration.ConfigurationException;
  32. // commons logging
  33. import org.apache.commons.logging.Log;
  34. import org.apache.commons.logging.LogFactory;
  35. // FOP
  36. import org.apache.fop.Version;
  37. import org.apache.fop.fo.ElementMapping;
  38. import org.apache.fop.fo.FOEventHandler;
  39. import org.apache.fop.layoutmgr.LayoutManagerMaker;
  40. import org.apache.fop.pdf.PDFEncryptionParams;
  41. import org.apache.fop.render.Renderer;
  42. import org.apache.fop.render.RendererFactory;
  43. import org.apache.fop.render.XMLHandlerRegistry;
  44. /**
  45. * The User Agent for fo.
  46. * This user agent is used by the processing to obtain user configurable
  47. * options.
  48. * <p>
  49. * Renderer specific extensions (that do not produce normal areas on
  50. * the output) will be done like so:
  51. * <br>
  52. * The extension will create an area, custom if necessary
  53. * <br>
  54. * this area will be added to the user agent with a key
  55. * <br>
  56. * the renderer will know keys for particular extensions
  57. * <br>
  58. * eg. bookmarks will be held in a special hierarchical area representing
  59. * the title and bookmark structure
  60. * <br>
  61. * These areas may contain resolvable areas that will be processed
  62. * with other resolvable areas
  63. */
  64. public class FOUserAgent {
  65. /** Defines the default resolution (72dpi) for FOP */
  66. public static final float DEFAULT_RESOLUTION = 72.0f; //dpi
  67. /** Defines the default resolution (72dpi) for FOP */
  68. public static final float DEFAULT_PX2MM = (25.4f / DEFAULT_RESOLUTION); //dpi (=25.4/dpi)
  69. /** Defines the default page-height */
  70. public static final String DEFAULT_PAGE_HEIGHT = "11in";
  71. /** Defines the default page-width */
  72. public static final String DEFAULT_PAGE_WIDTH = "8.26in";
  73. /** Factory for Renderers and FOEventHandlers */
  74. private RendererFactory rendererFactory = new RendererFactory();
  75. /** Registry for XML handlers */
  76. private XMLHandlerRegistry xmlHandlers = new XMLHandlerRegistry();
  77. private String baseURL;
  78. /** A user settable URI Resolver */
  79. private URIResolver uriResolver = null;
  80. /** Our default resolver if none is set */
  81. private URIResolver foURIResolver = new FOURIResolver();
  82. private PDFEncryptionParams pdfEncryptionParams;
  83. private float resolution = DEFAULT_RESOLUTION;
  84. private String pageHeight = DEFAULT_PAGE_HEIGHT;
  85. private String pageWidth = DEFAULT_PAGE_WIDTH;
  86. private Map rendererOptions = new java.util.HashMap();
  87. private File outputFile = null;
  88. private Renderer rendererOverride = null;
  89. private FOEventHandler foEventHandlerOverride = null;
  90. private LayoutManagerMaker lmMakerOverride = null;
  91. /* user configuration */
  92. private Configuration userConfig = null;
  93. private Log log = LogFactory.getLog("FOP");
  94. /* FOP has the ability, for some FO's, to continue processing even if the
  95. * input XSL violates that FO's content model. This is the default
  96. * behavior for FOP. However, this flag, if set, provides the user the
  97. * ability for FOP to halt on all content model violations if desired.
  98. */
  99. private boolean strictValidation = true;
  100. /* Additional fo.ElementMapping subclasses set by user */
  101. private List additionalElementMappings = null;
  102. /** Producer: Metadata element for the system/software that produces
  103. * the document. (Some renderers can store this in the document.)
  104. */
  105. protected String producer = "Apache FOP Version " + Version.getVersion();
  106. /** Creator: Metadata element for the user that created the
  107. * document. (Some renderers can store this in the document.)
  108. */
  109. protected String creator = null;
  110. /** Creation Date: Override of the date the document was created.
  111. * (Some renderers can store this in the document.)
  112. */
  113. protected Date creationDate = null;
  114. /** Author of the content of the document. */
  115. protected String author = null;
  116. /** Title of the document. */
  117. protected String title = null;
  118. /** Set of keywords applicable to this document. */
  119. protected String keywords = null;
  120. /**
  121. * Add the element mapping with the given class name.
  122. * @param elementMapping the class name representing the element mapping.
  123. */
  124. public void addElementMapping(ElementMapping elementMapping) {
  125. if (additionalElementMappings == null) {
  126. additionalElementMappings = new java.util.ArrayList();
  127. }
  128. additionalElementMappings.add(elementMapping);
  129. }
  130. /**
  131. * Returns the List of user-added ElementMapping class names
  132. * @return List of Strings holding ElementMapping names.
  133. */
  134. public List getAdditionalElementMappings() {
  135. return additionalElementMappings;
  136. }
  137. /**
  138. * Sets an explicit renderer to use which overrides the one defined by the
  139. * render type setting.
  140. * @param renderer the Renderer instance to use
  141. */
  142. public void setRendererOverride(Renderer renderer) {
  143. this.rendererOverride = renderer;
  144. }
  145. /**
  146. * Returns the overriding Renderer instance, if any.
  147. * @return the overriding Renderer or null
  148. */
  149. public Renderer getRendererOverride() {
  150. return rendererOverride;
  151. }
  152. /**
  153. * Sets an explicit FOEventHandler instance which overrides the one
  154. * defined by the render type setting.
  155. * @param handler the FOEventHandler instance
  156. */
  157. public void setFOEventHandlerOverride(FOEventHandler handler) {
  158. this.foEventHandlerOverride = handler;
  159. }
  160. /**
  161. * Returns the overriding FOEventHandler instance, if any.
  162. * @return the overriding FOEventHandler or null
  163. */
  164. public FOEventHandler getFOEventHandlerOverride() {
  165. return this.foEventHandlerOverride;
  166. }
  167. /**
  168. * Activates strict XSL content model validation for FOP
  169. * Default is false (FOP will continue processing where it can)
  170. * @param validateStrictly true to turn on strict validation
  171. */
  172. public void setStrictValidation(boolean validateStrictly) {
  173. this.strictValidation = validateStrictly;
  174. }
  175. /**
  176. * Returns whether FOP is strictly validating input XSL
  177. * @return true of strict validation turned on, false otherwise
  178. */
  179. public boolean validateStrictly() {
  180. return strictValidation;
  181. }
  182. /**
  183. * Sets an explicit LayoutManagerMaker instance which overrides the one
  184. * defined by the AreaTreeHandler.
  185. * @param lmMaker the LayoutManagerMaker instance
  186. */
  187. public void setLayoutManagerMakerOverride(LayoutManagerMaker lmMaker) {
  188. this.lmMakerOverride = lmMaker;
  189. }
  190. /**
  191. * Returns the overriding LayoutManagerMaker instance, if any.
  192. * @return the overriding LayoutManagerMaker or null
  193. */
  194. public LayoutManagerMaker getLayoutManagerMakerOverride() {
  195. return this.lmMakerOverride;
  196. }
  197. /**
  198. * Sets the producer of the document.
  199. * @param producer source of document
  200. */
  201. public void setProducer(String producer) {
  202. this.producer = producer;
  203. }
  204. /**
  205. * Returns the producer of the document
  206. * @return producer name
  207. */
  208. public String getProducer() {
  209. return producer;
  210. }
  211. /**
  212. * Sets the creator of the document.
  213. * @param creator of document
  214. */
  215. public void setCreator(String creator) {
  216. this.creator = creator;
  217. }
  218. /**
  219. * Returns the creator of the document
  220. * @return creator name
  221. */
  222. public String getCreator() {
  223. return creator;
  224. }
  225. /**
  226. * Sets the creation date of the document.
  227. * @param creationDate date of document
  228. */
  229. public void setCreationDate(Date creationDate) {
  230. this.creationDate = creationDate;
  231. }
  232. /**
  233. * Returns the creation date of the document
  234. * @return creation date of document
  235. */
  236. public Date getCreationDate() {
  237. return creationDate;
  238. }
  239. /**
  240. * Sets the author of the document.
  241. * @param author of document
  242. */
  243. public void setAuthor(String author) {
  244. this.author = author;
  245. }
  246. /**
  247. * Returns the author of the document
  248. * @return author name
  249. */
  250. public String getAuthor() {
  251. return author;
  252. }
  253. /**
  254. * Sets the title of the document. This will override any title coming from
  255. * an fo:title element.
  256. * @param title of document
  257. */
  258. public void setTitle(String title) {
  259. this.title = title;
  260. }
  261. /**
  262. * Returns the title of the document
  263. * @return title name
  264. */
  265. public String getTitle() {
  266. return title;
  267. }
  268. /**
  269. * Sets the keywords for the document.
  270. * @param keywords for the document
  271. */
  272. public void setKeywords(String keywords) {
  273. this.keywords = keywords;
  274. }
  275. /**
  276. * Returns the keywords for the document
  277. * @return the keywords
  278. */
  279. public String getKeywords() {
  280. return keywords;
  281. }
  282. /**
  283. * Returns the renderer options
  284. * @return renderer options
  285. */
  286. public Map getRendererOptions() {
  287. return rendererOptions;
  288. }
  289. /**
  290. * Set the user configuration.
  291. * @param userConfig configuration
  292. */
  293. public void setUserConfig(Configuration userConfig) {
  294. this.userConfig = userConfig;
  295. try {
  296. initUserConfig();
  297. } catch (ConfigurationException cfge) {
  298. log.error("Error initializing User Agent configuration: "
  299. + cfge.getMessage());
  300. }
  301. }
  302. /**
  303. * Get the user configuration.
  304. * @return the user configuration
  305. */
  306. public Configuration getUserConfig() {
  307. return userConfig;
  308. }
  309. /**
  310. * Initializes user agent settings from the user configuration
  311. * file, if present: baseURL, resolution, default page size,...
  312. *
  313. * @throws ConfigurationException when there is an entry that
  314. * misses the required attribute
  315. */
  316. public void initUserConfig() throws ConfigurationException {
  317. log.info("Initializing User Agent Configuration");
  318. if (userConfig.getChild("base", false) != null) {
  319. try {
  320. String cfgBaseDir = userConfig.getChild("base").getValue(null);
  321. if (cfgBaseDir != null) {
  322. File dir = new File(cfgBaseDir);
  323. if (dir.isDirectory()) {
  324. cfgBaseDir = "file://" + dir.getCanonicalPath()
  325. + System.getProperty("file.separator");
  326. cfgBaseDir = cfgBaseDir.replace(
  327. System.getProperty("file.separator").charAt(0), '/');
  328. } else {
  329. //The next statement is for validation only
  330. new URL(cfgBaseDir);
  331. }
  332. }
  333. setBaseURL(cfgBaseDir);
  334. } catch (MalformedURLException mue) {
  335. log.error("Base URL in user config is malformed!");
  336. } catch (IOException ioe) {
  337. log.error("Error converting relative base directory to absolute URL.");
  338. }
  339. log.info("Base URL set to: " + baseURL);
  340. }
  341. if (userConfig.getChild("pixelToMillimeter", false) != null) {
  342. this.resolution = 25.4f / userConfig.getChild("pixelToMillimeter")
  343. .getAttributeAsFloat("value", DEFAULT_PX2MM);
  344. log.info("resolution set to: " + resolution
  345. + "dpi (px2mm=" + getPixelUnitToMillimeter() + ")");
  346. } else if (userConfig.getChild("resolution", false) != null) {
  347. this.resolution
  348. = 25.4f / userConfig.getChild("resolution").getValueAsFloat(DEFAULT_RESOLUTION);
  349. log.info("resolution set to: " + resolution
  350. + "dpi (px2mm=" + getPixelUnitToMillimeter() + ")");
  351. }
  352. Configuration pageConfig = userConfig.getChild("default-page-settings");
  353. if (pageConfig.getAttribute("height", null) != null) {
  354. setPageHeight(pageConfig.getAttribute("height"));
  355. log.info("Default page-height set to: " + pageHeight);
  356. }
  357. if (pageConfig.getAttribute("width", null) != null) {
  358. setPageWidth(pageConfig.getAttribute("width"));
  359. log.info("Default page-width set to: " + pageWidth);
  360. }
  361. }
  362. /**
  363. * Returns the configuration subtree for a specific renderer.
  364. * @param mimeType MIME type of the renderer
  365. * @return the requested configuration subtree, null if there's no configuration
  366. */
  367. public Configuration getUserRendererConfig (String mimeType) {
  368. if (userConfig == null || mimeType == null) {
  369. return null;
  370. }
  371. Configuration userRendererConfig = null;
  372. Configuration[] cfgs
  373. = userConfig.getChild("renderers").getChildren("renderer");
  374. for (int i = 0; i < cfgs.length; ++i) {
  375. Configuration cfg = cfgs[i];
  376. try {
  377. if (cfg.getAttribute("mime").equals(mimeType)) {
  378. userRendererConfig = cfg;
  379. break;
  380. }
  381. } catch (ConfigurationException e) {
  382. // silently pass over configurations without mime type
  383. }
  384. }
  385. log.debug((userRendererConfig == null ? "No u" : "U")
  386. + "ser configuration found for MIME type " + mimeType);
  387. return userRendererConfig;
  388. }
  389. /**
  390. * Sets the base URL.
  391. * @param baseURL base URL
  392. */
  393. public void setBaseURL(String baseURL) {
  394. this.baseURL = baseURL;
  395. }
  396. /**
  397. * Returns the base URL.
  398. * @return the base URL
  399. */
  400. public String getBaseURL() {
  401. return this.baseURL;
  402. }
  403. /**
  404. * Sets the URI Resolver.
  405. * @param uriResolver the new URI resolver
  406. */
  407. public void setURIResolver(URIResolver uriResolver) {
  408. this.uriResolver = uriResolver;
  409. }
  410. /**
  411. * Returns the URI Resolver.
  412. * @return the URI Resolver
  413. */
  414. public URIResolver getURIResolver() {
  415. return this.uriResolver;
  416. }
  417. /**
  418. * Returns the parameters for PDF encryption.
  419. * @return the PDF encryption parameters, null if not applicable
  420. */
  421. public PDFEncryptionParams getPDFEncryptionParams() {
  422. return pdfEncryptionParams;
  423. }
  424. /**
  425. * Sets the parameters for PDF encryption.
  426. * @param pdfEncryptionParams the PDF encryption parameters, null to
  427. * disable PDF encryption
  428. */
  429. public void setPDFEncryptionParams(PDFEncryptionParams pdfEncryptionParams) {
  430. this.pdfEncryptionParams = pdfEncryptionParams;
  431. }
  432. /**
  433. * Attempts to resolve the given URI.
  434. * Will use the configured resolver and if not successful fall back
  435. * to the default resolver.
  436. * @param uri URI to access
  437. * @return A {@link javax.xml.transform.Source} object, or null if the URI
  438. * cannot be resolved.
  439. * @see org.apache.fop.apps.FOURIResolver
  440. */
  441. public Source resolveURI(String uri) {
  442. Source source = null;
  443. if (uriResolver != null) {
  444. try {
  445. source = uriResolver.resolve(uri, getBaseURL());
  446. } catch (TransformerException te) {
  447. log.error("Attempt to resolve URI '" + uri + "' failed: ", te);
  448. }
  449. }
  450. if (source == null) {
  451. // URI Resolver not configured or returned null, use default resolver
  452. try {
  453. source = foURIResolver.resolve(uri, getBaseURL());
  454. } catch (TransformerException te) {
  455. log.error("Attempt to resolve URI '" + uri + "' failed: ", te);
  456. }
  457. }
  458. return source;
  459. }
  460. /**
  461. * Sets the output File.
  462. * @param f the output File
  463. */
  464. public void setOutputFile(File f) {
  465. this.outputFile = f;
  466. }
  467. /**
  468. * Gets the output File.
  469. * @return the output File
  470. */
  471. public File getOutputFile() {
  472. return outputFile;
  473. }
  474. /**
  475. * Returns the conversion factor from pixel units to millimeters. This
  476. * depends on the desired reolution.
  477. * @return float conversion factor
  478. */
  479. public float getPixelUnitToMillimeter() {
  480. return 25.4f / this.resolution;
  481. }
  482. /** @return the resolution for resolution-dependant output */
  483. public float getResolution() {
  484. return this.resolution;
  485. }
  486. /**
  487. * Sets the resolution in dpi.
  488. * @param dpi resolution in dpi
  489. */
  490. public void setResolution(int dpi) {
  491. this.resolution = dpi;
  492. }
  493. /**
  494. * Gets the default page-height to use as fallback,
  495. * in case page-height="auto"
  496. *
  497. * @return the page-height, as a String
  498. */
  499. public String getPageHeight() {
  500. return this.pageHeight;
  501. }
  502. /**
  503. * Sets the page-height to use as fallback, in case
  504. * page-height="auto"
  505. *
  506. * @param pageHeight page-height as a String
  507. */
  508. public void setPageHeight(String pageHeight) {
  509. this.pageHeight = pageHeight;
  510. }
  511. /**
  512. * Gets the default page-width to use as fallback,
  513. * in case page-width="auto"
  514. *
  515. * @return the page-width, as a String
  516. */
  517. public String getPageWidth() {
  518. return this.pageWidth;
  519. }
  520. /**
  521. * Sets the page-width to use as fallback, in case
  522. * page-width="auto"
  523. *
  524. * @param pageWidth page-width as a String
  525. */
  526. public void setPageWidth(String pageWidth) {
  527. this.pageWidth = pageWidth;
  528. }
  529. /**
  530. * If to create hot links to footnotes and before floats.
  531. * @return True if hot links should be created
  532. */
  533. /* TODO This method is never referenced!
  534. public boolean linkToFootnotes() {
  535. return true;
  536. }*/
  537. /**
  538. * @return the RendererFactory
  539. */
  540. public RendererFactory getRendererFactory() {
  541. return this.rendererFactory;
  542. }
  543. /**
  544. * @return the XML handler registry
  545. */
  546. public XMLHandlerRegistry getXMLHandlerRegistry() {
  547. return this.xmlHandlers;
  548. }
  549. }