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

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