Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

AFPRenderer.java 35KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915
  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.afp;
  19. import java.awt.Color;
  20. import java.awt.Point;
  21. import java.awt.Rectangle;
  22. import java.awt.geom.AffineTransform;
  23. import java.awt.geom.Rectangle2D;
  24. import java.awt.image.RenderedImage;
  25. import java.io.FileNotFoundException;
  26. import java.io.IOException;
  27. import java.io.OutputStream;
  28. import java.io.UnsupportedEncodingException;
  29. import java.util.Iterator;
  30. import java.util.List;
  31. import java.util.Map;
  32. import org.apache.xmlgraphics.image.loader.ImageException;
  33. import org.apache.xmlgraphics.image.loader.ImageFlavor;
  34. import org.apache.xmlgraphics.image.loader.ImageInfo;
  35. import org.apache.xmlgraphics.image.loader.ImageManager;
  36. import org.apache.xmlgraphics.image.loader.ImageSessionContext;
  37. import org.apache.xmlgraphics.image.loader.util.ImageUtil;
  38. import org.apache.xmlgraphics.ps.ImageEncodingHelper;
  39. import org.apache.fop.ResourceEventProducer;
  40. import org.apache.fop.afp.AFPBorderPainter;
  41. import org.apache.fop.afp.AFPDataObjectInfo;
  42. import org.apache.fop.afp.AFPDitheredRectanglePainter;
  43. import org.apache.fop.afp.AFPEventProducer;
  44. import org.apache.fop.afp.AFPPaintingState;
  45. import org.apache.fop.afp.AFPRectanglePainter;
  46. import org.apache.fop.afp.AFPResourceLevelDefaults;
  47. import org.apache.fop.afp.AFPResourceManager;
  48. import org.apache.fop.afp.AFPTextDataInfo;
  49. import org.apache.fop.afp.AFPUnitConverter;
  50. import org.apache.fop.afp.AbstractAFPPainter;
  51. import org.apache.fop.afp.BorderPaintingInfo;
  52. import org.apache.fop.afp.DataStream;
  53. import org.apache.fop.afp.RectanglePaintingInfo;
  54. import org.apache.fop.afp.fonts.AFPFont;
  55. import org.apache.fop.afp.fonts.AFPFontAttributes;
  56. import org.apache.fop.afp.fonts.AFPFontCollection;
  57. import org.apache.fop.afp.fonts.AFPPageFonts;
  58. import org.apache.fop.afp.fonts.CharacterSet;
  59. import org.apache.fop.afp.modca.PageObject;
  60. import org.apache.fop.afp.modca.ResourceObject;
  61. import org.apache.fop.afp.util.DefaultFOPResourceAccessor;
  62. import org.apache.fop.afp.util.ResourceAccessor;
  63. import org.apache.fop.apps.FOPException;
  64. import org.apache.fop.apps.FOUserAgent;
  65. import org.apache.fop.apps.MimeConstants;
  66. import org.apache.fop.area.CTM;
  67. import org.apache.fop.area.OffDocumentExtensionAttachment;
  68. import org.apache.fop.area.OffDocumentItem;
  69. import org.apache.fop.area.PageSequence;
  70. import org.apache.fop.area.PageViewport;
  71. import org.apache.fop.area.Trait;
  72. import org.apache.fop.area.inline.Image;
  73. import org.apache.fop.area.inline.Leader;
  74. import org.apache.fop.area.inline.TextArea;
  75. import org.apache.fop.datatypes.URISpecification;
  76. import org.apache.fop.fo.extensions.ExtensionAttachment;
  77. import org.apache.fop.fonts.Font;
  78. import org.apache.fop.fonts.FontCollection;
  79. import org.apache.fop.fonts.FontInfo;
  80. import org.apache.fop.fonts.FontManager;
  81. import org.apache.fop.render.AbstractPathOrientedRenderer;
  82. import org.apache.fop.render.Graphics2DAdapter;
  83. import org.apache.fop.render.RendererContext;
  84. import org.apache.fop.render.afp.extensions.AFPElementMapping;
  85. import org.apache.fop.render.afp.extensions.AFPExtensionAttachment;
  86. import org.apache.fop.render.afp.extensions.AFPIncludeFormMap;
  87. import org.apache.fop.render.afp.extensions.AFPInvokeMediumMap;
  88. import org.apache.fop.render.afp.extensions.AFPPageOverlay;
  89. import org.apache.fop.render.afp.extensions.AFPPageSetup;
  90. /**
  91. * This is an implementation of a FOP Renderer that renders areas to AFP.
  92. * <p>
  93. * A renderer is primarily designed to convert a given area tree into the output
  94. * document format. It should be able to produce pages and fill the pages with
  95. * the text and graphical content. Usually the output is sent to an output
  96. * stream. Some output formats may support extra information that is not
  97. * available from the area tree or depends on the destination of the document.
  98. * Each renderer is given an area tree to render to its output format. The area
  99. * tree is simply a representation of the pages and the placement of text and
  100. * graphical objects on those pages.
  101. * </p>
  102. * <p>
  103. * The renderer will be given each page as it is ready and an output stream to
  104. * write the data out. All pages are supplied in the order they appear in the
  105. * document. In order to save memory it is possible to render the pages out of
  106. * order. Any page that is not ready to be rendered is setup by the renderer
  107. * first so that it can reserve a space or reference for when the page is ready
  108. * to be rendered.The renderer is responsible for managing the output format and
  109. * associated data and flow.
  110. * </p>
  111. * <p>
  112. * Each renderer is totally responsible for its output format. Because font
  113. * metrics (and therefore layout) are obtained in two different ways depending
  114. * on the renderer, the renderer actually sets up the fonts being used. The font
  115. * metrics are used during the layout process to determine the size of
  116. * characters.
  117. * </p>
  118. * <p>
  119. * The render context is used by handlers. It contains information about the
  120. * current state of the renderer, such as the page, the position, and any other
  121. * miscellaneous objects that are required to draw into the page.
  122. * </p>
  123. * <p>
  124. * A renderer is created by implementing the Renderer interface. However, the
  125. * AbstractRenderer does most of what is needed, including iterating through the
  126. * tree parts, so it is this that is extended. This means that this object only
  127. * need to implement the basic functionality such as text, images, and lines.
  128. * AbstractRenderer's methods can easily be overridden to handle things in a
  129. * different way or do some extra processing.
  130. * </p>
  131. * <p>
  132. * The relevant AreaTree structures that will need to be rendered are Page,
  133. * Viewport, Region, Span, Block, Line, Inline. A renderer implementation
  134. * renders each individual page, clips and aligns child areas to a viewport,
  135. * handle all types of inline area, text, image etc and draws various lines and
  136. * rectangles.
  137. * </p>
  138. *
  139. * Note: There are specific extensions that have been added to the FO. They are
  140. * specific to their location within the FO and have to be processed accordingly
  141. * (ie. at the start or end of the page).
  142. *
  143. */
  144. public class AFPRenderer extends AbstractPathOrientedRenderer implements AFPCustomizable {
  145. private static final int X = 0;
  146. private static final int Y = 1;
  147. /** the resource manager */
  148. private AFPResourceManager resourceManager;
  149. /** the painting state */
  150. private final AFPPaintingState paintingState;
  151. /** unit converter */
  152. private final AFPUnitConverter unitConv;
  153. /** the line painter */
  154. private AFPBorderPainter borderPainter;
  155. /** the map of page segments */
  156. private final Map/*<String,String>*/pageSegmentMap
  157. = new java.util.HashMap/*<String,String>*/();
  158. /** the map of saved incomplete pages */
  159. private final Map pages = new java.util.HashMap/*<PageViewport,PageObject>*/();
  160. /** the AFP datastream */
  161. private DataStream dataStream;
  162. /** the image handler registry */
  163. private final AFPImageHandlerRegistry imageHandlerRegistry;
  164. private AbstractAFPPainter rectanglePainter;
  165. /** the shading mode for filled rectangles */
  166. private AFPShadingMode shadingMode = AFPShadingMode.COLOR;
  167. /** medium map referenced used on previous page **/
  168. private String lastMediumMap;
  169. /**
  170. * Constructor for AFPRenderer.
  171. */
  172. public AFPRenderer() {
  173. super();
  174. this.imageHandlerRegistry = new AFPImageHandlerRegistry();
  175. this.resourceManager = new AFPResourceManager();
  176. this.paintingState = new AFPPaintingState();
  177. this.unitConv = paintingState.getUnitConverter();
  178. }
  179. /** {@inheritDoc} */
  180. public void setupFontInfo(FontInfo inFontInfo) {
  181. this.fontInfo = inFontInfo;
  182. FontManager fontManager = userAgent.getFactory().getFontManager();
  183. FontCollection[] fontCollections = new FontCollection[] {
  184. new AFPFontCollection(userAgent.getEventBroadcaster(), getFontList())
  185. };
  186. fontManager.setup(getFontInfo(), fontCollections);
  187. }
  188. /** {@inheritDoc} */
  189. public void setUserAgent(FOUserAgent agent) {
  190. super.setUserAgent(agent);
  191. }
  192. /** {@inheritDoc} */
  193. public void startRenderer(OutputStream outputStream) throws IOException {
  194. paintingState.setColor(Color.WHITE);
  195. this.dataStream = resourceManager.createDataStream(paintingState, outputStream);
  196. this.borderPainter = new AFPBorderPainter(paintingState, dataStream);
  197. this.rectanglePainter = createRectanglePainter();
  198. dataStream.startDocument();
  199. }
  200. AbstractAFPPainter createRectanglePainter() {
  201. if (AFPShadingMode.DITHERED.equals(this.shadingMode)) {
  202. return new AFPDitheredRectanglePainter(
  203. this.paintingState, this.dataStream, this.resourceManager);
  204. } else {
  205. return new AFPRectanglePainter(
  206. this.paintingState, this.dataStream);
  207. }
  208. }
  209. /** {@inheritDoc} */
  210. public void stopRenderer() throws IOException {
  211. dataStream.endDocument();
  212. resourceManager.writeToStream();
  213. resourceManager = null;
  214. }
  215. /** {@inheritDoc} */
  216. public void startPageSequence(PageSequence pageSequence) {
  217. super.startPageSequence(pageSequence);
  218. try {
  219. dataStream.startPageGroup();
  220. } catch (IOException e) {
  221. log.error(e.getMessage());
  222. }
  223. if (pageSequence.hasExtensionAttachments()) {
  224. for (Iterator iter = pageSequence.getExtensionAttachments().iterator();
  225. iter.hasNext();) {
  226. ExtensionAttachment attachment = (ExtensionAttachment)iter.next();
  227. if (attachment instanceof AFPInvokeMediumMap) {
  228. AFPInvokeMediumMap imm = (AFPInvokeMediumMap)attachment;
  229. String mediumMap = imm.getName();
  230. if (mediumMap != null) {
  231. dataStream.createInvokeMediumMap(mediumMap);
  232. }
  233. } else if (attachment instanceof AFPPageSetup) {
  234. AFPPageSetup aps = (AFPPageSetup)attachment;
  235. String name = aps.getName();
  236. String value = aps.getValue();
  237. dataStream.createTagLogicalElement(name, value);
  238. }
  239. }
  240. }
  241. }
  242. /** {@inheritDoc} */
  243. public boolean supportsOutOfOrder() {
  244. return false;
  245. }
  246. /** {@inheritDoc} */
  247. public void preparePage(PageViewport page) {
  248. int pageRotation = paintingState.getPageRotation();
  249. int pageWidth = paintingState.getPageWidth();
  250. int pageHeight = paintingState.getPageHeight();
  251. int resolution = paintingState.getResolution();
  252. dataStream.startPage(pageWidth, pageHeight, pageRotation,
  253. resolution, resolution);
  254. renderPageObjectExtensions(page);
  255. PageObject currentPage = dataStream.savePage();
  256. pages.put(page, currentPage);
  257. }
  258. /** {@inheritDoc} */
  259. public void processOffDocumentItem(OffDocumentItem odi) {
  260. if (odi instanceof OffDocumentExtensionAttachment) {
  261. ExtensionAttachment attachment = ((OffDocumentExtensionAttachment)odi).getAttachment();
  262. if (attachment != null) {
  263. if (AFPExtensionAttachment.CATEGORY.equals(attachment.getCategory())) {
  264. if (attachment instanceof AFPIncludeFormMap) {
  265. handleIncludeFormMap((AFPIncludeFormMap)attachment);
  266. }
  267. }
  268. }
  269. }
  270. }
  271. private void handleIncludeFormMap(AFPIncludeFormMap formMap) {
  272. ResourceAccessor accessor = new DefaultFOPResourceAccessor(
  273. getUserAgent(), null, null);
  274. try {
  275. this.resourceManager.createIncludedResource(formMap.getName(),
  276. formMap.getSrc(), accessor,
  277. ResourceObject.TYPE_FORMDEF);
  278. } catch (IOException ioe) {
  279. AFPEventProducer eventProducer
  280. = AFPEventProducer.Provider.get(userAgent.getEventBroadcaster());
  281. eventProducer.resourceEmbeddingError(this, formMap.getName(), ioe);
  282. }
  283. }
  284. /** {@inheritDoc} */
  285. public Graphics2DAdapter getGraphics2DAdapter() {
  286. return new AFPGraphics2DAdapter(paintingState);
  287. }
  288. /** {@inheritDoc} */
  289. public void startVParea(CTM ctm, Rectangle2D clippingRect) {
  290. saveGraphicsState();
  291. if (ctm != null) {
  292. AffineTransform at = ctm.toAffineTransform();
  293. concatenateTransformationMatrix(at);
  294. }
  295. if (clippingRect != null) {
  296. clipRect((float)clippingRect.getX() / 1000f,
  297. (float)clippingRect.getY() / 1000f,
  298. (float)clippingRect.getWidth() / 1000f,
  299. (float)clippingRect.getHeight() / 1000f);
  300. }
  301. }
  302. /** {@inheritDoc} */
  303. public void endVParea() {
  304. restoreGraphicsState();
  305. }
  306. /** {@inheritDoc} */
  307. protected void concatenateTransformationMatrix(AffineTransform at) {
  308. if (!at.isIdentity()) {
  309. paintingState.concatenate(at);
  310. }
  311. }
  312. /**
  313. * Returns the base AFP transform
  314. *
  315. * @return the base AFP transform
  316. */
  317. private AffineTransform getBaseTransform() {
  318. AffineTransform baseTransform = new AffineTransform();
  319. double scale = unitConv.mpt2units(1);
  320. baseTransform.scale(scale, scale);
  321. return baseTransform;
  322. }
  323. /** {@inheritDoc} */
  324. public void renderPage(PageViewport pageViewport) throws IOException, FOPException {
  325. paintingState.clear();
  326. Rectangle2D bounds = pageViewport.getViewArea();
  327. AffineTransform baseTransform = getBaseTransform();
  328. paintingState.concatenate(baseTransform);
  329. if (pages.containsKey(pageViewport)) {
  330. dataStream.restorePage(
  331. (PageObject)pages.remove(pageViewport));
  332. } else {
  333. int pageWidth
  334. = Math.round(unitConv.mpt2units((float)bounds.getWidth()));
  335. paintingState.setPageWidth(pageWidth);
  336. int pageHeight
  337. = Math.round(unitConv.mpt2units((float)bounds.getHeight()));
  338. paintingState.setPageHeight(pageHeight);
  339. int pageRotation = paintingState.getPageRotation();
  340. int resolution = paintingState.getResolution();
  341. // IMM should occur before BPG
  342. renderInvokeMediumMap(pageViewport);
  343. dataStream.startPage(pageWidth, pageHeight, pageRotation,
  344. resolution, resolution);
  345. renderPageObjectExtensions(pageViewport);
  346. }
  347. super.renderPage(pageViewport);
  348. AFPPageFonts pageFonts = paintingState.getPageFonts();
  349. if (pageFonts != null && !pageFonts.isEmpty()) {
  350. dataStream.addFontsToCurrentPage(pageFonts);
  351. }
  352. dataStream.endPage();
  353. }
  354. /** {@inheritDoc} */
  355. public void drawBorderLine(float x1, float y1, float x2, float y2,
  356. boolean horz, boolean startOrBefore, int style, Color col) {
  357. BorderPaintingInfo borderPaintInfo = new BorderPaintingInfo(x1, y1, x2, y2, horz, style, col);
  358. borderPainter.paint(borderPaintInfo);
  359. }
  360. /** {@inheritDoc} */
  361. public void fillRect(float x, float y, float width, float height) {
  362. RectanglePaintingInfo rectanglePaintInfo = new RectanglePaintingInfo(x, y, width, height);
  363. try {
  364. rectanglePainter.paint(rectanglePaintInfo);
  365. } catch (IOException ioe) {
  366. //TODO not ideal, but the AFPRenderer is legacy
  367. throw new RuntimeException("I/O error while painting a filled rectangle", ioe);
  368. }
  369. }
  370. /** {@inheritDoc} */
  371. protected RendererContext instantiateRendererContext() {
  372. return new AFPRendererContext(this, getMimeType());
  373. }
  374. /** {@inheritDoc} */
  375. protected RendererContext createRendererContext(int x, int y, int width,
  376. int height, Map foreignAttributes) {
  377. RendererContext context;
  378. context = super.createRendererContext(x, y, width, height,
  379. foreignAttributes);
  380. context.setProperty(AFPRendererContextConstants.AFP_FONT_INFO,
  381. this.fontInfo);
  382. context.setProperty(AFPRendererContextConstants.AFP_RESOURCE_MANAGER,
  383. this.resourceManager);
  384. context.setProperty(AFPRendererContextConstants.AFP_PAINTING_STATE, paintingState);
  385. return context;
  386. }
  387. private static final ImageFlavor[] NATIVE_FLAVORS = new ImageFlavor[] {
  388. ImageFlavor.XML_DOM,
  389. /*ImageFlavor.RAW_PNG, */ // PNG not natively supported in AFP
  390. ImageFlavor.RAW_JPEG, ImageFlavor.RAW_CCITTFAX, ImageFlavor.RAW_EPS,
  391. ImageFlavor.RAW_TIFF,
  392. ImageFlavor.GRAPHICS2D, ImageFlavor.BUFFERED_IMAGE, ImageFlavor.RENDERED_IMAGE };
  393. private static final ImageFlavor[] FLAVORS = new ImageFlavor[] {
  394. ImageFlavor.XML_DOM,
  395. ImageFlavor.GRAPHICS2D, ImageFlavor.BUFFERED_IMAGE, ImageFlavor.RENDERED_IMAGE };
  396. /** {@inheritDoc} */
  397. public void drawImage(String uri, Rectangle2D pos, Map foreignAttributes) {
  398. uri = URISpecification.getURL(uri);
  399. paintingState.setImageUri(uri);
  400. Point origin = new Point(currentIPPosition, currentBPPosition);
  401. Rectangle posInt = new Rectangle(
  402. (int)Math.round(pos.getX()),
  403. (int)Math.round(pos.getY()),
  404. (int)Math.round(pos.getWidth()),
  405. (int)Math.round(pos.getHeight())
  406. );
  407. int x = origin.x + posInt.x;
  408. int y = origin.y + posInt.y;
  409. String name = (String)pageSegmentMap.get(uri);
  410. if (name != null) {
  411. float[] srcPts = {x, y, posInt.width, posInt.height};
  412. int[] coords = unitConv.mpts2units(srcPts);
  413. int width = Math.round(unitConv.mpt2units(posInt.width));
  414. int height = Math.round(unitConv.mpt2units(posInt.height));
  415. dataStream.createIncludePageSegment(name, coords[X], coords[Y], width, height);
  416. } else {
  417. ImageManager manager = userAgent.getFactory().getImageManager();
  418. ImageInfo info = null;
  419. try {
  420. ImageSessionContext sessionContext = userAgent
  421. .getImageSessionContext();
  422. info = manager.getImageInfo(uri, sessionContext);
  423. // Only now fully load/prepare the image
  424. Map hints = ImageUtil.getDefaultHints(sessionContext);
  425. boolean nativeImagesSupported = paintingState.isNativeImagesSupported();
  426. ImageFlavor[] flavors = nativeImagesSupported ? NATIVE_FLAVORS : FLAVORS;
  427. // Load image
  428. org.apache.xmlgraphics.image.loader.Image img = manager.getImage(
  429. info, flavors, hints, sessionContext);
  430. // Handle image
  431. AFPImageHandler imageHandler
  432. = (AFPImageHandler)imageHandlerRegistry.getHandler(img);
  433. if (imageHandler != null) {
  434. RendererContext rendererContext = createRendererContext(
  435. x, y, posInt.width, posInt.height, foreignAttributes);
  436. AFPRendererImageInfo rendererImageInfo = new AFPRendererImageInfo(
  437. uri, pos, origin, info, img, rendererContext, foreignAttributes);
  438. AFPDataObjectInfo dataObjectInfo = null;
  439. try {
  440. dataObjectInfo = imageHandler.generateDataObjectInfo(rendererImageInfo);
  441. // Create image
  442. if (dataObjectInfo != null) {
  443. resourceManager.createObject(dataObjectInfo);
  444. }
  445. } catch (IOException ioe) {
  446. ResourceEventProducer eventProducer
  447. = ResourceEventProducer.Provider.get(userAgent.getEventBroadcaster());
  448. eventProducer.imageWritingError(this, ioe);
  449. throw ioe;
  450. }
  451. } else {
  452. throw new UnsupportedOperationException(
  453. "No AFPImageHandler available for image: "
  454. + info + " (" + img.getClass().getName() + ")");
  455. }
  456. } catch (ImageException ie) {
  457. ResourceEventProducer eventProducer = ResourceEventProducer.Provider
  458. .get(userAgent.getEventBroadcaster());
  459. eventProducer.imageError(this, (info != null ? info.toString()
  460. : uri), ie, null);
  461. } catch (FileNotFoundException fe) {
  462. ResourceEventProducer eventProducer = ResourceEventProducer.Provider
  463. .get(userAgent.getEventBroadcaster());
  464. eventProducer.imageNotFound(this, (info != null ? info.toString()
  465. : uri), fe, null);
  466. } catch (IOException ioe) {
  467. ResourceEventProducer eventProducer = ResourceEventProducer.Provider
  468. .get(userAgent.getEventBroadcaster());
  469. eventProducer.imageIOError(this, (info != null ? info.toString()
  470. : uri), ioe, null);
  471. }
  472. }
  473. }
  474. /**
  475. * Writes a RenderedImage to an OutputStream as raw sRGB bitmaps.
  476. *
  477. * @param image
  478. * the RenderedImage
  479. * @param out
  480. * the OutputStream
  481. * @throws IOException
  482. * In case of an I/O error.
  483. * @deprecated use ImageEncodingHelper.encodeRenderedImageAsRGB(image, out)
  484. * directly instead
  485. */
  486. public static void writeImage(RenderedImage image, OutputStream out)
  487. throws IOException {
  488. ImageEncodingHelper.encodeRenderedImageAsRGB(image, out);
  489. }
  490. /** {@inheritDoc} */
  491. public void updateColor(Color col, boolean fill) {
  492. if (fill) {
  493. paintingState.setColor(col);
  494. }
  495. }
  496. /** {@inheritDoc} */
  497. public void restoreStateStackAfterBreakOut(List breakOutList) {
  498. log.debug("Block.FIXED --> restoring context after break-out");
  499. paintingState.saveAll(breakOutList);
  500. }
  501. /** {@inheritDoc} */
  502. protected List breakOutOfStateStack() {
  503. log.debug("Block.FIXED --> break out");
  504. return paintingState.restoreAll();
  505. }
  506. /** {@inheritDoc} */
  507. public void saveGraphicsState() {
  508. paintingState.save();
  509. }
  510. /** {@inheritDoc} */
  511. public void restoreGraphicsState() {
  512. paintingState.restore();
  513. }
  514. /** {@inheritDoc} */
  515. public void renderImage(Image image, Rectangle2D pos) {
  516. drawImage(image.getURL(), pos, image.getForeignAttributes());
  517. }
  518. /** {@inheritDoc} */
  519. public void renderText(TextArea text) {
  520. renderInlineAreaBackAndBorders(text);
  521. // set font size
  522. int fontSize = ((Integer) text.getTrait(Trait.FONT_SIZE)).intValue();
  523. paintingState.setFontSize(fontSize);
  524. // register font as necessary
  525. String internalFontName = getInternalFontNameForArea(text);
  526. Map/*<String,FontMetrics>*/ fontMetricMap = fontInfo.getFonts();
  527. AFPFont font = (AFPFont)fontMetricMap.get(internalFontName);
  528. AFPPageFonts pageFonts = paintingState.getPageFonts();
  529. AFPFontAttributes fontAttributes = pageFonts.registerFont(internalFontName, font, fontSize);
  530. Font fnt = getFontFromArea(text);
  531. if (font.isEmbeddable()) {
  532. CharacterSet charSet = font.getCharacterSet(fontSize);
  533. try {
  534. this.resourceManager.embedFont(font, charSet);
  535. } catch (IOException ioe) {
  536. AFPEventProducer eventProducer
  537. = AFPEventProducer.Provider.get(userAgent.getEventBroadcaster());
  538. eventProducer.resourceEmbeddingError(this, charSet.getName(), ioe);
  539. }
  540. }
  541. // create text data info
  542. AFPTextDataInfo textDataInfo = new AFPTextDataInfo();
  543. int fontReference = fontAttributes.getFontReference();
  544. textDataInfo.setFontReference(fontReference);
  545. int x = (currentIPPosition + text.getBorderAndPaddingWidthStart());
  546. int y = (currentBPPosition + text.getOffset() + text.getBaselineOffset());
  547. int[] coords = unitConv.mpts2units(new float[] {x, y} );
  548. textDataInfo.setX(coords[X]);
  549. textDataInfo.setY(coords[Y]);
  550. Color color = (Color) text.getTrait(Trait.COLOR);
  551. textDataInfo.setColor(color);
  552. int textWordSpaceAdjust = text.getTextWordSpaceAdjust();
  553. int textLetterSpaceAdjust = text.getTextLetterSpaceAdjust();
  554. int textWidth = font.getWidth(' ', fontSize) / 1000;
  555. textWidth = 0; //JM, the above is strange
  556. int variableSpaceCharacterIncrement
  557. = textWidth + textWordSpaceAdjust + textLetterSpaceAdjust;
  558. variableSpaceCharacterIncrement
  559. = Math.round(unitConv.mpt2units(variableSpaceCharacterIncrement));
  560. textDataInfo.setVariableSpaceCharacterIncrement(variableSpaceCharacterIncrement);
  561. int interCharacterAdjustment
  562. = Math.round(unitConv.mpt2units(textLetterSpaceAdjust));
  563. textDataInfo.setInterCharacterAdjustment(interCharacterAdjustment);
  564. CharacterSet charSet = font.getCharacterSet(fontSize);
  565. String encoding = charSet.getEncoding();
  566. textDataInfo.setEncoding(encoding);
  567. String textString = text.getText();
  568. textDataInfo.setString(textString);
  569. try {
  570. dataStream.createText(textDataInfo, textLetterSpaceAdjust, textWordSpaceAdjust, fnt, charSet);
  571. } catch (UnsupportedEncodingException e) {
  572. AFPEventProducer eventProducer
  573. = AFPEventProducer.Provider.get(userAgent.getEventBroadcaster());
  574. eventProducer.characterSetEncodingError(this, charSet.getName(), encoding);
  575. }
  576. // word.getOffset() = only height of text itself
  577. // currentBlockIPPosition: 0 for beginning of line; nonzero
  578. // where previous line area failed to take up entire allocated space
  579. super.renderText(text);
  580. renderTextDecoration(font, fontSize, text, y, x);
  581. }
  582. /**
  583. * Render leader area. This renders a leader area which is an area with a
  584. * rule.
  585. *
  586. * @param area
  587. * the leader area to render
  588. */
  589. public void renderLeader(Leader area) {
  590. renderInlineAreaBackAndBorders(area);
  591. int style = area.getRuleStyle();
  592. float startx = (currentIPPosition + area
  593. .getBorderAndPaddingWidthStart()) / 1000f;
  594. float starty = (currentBPPosition + area.getOffset()) / 1000f;
  595. float endx = (currentIPPosition + area.getBorderAndPaddingWidthStart() + area
  596. .getIPD()) / 1000f;
  597. float ruleThickness = area.getRuleThickness() / 1000f;
  598. Color col = (Color) area.getTrait(Trait.COLOR);
  599. switch (style) {
  600. case EN_SOLID:
  601. case EN_DASHED:
  602. case EN_DOUBLE:
  603. case EN_DOTTED:
  604. case EN_GROOVE:
  605. case EN_RIDGE:
  606. drawBorderLine(startx, starty, endx, starty + ruleThickness, true,
  607. true, style, col);
  608. break;
  609. default:
  610. throw new UnsupportedOperationException("rule style not supported");
  611. }
  612. super.renderLeader(area);
  613. }
  614. /**
  615. * Get the MIME type of the renderer.
  616. *
  617. * @return The MIME type of the renderer
  618. */
  619. public String getMimeType() {
  620. return MimeConstants.MIME_AFP;
  621. }
  622. /**
  623. * checks for IMM Extension and renders if found and different
  624. * from previous page
  625. *
  626. * @param pageViewport the page object
  627. */
  628. private void renderInvokeMediumMap(PageViewport pageViewport) {
  629. if (pageViewport.getExtensionAttachments() != null
  630. && pageViewport.getExtensionAttachments().size() > 0) {
  631. Iterator it = pageViewport.getExtensionAttachments().iterator();
  632. while (it.hasNext()) {
  633. ExtensionAttachment attachment = (ExtensionAttachment) it.next();
  634. if (AFPExtensionAttachment.CATEGORY.equals(attachment.getCategory())) {
  635. AFPExtensionAttachment aea = (AFPExtensionAttachment)attachment;
  636. if (AFPElementMapping.INVOKE_MEDIUM_MAP.equals(aea.getElementName())) {
  637. AFPInvokeMediumMap imm = (AFPInvokeMediumMap)attachment;
  638. String mediumMap = imm.getName();
  639. if (mediumMap != null) {
  640. if (!mediumMap.equals(lastMediumMap)) {
  641. dataStream.createInvokeMediumMap(mediumMap);
  642. lastMediumMap = mediumMap;
  643. }
  644. }
  645. }
  646. }
  647. }
  648. }
  649. }
  650. /**
  651. * Method to render the page extension.
  652. * <p>
  653. *
  654. * @param pageViewport
  655. * the page object
  656. */
  657. private void renderPageObjectExtensions(PageViewport pageViewport) {
  658. pageSegmentMap.clear();
  659. if (pageViewport.getExtensionAttachments() != null
  660. && pageViewport.getExtensionAttachments().size() > 0) {
  661. // Extract all AFPPageSetup instances from the attachment list on
  662. // the s-p-m
  663. Iterator it = pageViewport.getExtensionAttachments().iterator();
  664. while (it.hasNext()) {
  665. ExtensionAttachment attachment = (ExtensionAttachment) it.next();
  666. if (AFPPageSetup.CATEGORY.equals(attachment.getCategory())) {
  667. if (attachment instanceof AFPPageSetup) {
  668. AFPPageSetup aps = (AFPPageSetup) attachment;
  669. String element = aps.getElementName();
  670. if (AFPElementMapping.INCLUDE_PAGE_SEGMENT
  671. .equals(element)) {
  672. String name = aps.getName();
  673. String source = aps.getValue();
  674. pageSegmentMap.put(source, name);
  675. } else if (AFPElementMapping.TAG_LOGICAL_ELEMENT
  676. .equals(element)) {
  677. String name = aps.getName();
  678. String value = aps.getValue();
  679. dataStream.createTagLogicalElement(name, value);
  680. } else if (AFPElementMapping.NO_OPERATION.equals(element)) {
  681. String content = aps.getContent();
  682. if (content != null) {
  683. dataStream.createNoOperation(content);
  684. }
  685. }
  686. } else if (attachment instanceof AFPPageOverlay) {
  687. AFPPageOverlay ipo = (AFPPageOverlay) attachment;
  688. String element = ipo.getElementName();
  689. if (AFPElementMapping.INCLUDE_PAGE_OVERLAY.equals(element)) {
  690. String overlay = ipo.getName();
  691. if (overlay != null) {
  692. dataStream.createIncludePageOverlay(overlay, ipo.getX(), ipo.getY());
  693. }
  694. }
  695. }
  696. }
  697. }
  698. }
  699. }
  700. /**
  701. * Sets the rotation to be used for portrait pages, valid values are 0
  702. * (default), 90, 180, 270.
  703. *
  704. * @param rotation
  705. * The rotation in degrees.
  706. */
  707. public void setPortraitRotation(int rotation) {
  708. paintingState.setPortraitRotation(rotation);
  709. }
  710. /**
  711. * Sets the rotation to be used for landscape pages, valid values are 0, 90,
  712. * 180, 270 (default).
  713. *
  714. * @param rotation
  715. * The rotation in degrees.
  716. */
  717. public void setLandscapeRotation(int rotation) {
  718. paintingState.setLandscapeRotation(rotation);
  719. }
  720. // ---=== AFPCustomizable ===---
  721. /** {@inheritDoc} */
  722. public void setBitsPerPixel(int bitsPerPixel) {
  723. paintingState.setBitsPerPixel(bitsPerPixel);
  724. }
  725. /** {@inheritDoc} */
  726. public void setColorImages(boolean colorImages) {
  727. paintingState.setColorImages(colorImages);
  728. }
  729. /** {@inheritDoc} */
  730. public void setNativeImagesSupported(boolean nativeImages) {
  731. paintingState.setNativeImagesSupported(nativeImages);
  732. }
  733. /** {@inheritDoc} */
  734. public void setCMYKImagesSupported(boolean value) {
  735. paintingState.setCMYKImagesSupported(value);
  736. }
  737. /** {@inheritDoc} */
  738. public void setShadingMode(AFPShadingMode shadingMode) {
  739. this.shadingMode = shadingMode;
  740. }
  741. /** {@inheritDoc} */
  742. public void setResolution(int resolution) {
  743. paintingState.setResolution(resolution);
  744. }
  745. /** {@inheritDoc} */
  746. public int getResolution() {
  747. return paintingState.getResolution();
  748. }
  749. /** {@inheritDoc} */
  750. public void setDefaultResourceGroupFilePath(String filePath) {
  751. resourceManager.setDefaultResourceGroupFilePath(filePath);
  752. }
  753. /** {@inheritDoc} */
  754. public void setResourceLevelDefaults(AFPResourceLevelDefaults defaults) {
  755. resourceManager.setResourceLevelDefaults(defaults);
  756. }
  757. /** {@inheritDoc} */
  758. protected void establishTransformationMatrix(AffineTransform at) {
  759. saveGraphicsState();
  760. concatenateTransformationMatrix(at);
  761. }
  762. /** {@inheritDoc} */
  763. public void clip() {
  764. // TODO
  765. // log.debug("NYI clip()");
  766. }
  767. /** {@inheritDoc} */
  768. public void clipRect(float x, float y, float width, float height) {
  769. // TODO
  770. // log.debug("NYI clipRect(x=" + x + ",y=" + y
  771. // + ",width=" + width + ", height=" + height + ")");
  772. }
  773. /** {@inheritDoc} */
  774. public void moveTo(float x, float y) {
  775. // TODO
  776. // log.debug("NYI moveTo(x=" + x + ",y=" + y + ")");
  777. }
  778. /** {@inheritDoc} */
  779. public void lineTo(float x, float y) {
  780. // TODO
  781. // log.debug("NYI lineTo(x=" + x + ",y=" + y + ")");
  782. }
  783. /** {@inheritDoc} */
  784. public void closePath() {
  785. // TODO
  786. // log.debug("NYI closePath()");
  787. }
  788. /** Indicates the beginning of a text object. */
  789. public void beginTextObject() {
  790. //TODO PDF specific maybe?
  791. // log.debug("NYI beginTextObject()");
  792. }
  793. /** Indicates the end of a text object. */
  794. public void endTextObject() {
  795. //TODO PDF specific maybe?
  796. // log.debug("NYI endTextObject()");
  797. }
  798. }