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.

AFPRenderer.java 32KB

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