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.

ResourceHandler.java 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  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.render.ps;
  19. import java.awt.geom.Dimension2D;
  20. import java.awt.image.RenderedImage;
  21. import java.awt.geom.Rectangle2D;
  22. import java.io.IOException;
  23. import java.io.InputStream;
  24. import java.io.OutputStream;
  25. import java.util.Iterator;
  26. import java.util.Map;
  27. import java.util.Set;
  28. import org.apache.xmlgraphics.image.loader.ImageException;
  29. import org.apache.xmlgraphics.image.loader.ImageFlavor;
  30. import org.apache.xmlgraphics.image.loader.ImageInfo;
  31. import org.apache.xmlgraphics.image.loader.ImageManager;
  32. import org.apache.xmlgraphics.image.loader.ImageSessionContext;
  33. import org.apache.xmlgraphics.image.loader.impl.ImageGraphics2D;
  34. import org.apache.xmlgraphics.image.loader.impl.ImageRawCCITTFax;
  35. import org.apache.xmlgraphics.image.loader.impl.ImageRawEPS;
  36. import org.apache.xmlgraphics.image.loader.impl.ImageRawJPEG;
  37. import org.apache.xmlgraphics.image.loader.impl.ImageRawStream;
  38. import org.apache.xmlgraphics.image.loader.impl.ImageRendered;
  39. import org.apache.xmlgraphics.image.loader.impl.ImageXMLDOM;
  40. import org.apache.xmlgraphics.image.loader.util.ImageUtil;
  41. import org.apache.xmlgraphics.ps.DSCConstants;
  42. import org.apache.xmlgraphics.ps.FormGenerator;
  43. import org.apache.xmlgraphics.ps.ImageEncoder;
  44. import org.apache.xmlgraphics.ps.ImageFormGenerator;
  45. import org.apache.xmlgraphics.ps.PSGenerator;
  46. import org.apache.xmlgraphics.ps.PSProcSets;
  47. import org.apache.xmlgraphics.ps.dsc.DSCException;
  48. import org.apache.xmlgraphics.ps.dsc.DSCFilter;
  49. import org.apache.xmlgraphics.ps.dsc.DSCParser;
  50. import org.apache.xmlgraphics.ps.dsc.DSCParserConstants;
  51. import org.apache.xmlgraphics.ps.dsc.DefaultNestedDocumentHandler;
  52. import org.apache.xmlgraphics.ps.dsc.ResourceTracker;
  53. import org.apache.xmlgraphics.ps.dsc.events.DSCComment;
  54. import org.apache.xmlgraphics.ps.dsc.events.DSCCommentBoundingBox;
  55. import org.apache.xmlgraphics.ps.dsc.events.DSCCommentDocumentNeededResources;
  56. import org.apache.xmlgraphics.ps.dsc.events.DSCCommentDocumentSuppliedResources;
  57. import org.apache.xmlgraphics.ps.dsc.events.DSCCommentHiResBoundingBox;
  58. import org.apache.xmlgraphics.ps.dsc.events.DSCCommentLanguageLevel;
  59. import org.apache.xmlgraphics.ps.dsc.events.DSCCommentPage;
  60. import org.apache.xmlgraphics.ps.dsc.events.DSCCommentPages;
  61. import org.apache.xmlgraphics.ps.dsc.events.DSCEvent;
  62. import org.apache.xmlgraphics.ps.dsc.events.DSCHeaderComment;
  63. import org.apache.xmlgraphics.ps.dsc.events.PostScriptComment;
  64. import org.apache.xmlgraphics.ps.dsc.tools.DSCTools;
  65. import org.apache.fop.apps.FOUserAgent;
  66. import org.apache.fop.fonts.FontInfo;
  67. /**
  68. * This class is used when two-pass production is used to generate the PostScript file (setting
  69. * "optimize-resources"). It uses the DSC parser from XML Graphics Commons to go over the
  70. * temporary file generated by the PSRenderer and adds all used fonts and images as resources
  71. * to the PostScript file.
  72. */
  73. public class ResourceHandler implements DSCParserConstants, PSSupportedFlavors {
  74. /**
  75. * Rewrites the temporary PostScript file generated by PSRenderer adding all needed resources
  76. * (fonts and images).
  77. * @param userAgent the FO user agent
  78. * @param in the InputStream for the temporary PostScript file
  79. * @param out the OutputStream to write the finished file to
  80. * @param fontInfo the font information
  81. * @param resTracker the resource tracker to use
  82. * @param formResources Contains all forms used by this document (maintained by PSRenderer)
  83. * @param pageCount the number of pages (given here because PSRenderer writes an "(atend)")
  84. * @param documentBoundingBox the document's bounding box
  85. * (given here because PSRenderer writes an "(atend)")
  86. * @throws DSCException If there's an error in the DSC structure of the PS file
  87. * @throws IOException In case of an I/O error
  88. */
  89. public static void process(FOUserAgent userAgent, InputStream in, OutputStream out,
  90. FontInfo fontInfo, ResourceTracker resTracker, Map formResources,
  91. int pageCount, Rectangle2D documentBoundingBox)
  92. throws DSCException, IOException {
  93. DSCParser parser = new DSCParser(in);
  94. PSGenerator gen = new PSGenerator(out);
  95. parser.setNestedDocumentHandler(new DefaultNestedDocumentHandler(gen));
  96. //Skip DSC header
  97. DSCHeaderComment header = DSCTools.checkAndSkipDSC30Header(parser);
  98. header.generate(gen);
  99. parser.setFilter(new DSCFilter() {
  100. private final Set filtered = new java.util.HashSet();
  101. {
  102. //We rewrite those as part of the processing
  103. filtered.add(DSCConstants.PAGES);
  104. filtered.add(DSCConstants.BBOX);
  105. filtered.add(DSCConstants.HIRES_BBOX);
  106. filtered.add(DSCConstants.DOCUMENT_NEEDED_RESOURCES);
  107. filtered.add(DSCConstants.DOCUMENT_SUPPLIED_RESOURCES);
  108. }
  109. public boolean accept(DSCEvent event) {
  110. if (event.isDSCComment()) {
  111. //Filter %%Pages which we add manually from a parameter
  112. return !(filtered.contains(event.asDSCComment().getName()));
  113. } else {
  114. return true;
  115. }
  116. }
  117. });
  118. //Get PostScript language level (may be missing)
  119. while (true) {
  120. DSCEvent event = parser.nextEvent();
  121. if (event == null) {
  122. reportInvalidDSC();
  123. }
  124. if (DSCTools.headerCommentsEndHere(event)) {
  125. //Set number of pages
  126. DSCCommentPages pages = new DSCCommentPages(pageCount);
  127. pages.generate(gen);
  128. new DSCCommentBoundingBox(documentBoundingBox).generate(gen);
  129. new DSCCommentHiResBoundingBox(documentBoundingBox).generate(gen);
  130. PSFontUtils.determineSuppliedFonts(resTracker, fontInfo, fontInfo.getUsedFonts());
  131. registerSuppliedForms(resTracker, formResources);
  132. //Supplied Resources
  133. DSCCommentDocumentSuppliedResources supplied
  134. = new DSCCommentDocumentSuppliedResources(
  135. resTracker.getDocumentSuppliedResources());
  136. supplied.generate(gen);
  137. //Needed Resources
  138. DSCCommentDocumentNeededResources needed
  139. = new DSCCommentDocumentNeededResources(
  140. resTracker.getDocumentNeededResources());
  141. needed.generate(gen);
  142. //Write original comment that ends the header comments
  143. event.generate(gen);
  144. break;
  145. }
  146. if (event.isDSCComment()) {
  147. DSCComment comment = event.asDSCComment();
  148. if (DSCConstants.LANGUAGE_LEVEL.equals(comment.getName())) {
  149. DSCCommentLanguageLevel level = (DSCCommentLanguageLevel)comment;
  150. gen.setPSLevel(level.getLanguageLevel());
  151. }
  152. }
  153. event.generate(gen);
  154. }
  155. //Skip to the FOPFontSetup
  156. PostScriptComment fontSetupPlaceholder = parser.nextPSComment("FOPFontSetup", gen);
  157. if (fontSetupPlaceholder == null) {
  158. throw new DSCException("Didn't find %FOPFontSetup comment in stream");
  159. }
  160. PSFontUtils.writeFontDict(gen, fontInfo, fontInfo.getUsedFonts());
  161. generateForms(resTracker, userAgent, formResources, gen);
  162. //Skip the prolog and to the first page
  163. DSCComment pageOrTrailer = parser.nextDSCComment(DSCConstants.PAGE, gen);
  164. if (pageOrTrailer == null) {
  165. throw new DSCException("Page expected, but none found");
  166. }
  167. //Process individual pages (and skip as necessary)
  168. while (true) {
  169. DSCCommentPage page = (DSCCommentPage)pageOrTrailer;
  170. page.generate(gen);
  171. pageOrTrailer = DSCTools.nextPageOrTrailer(parser, gen);
  172. if (pageOrTrailer == null) {
  173. reportInvalidDSC();
  174. } else if (!DSCConstants.PAGE.equals(pageOrTrailer.getName())) {
  175. pageOrTrailer.generate(gen);
  176. break;
  177. }
  178. }
  179. //Write the rest
  180. while (parser.hasNext()) {
  181. DSCEvent event = parser.nextEvent();
  182. event.generate(gen);
  183. }
  184. }
  185. private static void reportInvalidDSC() throws DSCException {
  186. throw new DSCException("File is not DSC-compliant: Unexpected end of file");
  187. }
  188. private static void registerSuppliedForms(ResourceTracker resTracker, Map formResources)
  189. throws IOException {
  190. if (formResources == null) {
  191. return;
  192. }
  193. Iterator iter = formResources.values().iterator();
  194. while (iter.hasNext()) {
  195. PSImageFormResource form = (PSImageFormResource)iter.next();
  196. resTracker.registerSuppliedResource(form);
  197. }
  198. }
  199. private static void generateForms(ResourceTracker resTracker, FOUserAgent userAgent,
  200. Map formResources, PSGenerator gen) throws IOException {
  201. if (formResources == null) {
  202. return;
  203. }
  204. Iterator iter = formResources.values().iterator();
  205. while (iter.hasNext()) {
  206. PSImageFormResource form = (PSImageFormResource)iter.next();
  207. final String uri = form.getImageURI();
  208. ImageManager manager = userAgent.getFactory().getImageManager();
  209. ImageInfo info = null;
  210. try {
  211. ImageSessionContext sessionContext = userAgent.getImageSessionContext();
  212. info = manager.getImageInfo(uri, sessionContext);
  213. ImageFlavor[] flavors;
  214. if (gen.getPSLevel() >= 3) {
  215. flavors = LEVEL_3_FLAVORS_FORM;
  216. } else {
  217. flavors = LEVEL_2_FLAVORS_FORM;
  218. }
  219. Map hints = ImageUtil.getDefaultHints(sessionContext);
  220. org.apache.xmlgraphics.image.loader.Image img = manager.getImage(
  221. info, flavors, hints, sessionContext);
  222. String imageDescription = info.getMimeType() + " " + info.getOriginalURI();
  223. final Dimension2D dimensionsPt = info.getSize().getDimensionPt();
  224. final Dimension2D dimensionsMpt = info.getSize().getDimensionMpt();
  225. if (img instanceof ImageGraphics2D) {
  226. final ImageGraphics2D imageG2D = (ImageGraphics2D)img;
  227. FormGenerator formGen = new FormGenerator(
  228. form.getName(), imageDescription, dimensionsPt) {
  229. protected void generatePaintProc(PSGenerator gen)
  230. throws IOException {
  231. gen.getResourceTracker().notifyResourceUsageOnPage(
  232. PSProcSets.EPS_PROCSET);
  233. gen.writeln("BeginEPSF");
  234. PSGraphics2DAdapter adapter = new PSGraphics2DAdapter(gen, false);
  235. adapter.paintImage(imageG2D.getGraphics2DImagePainter(),
  236. null,
  237. 0, 0,
  238. (int)Math.round(dimensionsMpt.getWidth()),
  239. (int)Math.round(dimensionsMpt.getHeight()));
  240. gen.writeln("EndEPSF");
  241. }
  242. };
  243. formGen.generate(gen);
  244. } else if (img instanceof ImageRendered) {
  245. ImageRendered imgRend = (ImageRendered)img;
  246. RenderedImage ri = imgRend.getRenderedImage();
  247. FormGenerator formGen = new ImageFormGenerator(
  248. form.getName(), imageDescription,
  249. info.getSize().getDimensionPt(),
  250. ri, false);
  251. formGen.generate(gen);
  252. } else if (img instanceof ImageXMLDOM) {
  253. throw new UnsupportedOperationException(
  254. "Embedding an ImageXMLDOM as a form isn't supported, yet");
  255. } else if (img instanceof ImageRawStream) {
  256. final ImageRawStream raw = (ImageRawStream)img;
  257. if (raw instanceof ImageRawEPS) {
  258. final ImageRawEPS eps = (ImageRawEPS)raw;
  259. throw new UnsupportedOperationException(
  260. "Embedding EPS as forms isn't supported, yet");
  261. /*
  262. InputStream in = eps.createInputStream();
  263. try {
  264. FormGenerator formGen = new EPSFormGenerator(form.getName(),
  265. imageDescription, dimensions, in);
  266. formGen.generate(gen);
  267. } finally {
  268. IOUtils.closeQuietly(in);
  269. }*/
  270. } else if (raw instanceof ImageRawCCITTFax) {
  271. ImageRawCCITTFax jpeg = (ImageRawCCITTFax)raw;
  272. ImageEncoder encoder = new ImageEncoderCCITTFax(jpeg);
  273. FormGenerator formGen = new ImageFormGenerator(
  274. form.getName(), imageDescription,
  275. info.getSize().getDimensionPt(),
  276. info.getSize().getDimensionPx(),
  277. encoder,
  278. jpeg.getColorSpace(), 1, false);
  279. formGen.generate(gen);
  280. } else if (raw instanceof ImageRawJPEG) {
  281. ImageRawJPEG jpeg = (ImageRawJPEG)raw;
  282. ImageEncoder encoder = new ImageEncoderJPEG(jpeg);
  283. FormGenerator formGen = new ImageFormGenerator(
  284. form.getName(), imageDescription,
  285. info.getSize().getDimensionPt(),
  286. info.getSize().getDimensionPx(),
  287. encoder,
  288. jpeg.getColorSpace(), jpeg.isInverted());
  289. formGen.generate(gen);
  290. } else {
  291. throw new UnsupportedOperationException("Unsupported raw image: " + info);
  292. }
  293. } else {
  294. throw new UnsupportedOperationException("Unsupported image type: " + img);
  295. }
  296. } catch (ImageException ie) {
  297. throw new IOException("Error while generating form for image: " + ie.getMessage());
  298. }
  299. }
  300. }
  301. private static FormGenerator createMissingForm(String formName, final Dimension2D dimensions) {
  302. FormGenerator formGen = new FormGenerator(formName, null, dimensions) {
  303. protected void generatePaintProc(PSGenerator gen) throws IOException {
  304. gen.writeln("0 setgray");
  305. gen.writeln("0 setlinewidth");
  306. String w = gen.formatDouble(dimensions.getWidth());
  307. String h = gen.formatDouble(dimensions.getHeight());
  308. gen.writeln(w + " " + h + " scale");
  309. gen.writeln("0 0 1 1 rectstroke");
  310. gen.writeln("newpath");
  311. gen.writeln("0 0 moveto");
  312. gen.writeln("1 1 lineto");
  313. gen.writeln("stroke");
  314. gen.writeln("newpath");
  315. gen.writeln("0 1 moveto");
  316. gen.writeln("1 0 lineto");
  317. gen.writeln("stroke");
  318. }
  319. };
  320. return formGen;
  321. }
  322. }