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.

FopFactory.java 23KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608
  1. /*
  2. * Copyright 2006 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. import java.io.File;
  19. import java.io.IOException;
  20. import java.io.OutputStream;
  21. import java.net.MalformedURLException;
  22. import java.util.List;
  23. import javax.xml.transform.Source;
  24. import javax.xml.transform.TransformerException;
  25. import javax.xml.transform.URIResolver;
  26. import org.apache.avalon.framework.configuration.Configuration;
  27. import org.apache.avalon.framework.configuration.ConfigurationException;
  28. import org.apache.avalon.framework.configuration.DefaultConfigurationBuilder;
  29. import org.apache.commons.logging.Log;
  30. import org.apache.commons.logging.LogFactory;
  31. import org.apache.fop.fo.ElementMapping;
  32. import org.apache.fop.fo.ElementMappingRegistry;
  33. import org.apache.fop.hyphenation.HyphenationTreeResolver;
  34. import org.apache.fop.image.ImageFactory;
  35. import org.apache.fop.layoutmgr.LayoutManagerMaker;
  36. import org.apache.fop.render.RendererFactory;
  37. import org.apache.fop.render.XMLHandlerRegistry;
  38. import org.apache.fop.util.ContentHandlerFactoryRegistry;
  39. import org.xml.sax.SAXException;
  40. /**
  41. * Factory class which instantiates new Fop and FOUserAgent instances. This class also holds
  42. * environmental information and configuration used by FOP. Information that may potentially be
  43. * different for each rendering run can be found and managed in the FOUserAgent.
  44. */
  45. public class FopFactory {
  46. /** Defines the default source resolution (72dpi) for FOP */
  47. private static final float DEFAULT_SOURCE_RESOLUTION = 72.0f; //dpi
  48. /** Defines the default page-height */
  49. private static final String DEFAULT_PAGE_HEIGHT = "11in";
  50. /** Defines the default page-width */
  51. private static final String DEFAULT_PAGE_WIDTH = "8.26in";
  52. /** logger instance */
  53. private static Log log = LogFactory.getLog(FopFactory.class);
  54. /** Factory for Renderers and FOEventHandlers */
  55. private RendererFactory rendererFactory = new RendererFactory();
  56. /** Registry for XML handlers */
  57. private XMLHandlerRegistry xmlHandlers = new XMLHandlerRegistry();
  58. /** The registry for ElementMapping instances */
  59. private ElementMappingRegistry elementMappingRegistry;
  60. /** The registry for ContentHandlerFactory instance */
  61. private ContentHandlerFactoryRegistry contentHandlerFactoryRegistry
  62. = new ContentHandlerFactoryRegistry();
  63. /** Our default resolver if none is set */
  64. private URIResolver foURIResolver = new FOURIResolver();
  65. /** A user settable URI Resolver */
  66. private URIResolver uriResolver = null;
  67. /** The resolver for user-supplied hyphenation patterns */
  68. private HyphenationTreeResolver hyphResolver;
  69. private ImageFactory imageFactory = new ImageFactory();
  70. /** user configuration */
  71. private Configuration userConfig = null;
  72. /** The base URL for all font URL resolutions */
  73. private String fontBaseURL;
  74. /**
  75. * FOP has the ability, for some FO's, to continue processing even if the
  76. * input XSL violates that FO's content model. This is the default
  77. * behavior for FOP. However, this flag, if set, provides the user the
  78. * ability for FOP to halt on all content model violations if desired.
  79. */
  80. private boolean strictValidation = true;
  81. /** Allows enabling kerning on the base 14 fonts, default is false */
  82. private boolean enableBase14Kerning = false;
  83. /** Source resolution in dpi */
  84. private float sourceResolution = DEFAULT_SOURCE_RESOLUTION;
  85. private String pageHeight = DEFAULT_PAGE_HEIGHT;
  86. private String pageWidth = DEFAULT_PAGE_WIDTH;
  87. /** @see #setBreakIndentInheritanceOnReferenceAreaBoundary(boolean) */
  88. private boolean breakIndentInheritanceOnReferenceAreaBoundary = false;
  89. /** Additional fo.ElementMapping subclasses set by user */
  90. private List additionalElementMappings = null;
  91. /** Optional overriding LayoutManagerMaker */
  92. private LayoutManagerMaker lmMakerOverride = null;
  93. /**
  94. * Main constructor.
  95. */
  96. protected FopFactory() {
  97. this.elementMappingRegistry = new ElementMappingRegistry(this);
  98. }
  99. /**
  100. * Returns a new FopFactory instance.
  101. * @return the requested FopFactory instance.
  102. */
  103. public static FopFactory newInstance() {
  104. return new FopFactory();
  105. }
  106. /**
  107. * Returns a new FOUserAgent instance. Use the FOUserAgent to configure special values that
  108. * are particular to a rendering run. Don't reuse instances over multiple rendering runs but
  109. * instead create a new one each time and reuse the FopFactory.
  110. * @return the newly created FOUserAgent instance initialized with default values
  111. */
  112. public FOUserAgent newFOUserAgent() {
  113. FOUserAgent userAgent = new FOUserAgent(this);
  114. return userAgent;
  115. }
  116. /**
  117. * Returns a new {@link Fop} instance. FOP will be configured with a default user agent
  118. * instance.
  119. * <p>
  120. * MIME types are used to select the output format (ex. "application/pdf" for PDF). You can
  121. * use the constants defined in {@link MimeConstants}.
  122. * @param outputFormat the MIME type of the output format to use (ex. "application/pdf").
  123. * @return the new Fop instance
  124. * @throws FOPException when the constructor fails
  125. */
  126. public Fop newFop(String outputFormat) throws FOPException {
  127. return new Fop(outputFormat, newFOUserAgent());
  128. }
  129. /**
  130. * Returns a new {@link Fop} instance. Use this factory method if you want to configure this
  131. * very rendering run, i.e. if you want to set some metadata like the title and author of the
  132. * document you want to render. In that case, create a new {@link FOUserAgent}
  133. * instance using {@link #newFOUserAgent()}.
  134. * <p>
  135. * MIME types are used to select the output format (ex. "application/pdf" for PDF). You can
  136. * use the constants defined in {@link MimeConstants}.
  137. * @param outputFormat the MIME type of the output format to use (ex. "application/pdf").
  138. * @param userAgent the user agent that will be used to control the rendering run
  139. * @return the new Fop instance
  140. * @throws FOPException when the constructor fails
  141. */
  142. public Fop newFop(String outputFormat, FOUserAgent userAgent) throws FOPException {
  143. if (userAgent == null) {
  144. throw new NullPointerException("The userAgent parameter must not be null!");
  145. }
  146. return new Fop(outputFormat, userAgent);
  147. }
  148. /**
  149. * Returns a new {@link Fop} instance. FOP will be configured with a default user agent
  150. * instance. Use this factory method if your output type requires an output stream.
  151. * <p>
  152. * MIME types are used to select the output format (ex. "application/pdf" for PDF). You can
  153. * use the constants defined in {@link MimeConstants}.
  154. * @param outputFormat the MIME type of the output format to use (ex. "application/pdf").
  155. * @param stream the output stream
  156. * @return the new Fop instance
  157. * @throws FOPException when the constructor fails
  158. */
  159. public Fop newFop(String outputFormat, OutputStream stream) throws FOPException {
  160. return new Fop(outputFormat, newFOUserAgent(), stream);
  161. }
  162. /**
  163. * Returns a new {@link Fop} instance. Use this factory method if your output type
  164. * requires an output stream and you want to configure this very rendering run,
  165. * i.e. if you want to set some metadata like the title and author of the document
  166. * you want to render. In that case, create a new {@link FOUserAgent} instance
  167. * using {@link #newFOUserAgent()}.
  168. * <p>
  169. * MIME types are used to select the output format (ex. "application/pdf" for PDF). You can
  170. * use the constants defined in {@link MimeConstants}.
  171. * @param outputFormat the MIME type of the output format to use (ex. "application/pdf").
  172. * @param userAgent the user agent that will be used to control the rendering run
  173. * @param stream the output stream
  174. * @return the new Fop instance
  175. * @throws FOPException when the constructor fails
  176. */
  177. public Fop newFop(String outputFormat, FOUserAgent userAgent, OutputStream stream)
  178. throws FOPException {
  179. if (userAgent == null) {
  180. throw new NullPointerException("The userAgent parameter must not be null!");
  181. }
  182. return new Fop(outputFormat, userAgent, stream);
  183. }
  184. /**
  185. * Returns a new {@link Fop} instance. Use this factory method if you want to supply your
  186. * own {@link org.apache.fop.render.Renderer Renderer} or
  187. * {@link org.apache.fop.fo.FOEventHandler FOEventHandler}
  188. * instance instead of the default ones created internally by FOP.
  189. * @param userAgent the user agent that will be used to control the rendering run
  190. * @return the new Fop instance
  191. * @throws FOPException when the constructor fails
  192. */
  193. public Fop newFop(FOUserAgent userAgent) throws FOPException {
  194. if (userAgent.getRendererOverride() == null
  195. && userAgent.getFOEventHandlerOverride() == null) {
  196. throw new IllegalStateException("Either the overriding renderer or the overriding"
  197. + " FOEventHandler must be set when this factory method is used!");
  198. }
  199. return newFop(null, userAgent);
  200. }
  201. /** @return the RendererFactory */
  202. public RendererFactory getRendererFactory() {
  203. return this.rendererFactory;
  204. }
  205. /** @return the XML handler registry */
  206. public XMLHandlerRegistry getXMLHandlerRegistry() {
  207. return this.xmlHandlers;
  208. }
  209. /** @return the element mapping registry */
  210. public ElementMappingRegistry getElementMappingRegistry() {
  211. return this.elementMappingRegistry;
  212. }
  213. /** @return the content handler factory registry */
  214. public ContentHandlerFactoryRegistry getContentHandlerFactoryRegistry() {
  215. return this.contentHandlerFactoryRegistry;
  216. }
  217. /** @return the image factory */
  218. public ImageFactory getImageFactory() {
  219. return this.imageFactory;
  220. }
  221. /**
  222. * Add the element mapping with the given class name.
  223. * @param elementMapping the class name representing the element mapping.
  224. */
  225. public void addElementMapping(ElementMapping elementMapping) {
  226. if (additionalElementMappings == null) {
  227. additionalElementMappings = new java.util.ArrayList();
  228. }
  229. additionalElementMappings.add(elementMapping);
  230. }
  231. /**
  232. * Returns the List of user-added ElementMapping class names
  233. * @return List of Strings holding ElementMapping names.
  234. */
  235. public List getAdditionalElementMappings() {
  236. return additionalElementMappings;
  237. }
  238. /**
  239. * Sets an explicit LayoutManagerMaker instance which overrides the one
  240. * defined by the AreaTreeHandler.
  241. * @param lmMaker the LayoutManagerMaker instance
  242. */
  243. public void setLayoutManagerMakerOverride(LayoutManagerMaker lmMaker) {
  244. this.lmMakerOverride = lmMaker;
  245. }
  246. /**
  247. * Returns the overriding LayoutManagerMaker instance, if any.
  248. * @return the overriding LayoutManagerMaker or null
  249. */
  250. public LayoutManagerMaker getLayoutManagerMakerOverride() {
  251. return this.lmMakerOverride;
  252. }
  253. /**
  254. * Sets the font base URL.
  255. * @param fontBaseURL font base URL
  256. */
  257. public void setFontBaseURL(String fontBaseURL) {
  258. this.fontBaseURL = fontBaseURL;
  259. }
  260. /** @return the font base URL */
  261. public String getFontBaseURL() {
  262. return this.fontBaseURL;
  263. }
  264. /**
  265. * Sets the URI Resolver. It is used for resolving factory-level URIs like hyphenation
  266. * patterns and as backup for URI resolution performed during a rendering run.
  267. * @param resolver the new URI resolver
  268. */
  269. public void setURIResolver(URIResolver resolver) {
  270. this.uriResolver = resolver;
  271. }
  272. /**
  273. * Returns the URI Resolver.
  274. * @return the URI Resolver
  275. */
  276. public URIResolver getURIResolver() {
  277. return this.uriResolver;
  278. }
  279. /** @return the HyphenationTreeResolver for resolving user-supplied hyphenation patterns. */
  280. public HyphenationTreeResolver getHyphenationTreeResolver() {
  281. return this.hyphResolver;
  282. }
  283. /**
  284. * Activates strict XSL content model validation for FOP
  285. * Default is false (FOP will continue processing where it can)
  286. * @param validateStrictly true to turn on strict validation
  287. */
  288. public void setStrictValidation(boolean validateStrictly) {
  289. this.strictValidation = validateStrictly;
  290. }
  291. /**
  292. * Returns whether FOP is strictly validating input XSL
  293. * @return true of strict validation turned on, false otherwise
  294. */
  295. public boolean validateStrictly() {
  296. return strictValidation;
  297. }
  298. /**
  299. * @return true if the indent inheritance should be broken when crossing reference area
  300. * boundaries (for more info, see the javadoc for the relative member variable)
  301. */
  302. public boolean isBreakIndentInheritanceOnReferenceAreaBoundary() {
  303. return breakIndentInheritanceOnReferenceAreaBoundary;
  304. }
  305. /**
  306. * Controls whether to enable a feature that breaks indent inheritance when crossing
  307. * reference area boundaries.
  308. * <p>
  309. * This flag controls whether FOP will enable special code that breaks property
  310. * inheritance for start-indent and end-indent when the evaluation of the inherited
  311. * value would cross a reference area. This is described under
  312. * http://wiki.apache.org/xmlgraphics-fop/IndentInheritance as is intended to
  313. * improve interoperability with commercial FO implementations and to produce
  314. * results that are more in line with the expectation of unexperienced FO users.
  315. * Note: Enabling this features violates the XSL specification!
  316. * @param value true to enable the feature
  317. */
  318. public void setBreakIndentInheritanceOnReferenceAreaBoundary(boolean value) {
  319. this.breakIndentInheritanceOnReferenceAreaBoundary = value;
  320. }
  321. /** @return true if kerning on base 14 fonts is enabled */
  322. public boolean isBase14KerningEnabled() {
  323. return this.enableBase14Kerning;
  324. }
  325. /**
  326. * Controls whether kerning is activated on base 14 fonts.
  327. * @param value true if kerning should be activated
  328. */
  329. public void setBase14KerningEnabled(boolean value) {
  330. this.enableBase14Kerning = value;
  331. }
  332. /** @return the resolution for resolution-dependant input */
  333. public float getSourceResolution() {
  334. return this.sourceResolution;
  335. }
  336. /**
  337. * Returns the conversion factor from pixel units to millimeters. This
  338. * depends on the desired source resolution.
  339. * @return float conversion factor
  340. * @see #getSourceResolution()
  341. */
  342. public float getSourcePixelUnitToMillimeter() {
  343. return 25.4f / getSourceResolution();
  344. }
  345. /**
  346. * Sets the source resolution in dpi. This value is used to interpret the pixel size
  347. * of source documents like SVG images and bitmap images without resolution information.
  348. * @param dpi resolution in dpi
  349. */
  350. public void setSourceResolution(int dpi) {
  351. this.sourceResolution = dpi;
  352. }
  353. /**
  354. * Gets the default page-height to use as fallback,
  355. * in case page-height="auto"
  356. *
  357. * @return the page-height, as a String
  358. */
  359. public String getPageHeight() {
  360. return this.pageHeight;
  361. }
  362. /**
  363. * Sets the page-height to use as fallback, in case
  364. * page-height="auto"
  365. *
  366. * @param pageHeight page-height as a String
  367. */
  368. public void setPageHeight(String pageHeight) {
  369. this.pageHeight = pageHeight;
  370. }
  371. /**
  372. * Gets the default page-width to use as fallback,
  373. * in case page-width="auto"
  374. *
  375. * @return the page-width, as a String
  376. */
  377. public String getPageWidth() {
  378. return this.pageWidth;
  379. }
  380. /**
  381. * Sets the page-width to use as fallback, in case
  382. * page-width="auto"
  383. *
  384. * @param pageWidth page-width as a String
  385. */
  386. public void setPageWidth(String pageWidth) {
  387. this.pageWidth = pageWidth;
  388. }
  389. //------------------------------------------- Configuration stuff
  390. /**
  391. * Set the user configuration.
  392. * @param userConfigFile the configuration file
  393. * @throws IOException if an I/O error occurs
  394. * @throws SAXException if a parsing error occurs
  395. */
  396. public void setUserConfig(File userConfigFile)
  397. throws SAXException, IOException {
  398. try {
  399. DefaultConfigurationBuilder cfgBuilder = new DefaultConfigurationBuilder();
  400. setUserConfig(cfgBuilder.buildFromFile(userConfigFile));
  401. } catch (ConfigurationException cfge) {
  402. log.error("Error loading configuration: "
  403. + cfge.getMessage());
  404. }
  405. }
  406. /**
  407. * Set the user configuration from an URI.
  408. * @param uri the URI to the configuration file
  409. * @throws IOException if an I/O error occurs
  410. * @throws SAXException if a parsing error occurs
  411. */
  412. public void setUserConfig(String uri)
  413. throws SAXException, IOException {
  414. try {
  415. DefaultConfigurationBuilder cfgBuilder = new DefaultConfigurationBuilder();
  416. setUserConfig(cfgBuilder.build(uri));
  417. } catch (ConfigurationException cfge) {
  418. log.error("Error loading configuration: "
  419. + cfge.getMessage());
  420. }
  421. }
  422. /**
  423. * Set the user configuration.
  424. * @param userConfig configuration
  425. */
  426. public void setUserConfig(Configuration userConfig) {
  427. this.userConfig = userConfig;
  428. try {
  429. initUserConfig();
  430. } catch (ConfigurationException cfge) {
  431. log.error("Error initializing factory configuration: "
  432. + cfge.getMessage());
  433. }
  434. }
  435. /**
  436. * Get the user configuration.
  437. * @return the user configuration
  438. */
  439. public Configuration getUserConfig() {
  440. return userConfig;
  441. }
  442. /**
  443. * Initializes user agent settings from the user configuration
  444. * file, if present: baseURL, resolution, default page size,...
  445. *
  446. * @throws ConfigurationException when there is an entry that
  447. * misses the required attribute
  448. */
  449. public void initUserConfig() throws ConfigurationException {
  450. log.debug("Initializing User Agent Configuration");
  451. setFontBaseURL(getBaseURLfromConfig(userConfig, "font-base"));
  452. final String hyphBase = getBaseURLfromConfig(userConfig, "hyphenation-base");
  453. if (hyphBase != null) {
  454. this.hyphResolver = new HyphenationTreeResolver() {
  455. public Source resolve(String href) {
  456. return resolveURI(href, hyphBase);
  457. }
  458. };
  459. }
  460. if (userConfig.getChild("source-resolution", false) != null) {
  461. this.sourceResolution
  462. = userConfig.getChild("source-resolution").getValueAsFloat(
  463. DEFAULT_SOURCE_RESOLUTION);
  464. log.info("Source resolution set to: " + sourceResolution
  465. + "dpi (px2mm=" + getSourcePixelUnitToMillimeter() + ")");
  466. }
  467. if (userConfig.getChild("strict-validation", false) != null) {
  468. this.strictValidation = userConfig.getChild("strict-validation").getValueAsBoolean();
  469. }
  470. if (userConfig.getChild("break-indent-inheritance", false) != null) {
  471. this.breakIndentInheritanceOnReferenceAreaBoundary
  472. = userConfig.getChild("break-indent-inheritance").getValueAsBoolean();
  473. }
  474. Configuration pageConfig = userConfig.getChild("default-page-settings");
  475. if (pageConfig.getAttribute("height", null) != null) {
  476. setPageHeight(pageConfig.getAttribute("height"));
  477. log.info("Default page-height set to: " + pageHeight);
  478. }
  479. if (pageConfig.getAttribute("width", null) != null) {
  480. setPageWidth(pageConfig.getAttribute("width"));
  481. log.info("Default page-width set to: " + pageWidth);
  482. }
  483. }
  484. /**
  485. * Retrieves and verifies a base URL.
  486. * @param cfg The Configuration object to retrieve the base URL from
  487. * @param name the element name for the base URL
  488. * @return the requested base URL or null if not available
  489. */
  490. public static String getBaseURLfromConfig(Configuration cfg, String name) {
  491. if (cfg.getChild(name, false) != null) {
  492. try {
  493. String cfgBaseDir = cfg.getChild(name).getValue(null);
  494. if (cfgBaseDir != null) {
  495. File dir = new File(cfgBaseDir);
  496. if (dir.isDirectory()) {
  497. cfgBaseDir = dir.toURL().toExternalForm();
  498. }
  499. }
  500. log.info(name + " set to: " + cfgBaseDir);
  501. return cfgBaseDir;
  502. } catch (MalformedURLException mue) {
  503. log.error("Base URL in user config is malformed!");
  504. }
  505. }
  506. return null;
  507. }
  508. //------------------------------------------- URI resolution
  509. /**
  510. * Attempts to resolve the given URI.
  511. * Will use the configured resolver and if not successful fall back
  512. * to the default resolver.
  513. * @param uri URI to access
  514. * @param base the base URI to resolve against
  515. * @return A {@link javax.xml.transform.Source} object, or null if the URI
  516. * cannot be resolved.
  517. * @see org.apache.fop.apps.FOURIResolver
  518. */
  519. public Source resolveURI(String uri, String base) {
  520. Source source = null;
  521. if (uriResolver != null) {
  522. try {
  523. source = uriResolver.resolve(uri, base);
  524. } catch (TransformerException te) {
  525. log.error("Attempt to resolve URI '" + uri + "' failed: ", te);
  526. }
  527. }
  528. if (source == null) {
  529. // URI Resolver not configured or returned null, use default resolver
  530. try {
  531. source = foURIResolver.resolve(uri, base);
  532. } catch (TransformerException te) {
  533. log.error("Attempt to resolve URI '" + uri + "' failed: ", te);
  534. }
  535. }
  536. return source;
  537. }
  538. }