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 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  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. import java.io.File;
  20. import java.io.IOException;
  21. import java.io.InputStream;
  22. import java.io.OutputStream;
  23. import java.net.URI;
  24. import java.security.AccessController;
  25. import java.security.PrivilegedAction;
  26. import java.util.HashMap;
  27. import java.util.Map;
  28. import java.util.Set;
  29. import org.xml.sax.SAXException;
  30. import org.apache.commons.logging.Log;
  31. import org.apache.commons.logging.LogFactory;
  32. import org.apache.xmlgraphics.image.loader.ImageContext;
  33. import org.apache.xmlgraphics.image.loader.ImageManager;
  34. import org.apache.xmlgraphics.image.loader.impl.AbstractImageSessionContext.FallbackResolver;
  35. import org.apache.xmlgraphics.util.UnitConv;
  36. import org.apache.fop.apps.io.InternalResourceResolver;
  37. import org.apache.fop.apps.io.ResourceResolverFactory;
  38. import org.apache.fop.configuration.Configuration;
  39. import org.apache.fop.fo.ElementMapping;
  40. import org.apache.fop.fo.ElementMappingRegistry;
  41. import org.apache.fop.fonts.FontManager;
  42. import org.apache.fop.hyphenation.HyphenationTreeCache;
  43. import org.apache.fop.layoutmgr.LayoutManagerMaker;
  44. import org.apache.fop.render.ImageHandlerRegistry;
  45. import org.apache.fop.render.RendererConfig;
  46. import org.apache.fop.render.RendererConfig.RendererConfigParser;
  47. import org.apache.fop.render.RendererFactory;
  48. import org.apache.fop.render.XMLHandlerRegistry;
  49. import org.apache.fop.util.ColorSpaceCache;
  50. import org.apache.fop.util.ContentHandlerFactoryRegistry;
  51. /**
  52. * Factory class which instantiates new Fop and FOUserAgent instances. This
  53. * class also holds environmental information and configuration used by FOP.
  54. * Information that may potentially be different for each renderingq run can be
  55. * found and managed in the FOUserAgent.
  56. */
  57. public final class FopFactory implements ImageContext {
  58. /** logger instance */
  59. private static Log log = LogFactory.getLog(FopFactory.class);
  60. /** Factory for Renderers and FOEventHandlers */
  61. private final RendererFactory rendererFactory;
  62. /** Registry for XML handlers */
  63. private final XMLHandlerRegistry xmlHandlers;
  64. /** Registry for image handlers */
  65. private final ImageHandlerRegistry imageHandlers;
  66. /** The registry for ElementMapping instances */
  67. private final ElementMappingRegistry elementMappingRegistry;
  68. /** The registry for ContentHandlerFactory instance */
  69. private final ContentHandlerFactoryRegistry contentHandlerFactoryRegistry
  70. = new ContentHandlerFactoryRegistry();
  71. private final ColorSpaceCache colorSpaceCache;
  72. private final FopFactoryConfig config;
  73. private final InternalResourceResolver resolver;
  74. private final Map<String, RendererConfig> rendererConfig;
  75. private HyphenationTreeCache hyphenationTreeCache;
  76. private FopFactory(FopFactoryConfig config) {
  77. this.config = config;
  78. this.resolver = ResourceResolverFactory.createInternalResourceResolver(config.getBaseURI(),
  79. config.getResourceResolver());
  80. this.elementMappingRegistry = new ElementMappingRegistry(this);
  81. this.colorSpaceCache = new ColorSpaceCache(resolver);
  82. this.rendererFactory = new RendererFactory(config.preferRenderer());
  83. this.xmlHandlers = new XMLHandlerRegistry();
  84. this.imageHandlers = new ImageHandlerRegistry();
  85. rendererConfig = new HashMap<String, RendererConfig>();
  86. }
  87. /**
  88. * Map of configured names of hyphenation pattern file names: ll_CC => name
  89. */
  90. private Map<String, String> hyphPatNames;
  91. /**
  92. * FOP has the ability, for some FO's, to continue processing even if the
  93. * input XSL violates that FO's content model. This is the default
  94. * behavior for FOP. However, this flag, if set, provides the user the
  95. * ability for FOP to halt on all content model violations if desired.
  96. * Returns a new FopFactory instance that is configured using the {@link FopFactoryConfig} object.
  97. *
  98. * @param config the fop configuration
  99. * @return the requested FopFactory instance.
  100. */
  101. public static FopFactory newInstance(FopFactoryConfig config) {
  102. return new FopFactory(config);
  103. }
  104. /**
  105. * Returns a new FopFactory instance that is configured using the {@link FopFactoryConfig} object that
  106. * is created when the fopConf is parsed.
  107. *
  108. * @param fopConf the fop conf configuration file to parse
  109. * @return the requested FopFactory instance.
  110. * @throws IOException
  111. * @throws SAXException
  112. */
  113. public static FopFactory newInstance(File fopConf) throws SAXException, IOException {
  114. return new FopConfParser(fopConf).getFopFactoryBuilder().build();
  115. }
  116. /**
  117. * Returns a new FopFactory instance that is configured only by the default configuration
  118. * parameters.
  119. *
  120. * @param baseURI the base URI to resolve resource URIs against
  121. * @return the requested FopFactory instance.
  122. */
  123. public static FopFactory newInstance(final URI baseURI) {
  124. return AccessController.doPrivileged(
  125. new PrivilegedAction<FopFactory>() {
  126. public FopFactory run() {
  127. return new FopFactoryBuilder(baseURI).build();
  128. }
  129. }
  130. );
  131. }
  132. /**
  133. * Returns a new FopFactory instance that is configured using the {@link FopFactoryConfig} object that
  134. * is created when the fopConf is parsed.
  135. *
  136. * @param baseURI the base URI to resolve resource URIs against
  137. * @param confStream the fop conf configuration stream to parse
  138. * @return the requested FopFactory instance.
  139. * @throws SAXException
  140. * @throws IOException
  141. */
  142. public static FopFactory newInstance(final URI baseURI, final InputStream confStream) throws SAXException,
  143. IOException {
  144. Object action = AccessController.doPrivileged(
  145. new PrivilegedAction<Object>() {
  146. public Object run() {
  147. try {
  148. return new FopConfParser(confStream, baseURI).getFopFactoryBuilder().build();
  149. } catch (SAXException | IOException e) {
  150. return e;
  151. }
  152. }
  153. }
  154. );
  155. if (action instanceof SAXException) {
  156. throw (SAXException) action;
  157. }
  158. if (action instanceof IOException) {
  159. throw (IOException) action;
  160. }
  161. return (FopFactory) action;
  162. }
  163. /**
  164. * Returns a new FOUserAgent instance. Use the FOUserAgent to configure special values that
  165. * are particular to a rendering run. Don't reuse instances over multiple rendering runs but
  166. * instead create a new one each time and reuse the FopFactory.
  167. * @return the newly created FOUserAgent instance initialized with default values
  168. */
  169. public FOUserAgent newFOUserAgent() {
  170. FOUserAgent userAgent = new FOUserAgent(this, resolver);
  171. return userAgent;
  172. }
  173. boolean isComplexScriptFeaturesEnabled() {
  174. return config.isComplexScriptFeaturesEnabled();
  175. }
  176. /**
  177. * Returns a new {@link Fop} instance. FOP will be configured with a default user agent
  178. * instance.
  179. * <p>
  180. * MIME types are used to select the output format (ex. "application/pdf" for PDF). You can
  181. * use the constants defined in {@link MimeConstants}.
  182. * @param outputFormat the MIME type of the output format to use (ex. "application/pdf").
  183. * @return the new Fop instance
  184. * @throws FOPException when the constructor fails
  185. */
  186. public Fop newFop(String outputFormat) throws FOPException {
  187. return newFOUserAgent().newFop(outputFormat);
  188. }
  189. /**
  190. * Returns a new {@link Fop} instance. Use this factory method if you want to configure this
  191. * very rendering run, i.e. if you want to set some metadata like the title and author of the
  192. * document you want to render. In that case, create a new {@link FOUserAgent}
  193. * instance using {@link #newFOUserAgent()}.
  194. * <p>
  195. * MIME types are used to select the output format (ex. "application/pdf" for PDF). You can
  196. * use the constants defined in {@link MimeConstants}.
  197. * @param outputFormat the MIME type of the output format to use (ex. "application/pdf").
  198. * @param userAgent the user agent that will be used to control the rendering run
  199. * @return the new Fop instance
  200. * @throws FOPException when the constructor fails
  201. */
  202. public Fop newFop(String outputFormat, FOUserAgent userAgent) throws FOPException {
  203. return userAgent.newFop(outputFormat, null);
  204. }
  205. boolean isTableBorderOverpaint() {
  206. return config.isTableBorderOverpaint();
  207. }
  208. boolean isSimpleLineBreaking() {
  209. return config.isSimpleLineBreaking();
  210. }
  211. boolean isSkipPagePositionOnlyAllowed() {
  212. return config.isSkipPagePositionOnlyAllowed();
  213. }
  214. /**
  215. * Returns a new {@link Fop} instance. FOP will be configured with a default user agent
  216. * instance. Use this factory method if your output type requires an output stream.
  217. * <p>
  218. * MIME types are used to select the output format (ex. "application/pdf" for PDF). You can
  219. * use the constants defined in {@link MimeConstants}.
  220. * @param outputFormat the MIME type of the output format to use (ex. "application/pdf").
  221. * @param stream the output stream
  222. * @return the new Fop instance
  223. * @throws FOPException when the constructor fails
  224. */
  225. public Fop newFop(String outputFormat, OutputStream stream) throws FOPException {
  226. return newFOUserAgent().newFop(outputFormat, stream);
  227. }
  228. /**
  229. * Returns a new {@link Fop} instance. Use this factory method if your output type
  230. * requires an output stream and you want to configure this very rendering run,
  231. * i.e. if you want to set some metadata like the title and author of the document
  232. * you want to render. In that case, create a new {@link FOUserAgent} instance
  233. * using {@link #newFOUserAgent()}.
  234. * <p>
  235. * MIME types are used to select the output format (ex. "application/pdf" for PDF). You can
  236. * use the constants defined in {@link MimeConstants}.
  237. * @param outputFormat the MIME type of the output format to use (ex. "application/pdf").
  238. * @param userAgent the user agent that will be used to control the rendering run
  239. * @param stream the output stream
  240. * @return the new Fop instance
  241. * @throws FOPException when the constructor fails
  242. */
  243. public Fop newFop(String outputFormat, FOUserAgent userAgent, OutputStream stream)
  244. throws FOPException {
  245. return userAgent.newFop(outputFormat, stream);
  246. }
  247. /**
  248. * Returns a new {@link Fop} instance. Use this factory method if you want to supply your
  249. * own {@link org.apache.fop.render.Renderer Renderer} or
  250. * {@link org.apache.fop.fo.FOEventHandler FOEventHandler}
  251. * instance instead of the default ones created internally by FOP.
  252. * @param userAgent the user agent that will be used to control the rendering run
  253. * @return the new Fop instance
  254. * @throws FOPException when the constructor fails
  255. */
  256. public Fop newFop(FOUserAgent userAgent) throws FOPException {
  257. if (userAgent.getRendererOverride() == null
  258. && userAgent.getFOEventHandlerOverride() == null
  259. && userAgent.getDocumentHandlerOverride() == null) {
  260. throw new IllegalStateException("An overriding renderer,"
  261. + " FOEventHandler or IFDocumentHandler must be set on the user agent"
  262. + " when this factory method is used!");
  263. }
  264. return newFop(null, userAgent);
  265. }
  266. /** @return the RendererFactory */
  267. public RendererFactory getRendererFactory() {
  268. return this.rendererFactory;
  269. }
  270. /** @return the XML handler registry */
  271. public XMLHandlerRegistry getXMLHandlerRegistry() {
  272. return this.xmlHandlers;
  273. }
  274. /** @return the image handler registry */
  275. public ImageHandlerRegistry getImageHandlerRegistry() {
  276. return this.imageHandlers;
  277. }
  278. /** @return the element mapping registry */
  279. public ElementMappingRegistry getElementMappingRegistry() {
  280. return this.elementMappingRegistry;
  281. }
  282. /** @return the content handler factory registry */
  283. public ContentHandlerFactoryRegistry getContentHandlerFactoryRegistry() {
  284. return this.contentHandlerFactoryRegistry;
  285. }
  286. /**
  287. * Returns the renderer configuration object for a specific renderer given the parser and
  288. * configuration to read. The renderer config is cached such that the {@link Configuration} is
  289. * only parsed once per renderer, per FopFactory instance.
  290. *
  291. * @param userAgent the user agent
  292. * @param cfg the configuration to be parsed
  293. * @param configCreator the parser that creates the config object
  294. * @return the config object
  295. * @throws FOPException when an error occurs while creating the configuration object
  296. */
  297. synchronized RendererConfig getRendererConfig(FOUserAgent userAgent, Configuration cfg,
  298. RendererConfigParser configCreator) throws FOPException {
  299. RendererConfig config = rendererConfig.get(configCreator.getMimeType());
  300. if (config == null) {
  301. try {
  302. config = configCreator.build(userAgent, cfg);
  303. rendererConfig.put(configCreator.getMimeType(), config);
  304. } catch (Exception e) {
  305. throw new FOPException(e);
  306. }
  307. }
  308. return config;
  309. }
  310. /**
  311. * Add the element mapping with the given class name.
  312. * @param elementMapping the class name representing the element mapping.
  313. */
  314. public void addElementMapping(ElementMapping elementMapping) {
  315. this.elementMappingRegistry.addElementMapping(elementMapping);
  316. }
  317. /**
  318. * Returns whether accessibility is enabled.
  319. * @return true if accessibility is enabled
  320. */
  321. boolean isAccessibilityEnabled() {
  322. return config.isAccessibilityEnabled();
  323. }
  324. boolean isKeepEmptyTags() {
  325. return config.isKeepEmptyTags();
  326. }
  327. /** @see FopFactoryConfig#getImageManager() */
  328. public ImageManager getImageManager() {
  329. return config.getImageManager();
  330. }
  331. /** @see FopFactoryConfig#getLayoutManagerMakerOverride() */
  332. public LayoutManagerMaker getLayoutManagerMakerOverride() {
  333. return config.getLayoutManagerMakerOverride();
  334. }
  335. /** @see FopFactoryConfig#getHyphenationPatternNames() */
  336. public Map<String, String> getHyphenationPatternNames() {
  337. return config.getHyphenationPatternNames();
  338. }
  339. /** @see FopFactoryConfig#validateStrictly() */
  340. public boolean validateStrictly() {
  341. return config.validateStrictly();
  342. }
  343. /** @see FopFactoryConfig#isBreakIndentInheritanceOnReferenceAreaBoundary() */
  344. public boolean isBreakIndentInheritanceOnReferenceAreaBoundary() {
  345. return config.isBreakIndentInheritanceOnReferenceAreaBoundary();
  346. }
  347. /** @see FopFactoryConfig#getSourceResolution() */
  348. public float getSourceResolution() {
  349. return config.getSourceResolution();
  350. }
  351. /** @see FopFactoryConfig#getTargetResolution() */
  352. public float getTargetResolution() {
  353. return config.getTargetResolution();
  354. }
  355. public InternalResourceResolver getHyphenationResourceResolver() {
  356. return config.getHyphenationResourceResolver();
  357. }
  358. /**
  359. * Returns the conversion factor from pixel units to millimeters. This
  360. * depends on the desired source resolution.
  361. * @return float conversion factor
  362. * @see #getSourceResolution()
  363. */
  364. public float getSourcePixelUnitToMillimeter() {
  365. return UnitConv.IN2MM / getSourceResolution();
  366. }
  367. /**
  368. * Returns the conversion factor from pixel units to millimeters. This
  369. * depends on the desired target resolution.
  370. * @return float conversion factor
  371. * @see #getTargetResolution()
  372. */
  373. public float getTargetPixelUnitToMillimeter() {
  374. return 25.4f / getTargetResolution();
  375. }
  376. /** @see FopFactoryConfig#getPageHeight() */
  377. public String getPageHeight() {
  378. return config.getPageHeight();
  379. }
  380. /** @see FopFactoryConfig#getPageWidth() */
  381. public String getPageWidth() {
  382. return config.getPageWidth();
  383. }
  384. /** @see FopFactoryConfig#isNamespaceIgnored(String) */
  385. public boolean isNamespaceIgnored(String namespaceURI) {
  386. return config.isNamespaceIgnored(namespaceURI);
  387. }
  388. /** @see FopFactoryConfig#getIgnoredNamespaces() */
  389. public Set<String> getIgnoredNamespace() {
  390. return config.getIgnoredNamespaces();
  391. }
  392. /**
  393. * Get the user configuration.
  394. * @return the user configuration
  395. */
  396. public Configuration getUserConfig() {
  397. return config.getUserConfig();
  398. }
  399. /** @see FopFactoryConfig#validateUserConfigStrictly() */
  400. public boolean validateUserConfigStrictly() {
  401. return config.validateUserConfigStrictly();
  402. }
  403. /** @see FopFactoryConfig#getFontManager() */
  404. public FontManager getFontManager() {
  405. return config.getFontManager();
  406. }
  407. /** @see FopFactoryConfig#getFallbackResolver() */
  408. FallbackResolver getFallbackResolver() {
  409. return config.getFallbackResolver();
  410. }
  411. /**
  412. * Returns the color space cache for this instance.
  413. * <p>
  414. * Note: this method should not be considered as part of FOP's external API.
  415. * @return the color space cache
  416. */
  417. public ColorSpaceCache getColorSpaceCache() {
  418. return this.colorSpaceCache;
  419. }
  420. public HyphenationTreeCache getHyphenationTreeCache() {
  421. if (hyphenationTreeCache == null) {
  422. hyphenationTreeCache = new HyphenationTreeCache();
  423. }
  424. return hyphenationTreeCache;
  425. }
  426. }