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.

Java2DRenderer.java 40KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024
  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.java2d;
  19. // Java
  20. import java.awt.BasicStroke;
  21. import java.awt.Color;
  22. import java.awt.Graphics;
  23. import java.awt.Graphics2D;
  24. import java.awt.Rectangle;
  25. import java.awt.RenderingHints;
  26. import java.awt.font.GlyphVector;
  27. import java.awt.geom.AffineTransform;
  28. import java.awt.geom.GeneralPath;
  29. import java.awt.geom.Line2D;
  30. import java.awt.geom.Point2D;
  31. import java.awt.geom.Rectangle2D;
  32. import java.awt.image.BufferedImage;
  33. import java.awt.print.PageFormat;
  34. import java.awt.print.Printable;
  35. import java.awt.print.PrinterException;
  36. import java.io.FileNotFoundException;
  37. import java.io.IOException;
  38. import java.io.OutputStream;
  39. import java.util.Iterator;
  40. import java.util.List;
  41. import java.util.Map;
  42. import java.util.Stack;
  43. import org.apache.xmlgraphics.image.loader.ImageException;
  44. import org.apache.xmlgraphics.image.loader.ImageFlavor;
  45. import org.apache.xmlgraphics.image.loader.ImageInfo;
  46. import org.apache.xmlgraphics.image.loader.ImageManager;
  47. import org.apache.xmlgraphics.image.loader.ImageSessionContext;
  48. import org.apache.xmlgraphics.image.loader.impl.ImageGraphics2D;
  49. import org.apache.xmlgraphics.image.loader.impl.ImageRendered;
  50. import org.apache.xmlgraphics.image.loader.impl.ImageXMLDOM;
  51. import org.apache.xmlgraphics.image.loader.util.ImageUtil;
  52. import org.apache.xmlgraphics.util.UnitConv;
  53. import org.apache.fop.ResourceEventProducer;
  54. import org.apache.fop.apps.FOPException;
  55. import org.apache.fop.apps.FOUserAgent;
  56. import org.apache.fop.apps.FopFactoryConfig;
  57. import org.apache.fop.area.CTM;
  58. import org.apache.fop.area.PageViewport;
  59. import org.apache.fop.area.Trait;
  60. import org.apache.fop.area.inline.Image;
  61. import org.apache.fop.area.inline.InlineArea;
  62. import org.apache.fop.area.inline.Leader;
  63. import org.apache.fop.area.inline.SpaceArea;
  64. import org.apache.fop.area.inline.TextArea;
  65. import org.apache.fop.area.inline.WordArea;
  66. import org.apache.fop.datatypes.URISpecification;
  67. import org.apache.fop.fo.Constants;
  68. import org.apache.fop.fonts.Font;
  69. import org.apache.fop.fonts.FontCollection;
  70. import org.apache.fop.fonts.FontInfo;
  71. import org.apache.fop.fonts.FontManager;
  72. import org.apache.fop.fonts.Typeface;
  73. import org.apache.fop.render.AbstractPathOrientedRenderer;
  74. import org.apache.fop.render.Graphics2DAdapter;
  75. import org.apache.fop.render.RendererContext;
  76. import org.apache.fop.render.extensions.prepress.PageBoundaries;
  77. import org.apache.fop.render.extensions.prepress.PageScale;
  78. import org.apache.fop.render.pdf.CTMHelper;
  79. import org.apache.fop.util.CharUtilities;
  80. import org.apache.fop.util.ColorUtil;
  81. import static org.apache.fop.render.java2d.Java2DRendererOptions.JAVA2D_TRANSPARENT_PAGE_BACKGROUND;
  82. /**
  83. * The <code>Java2DRenderer</code> class provides the abstract technical
  84. * foundation for all rendering with the Java2D API. Renderers like
  85. * <code>AWTRenderer</code> subclass it and provide the concrete output paths.
  86. * <p>
  87. * A lot of the logic is performed by <code>AbstractRenderer</code>. The
  88. * class-variables <code>currentIPPosition</code> and
  89. * <code>currentBPPosition</code> hold the position of the currently rendered
  90. * area.
  91. * <p>
  92. * <code>Java2DGraphicsState state</code> holds the <code>Graphics2D</code>,
  93. * which is used along the whole rendering. <code>state</code> also acts as a
  94. * stack (<code>state.push()</code> and <code>state.pop()</code>).
  95. * <p>
  96. * The rendering process is basically always the same:
  97. * <p>
  98. * <code>void renderXXXXX(Area area) {
  99. * //calculate the currentPosition
  100. * state.updateFont(name, size, null);
  101. * state.updateColor(ct, false, null);
  102. * state.getGraph.draw(new Shape(args));
  103. * }</code>
  104. *
  105. */
  106. public abstract class Java2DRenderer extends AbstractPathOrientedRenderer implements Printable {
  107. /** The scale factor for the image size, values: ]0 ; 1] */
  108. protected double scaleFactor = 1;
  109. /** The page width in pixels */
  110. protected int pageWidth = 0;
  111. /** The page height in pixels */
  112. protected int pageHeight = 0;
  113. /** List of Viewports */
  114. protected List pageViewportList = new java.util.ArrayList();
  115. /** The 0-based current page number */
  116. private int currentPageNumber = 0;
  117. /** true if anti-aliasing is set */
  118. protected boolean antialiasing = true;
  119. /** true if qualityRendering is set */
  120. protected boolean qualityRendering = true;
  121. /** false: paints a non-transparent white background, true: for a transparent background */
  122. protected boolean transparentPageBackground = false;
  123. /** The current state, holds a Graphics2D and its context */
  124. protected Java2DGraphicsState state;
  125. private final Stack stateStack = new Stack();
  126. /** true if the renderer has finished rendering all the pages */
  127. private boolean renderingDone;
  128. private GeneralPath currentPath = null;
  129. /**
  130. * Default constructor
  131. *
  132. * @param userAgent the user agent that contains configuration details. This cannot be null.
  133. */
  134. public Java2DRenderer(FOUserAgent userAgent) {
  135. super(userAgent);
  136. // MH: necessary? the caller has access to FOUserAgent
  137. userAgent.setRendererOverride(this); // for document regeneration
  138. String s = (String) userAgent.getRendererOption(JAVA2D_TRANSPARENT_PAGE_BACKGROUND);
  139. if (s != null) {
  140. this.transparentPageBackground = "true".equalsIgnoreCase(s);
  141. }
  142. }
  143. /** @return the FOUserAgent */
  144. public FOUserAgent getUserAgent() {
  145. return userAgent;
  146. }
  147. /** {@inheritDoc} */
  148. public void setupFontInfo(FontInfo inFontInfo) {
  149. //Don't call super.setupFontInfo() here! Java2D needs a special font setup
  150. // create a temp Image to test font metrics on
  151. this.fontInfo = inFontInfo;
  152. final Java2DFontMetrics java2DFontMetrics = new Java2DFontMetrics();
  153. FontManager fontManager = userAgent.getFontManager();
  154. FontCollection[] fontCollections = new FontCollection[] {
  155. new Base14FontCollection(java2DFontMetrics),
  156. new InstalledFontCollection(java2DFontMetrics),
  157. new ConfiguredFontCollection(fontManager.getResourceResolver(), getFontList(),
  158. userAgent.isComplexScriptFeaturesEnabled())
  159. };
  160. fontManager.setup(getFontInfo(), fontCollections);
  161. }
  162. /** {@inheritDoc} */
  163. public Graphics2DAdapter getGraphics2DAdapter() {
  164. return new Java2DGraphics2DAdapter();
  165. }
  166. /**
  167. * Sets the new scale factor.
  168. * @param newScaleFactor ]0 ; 1]
  169. */
  170. public void setScaleFactor(double newScaleFactor) {
  171. this.scaleFactor = newScaleFactor;
  172. }
  173. /** @return the scale factor */
  174. public double getScaleFactor() {
  175. return this.scaleFactor;
  176. }
  177. /** {@inheritDoc} */
  178. public void startRenderer(OutputStream out) throws IOException {
  179. super.startRenderer(out);
  180. // do nothing by default
  181. }
  182. /** {@inheritDoc} */
  183. public void stopRenderer() throws IOException {
  184. log.debug("Java2DRenderer stopped");
  185. renderingDone = true;
  186. int numberOfPages = currentPageNumber;
  187. // TODO set all vars to null for gc
  188. if (numberOfPages == 0) {
  189. new FOPException("No page could be rendered");
  190. }
  191. }
  192. /** @return true if the renderer is not currently processing */
  193. public boolean isRenderingDone() {
  194. return this.renderingDone;
  195. }
  196. /**
  197. * @return The 0-based current page number
  198. */
  199. public int getCurrentPageNumber() {
  200. return currentPageNumber;
  201. }
  202. /**
  203. * @param c the 0-based current page number
  204. */
  205. public void setCurrentPageNumber(int c) {
  206. this.currentPageNumber = c;
  207. }
  208. /**
  209. * Returns the number of pages available. This method is also part of the Pageable interface.
  210. * @return The 0-based total number of rendered pages
  211. * @see java.awt.print.Pageable
  212. */
  213. public int getNumberOfPages() {
  214. return pageViewportList.size();
  215. }
  216. /**
  217. * Clears the ViewportList.
  218. * Used if the document is reloaded.
  219. */
  220. public void clearViewportList() {
  221. pageViewportList.clear();
  222. setCurrentPageNumber(0);
  223. }
  224. /**
  225. * This method override only stores the PageViewport in a List. No actual
  226. * rendering is performed here. A renderer override renderPage() to get the
  227. * freshly produced PageViewport, and render them on the fly (producing the
  228. * desired BufferedImages by calling getPageImage(), which lazily starts the
  229. * rendering process).
  230. *
  231. * @param pageViewport the <code>PageViewport</code> object supplied by
  232. * the Area Tree
  233. * @throws IOException In case of an I/O error
  234. * @throws FOPException if cloning of pageViewport is not supported
  235. * @see org.apache.fop.render.Renderer
  236. */
  237. public void renderPage(PageViewport pageViewport) throws IOException, FOPException {
  238. try {
  239. rememberPage((PageViewport)pageViewport.clone());
  240. } catch (CloneNotSupportedException e) {
  241. throw new FOPException(e);
  242. }
  243. //The clone() call is necessary as we store the page for later. Otherwise, the
  244. //RenderPagesModel calls PageViewport.clear() to release memory as early as possible.
  245. currentPageNumber++;
  246. }
  247. /**
  248. * Stores the pageViewport in a list of page viewports so they can be rendered later.
  249. * Subclasses can override this method to filter pages, for example.
  250. * @param pageViewport the page viewport
  251. */
  252. protected void rememberPage(PageViewport pageViewport) {
  253. assert pageViewport.getPageIndex() >= 0;
  254. pageViewportList.add(pageViewport);
  255. }
  256. /**
  257. * Generates a desired page from the renderer's page viewport list.
  258. *
  259. * @param pageViewport the PageViewport to be rendered
  260. * @return the <code>java.awt.image.BufferedImage</code> corresponding to
  261. * the page or null if the page doesn't exist.
  262. */
  263. public BufferedImage getPageImage(PageViewport pageViewport) {
  264. this.currentPageViewport = pageViewport;
  265. try {
  266. PageBoundaries boundaries = new PageBoundaries(
  267. pageViewport.getViewArea().getSize(), pageViewport.getForeignAttributes());
  268. Rectangle bounds = boundaries.getCropBox();
  269. Rectangle bleedBox = boundaries.getBleedBox();
  270. this.pageWidth = (int) Math.round(bounds.getWidth() / 1000f);
  271. this.pageHeight = (int) Math.round(bounds.getHeight() / 1000f);
  272. log.info(
  273. "Rendering Page " + pageViewport.getPageNumberString()
  274. + " (pageWidth " + pageWidth + ", pageHeight "
  275. + pageHeight + ")");
  276. // set scale factor
  277. double scaleX = scaleFactor;
  278. double scaleY = scaleFactor;
  279. String scale = currentPageViewport.getForeignAttributes().get(
  280. PageScale.EXT_PAGE_SCALE);
  281. Point2D scales = PageScale.getScale(scale);
  282. if (scales != null) {
  283. scaleX *= scales.getX();
  284. scaleY *= scales.getY();
  285. }
  286. scaleX = scaleX
  287. * (UnitConv.IN2MM / FopFactoryConfig.DEFAULT_TARGET_RESOLUTION)
  288. / userAgent.getTargetPixelUnitToMillimeter();
  289. scaleY = scaleY
  290. * (UnitConv.IN2MM / FopFactoryConfig.DEFAULT_TARGET_RESOLUTION)
  291. / userAgent.getTargetPixelUnitToMillimeter();
  292. int bitmapWidth = (int) ((pageWidth * scaleX) + 0.5);
  293. int bitmapHeight = (int) ((pageHeight * scaleY) + 0.5);
  294. BufferedImage currentPageImage = getBufferedImage(bitmapWidth, bitmapHeight);
  295. Graphics2D graphics = currentPageImage.createGraphics();
  296. graphics.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS,
  297. RenderingHints.VALUE_FRACTIONALMETRICS_ON);
  298. if (antialiasing) {
  299. graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
  300. RenderingHints.VALUE_ANTIALIAS_ON);
  301. graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
  302. RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
  303. }
  304. if (qualityRendering) {
  305. graphics.setRenderingHint(RenderingHints.KEY_RENDERING,
  306. RenderingHints.VALUE_RENDER_QUALITY);
  307. }
  308. graphics.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL,
  309. RenderingHints.VALUE_STROKE_PURE);
  310. // transform page based on scale factor supplied
  311. AffineTransform at = graphics.getTransform();
  312. at.scale(scaleX, scaleY);
  313. at.translate(bounds.getMinX() / -1000f, bounds.getMinY() / -1000f);
  314. graphics.setTransform(at);
  315. // draw page frame
  316. if (!transparentPageBackground) {
  317. graphics.setColor(Color.white);
  318. graphics.fillRect(
  319. (int)Math.round(bleedBox.getMinX() / 1000f),
  320. (int)Math.round(bleedBox.getMinY() / 1000f),
  321. (int)Math.round(bleedBox.getWidth() / 1000f),
  322. (int)Math.round(bleedBox.getHeight() / 1000f));
  323. }
  324. /* why did we have this???
  325. graphics.setColor(Color.black);
  326. graphics.drawRect(-1, -1, pageWidth + 2, pageHeight + 2);
  327. graphics.drawLine(pageWidth + 2, 0, pageWidth + 2, pageHeight + 2);
  328. graphics.drawLine(pageWidth + 3, 1, pageWidth + 3, pageHeight + 3);
  329. graphics.drawLine(0, pageHeight + 2, pageWidth + 2, pageHeight + 2);
  330. graphics.drawLine(1, pageHeight + 3, pageWidth + 3, pageHeight + 3);
  331. */
  332. state = new Java2DGraphicsState(graphics, this.fontInfo, at);
  333. try {
  334. // reset the current Positions
  335. currentBPPosition = 0;
  336. currentIPPosition = 0;
  337. // this toggles the rendering of all areas
  338. renderPageAreas(pageViewport.getPage());
  339. } finally {
  340. state = null;
  341. }
  342. return currentPageImage;
  343. } finally {
  344. this.currentPageViewport = null;
  345. }
  346. }
  347. /**
  348. * Returns a specific <code>BufferedImage</code> to paint a page image on. This method can
  349. * be overridden in subclasses to produce different image formats (ex. grayscale or b/w).
  350. * @param bitmapWidth width of the image in pixels
  351. * @param bitmapHeight heigth of the image in pixels
  352. * @return the newly created BufferedImage
  353. */
  354. protected BufferedImage getBufferedImage(int bitmapWidth, int bitmapHeight) {
  355. return new BufferedImage(
  356. bitmapWidth, bitmapHeight, BufferedImage.TYPE_INT_ARGB);
  357. }
  358. /**
  359. * Returns a page viewport.
  360. * @param pageIndex the page index (zero-based)
  361. * @return the requested PageViewport instance
  362. * @exception FOPException If the page is out of range.
  363. */
  364. public PageViewport getPageViewport(int pageIndex) throws FOPException {
  365. if (pageIndex < 0 || pageIndex >= pageViewportList.size()) {
  366. throw new FOPException("Requested page number is out of range: " + pageIndex
  367. + "; only " + pageViewportList.size()
  368. + " page(s) available.");
  369. }
  370. return (PageViewport) pageViewportList.get(pageIndex);
  371. }
  372. /**
  373. * Generates a desired page from the renderer's page viewport list.
  374. *
  375. * @param pageNum the 0-based page number to generate
  376. * @return the <code>java.awt.image.BufferedImage</code> corresponding to
  377. * the page or null if the page doesn't exist.
  378. * @throws FOPException If there's a problem preparing the page image
  379. */
  380. public BufferedImage getPageImage(int pageNum) throws FOPException {
  381. return getPageImage(getPageViewport(pageNum));
  382. }
  383. /** Saves the graphics state of the rendering engine. */
  384. protected void saveGraphicsState() {
  385. // push (and save) the current graphics state
  386. stateStack.push(state);
  387. state = new Java2DGraphicsState(state);
  388. }
  389. /** Restores the last graphics state of the rendering engine. */
  390. protected void restoreGraphicsState() {
  391. state.dispose();
  392. state = (Java2DGraphicsState)stateStack.pop();
  393. }
  394. /** {@inheritDoc} */
  395. protected void concatenateTransformationMatrix(AffineTransform at) {
  396. state.transform(at);
  397. }
  398. /** {@inheritDoc} */
  399. protected void startVParea(CTM ctm, Rectangle clippingRect) {
  400. saveGraphicsState();
  401. if (clippingRect != null) {
  402. clipRect((float)clippingRect.getX() / 1000f,
  403. (float)clippingRect.getY() / 1000f,
  404. (float)clippingRect.getWidth() / 1000f,
  405. (float)clippingRect.getHeight() / 1000f);
  406. }
  407. // Set the given CTM in the graphics state
  408. //state.setTransform(new AffineTransform(CTMHelper.toPDFArray(ctm)));
  409. state.transform(new AffineTransform(CTMHelper.toPDFArray(ctm)));
  410. }
  411. /** {@inheritDoc} */
  412. protected void endVParea() {
  413. restoreGraphicsState();
  414. }
  415. /** {@inheritDoc} */
  416. protected List breakOutOfStateStack() {
  417. log.debug("Block.FIXED --> break out");
  418. List breakOutList;
  419. breakOutList = new java.util.ArrayList();
  420. while (!stateStack.isEmpty()) {
  421. breakOutList.add(0, state);
  422. //We only pop, we don't dispose, because we can use the instances again later
  423. state = (Java2DGraphicsState)stateStack.pop();
  424. }
  425. return breakOutList;
  426. }
  427. /** {@inheritDoc} */
  428. protected void restoreStateStackAfterBreakOut(List breakOutList) {
  429. log.debug("Block.FIXED --> restoring context after break-out");
  430. Iterator it = breakOutList.iterator();
  431. while (it.hasNext()) {
  432. Java2DGraphicsState s = (Java2DGraphicsState)it.next();
  433. stateStack.push(state);
  434. this.state = s;
  435. }
  436. }
  437. /** {@inheritDoc} */
  438. protected void updateColor(Color col, boolean fill) {
  439. state.updateColor(col);
  440. }
  441. /** {@inheritDoc} */
  442. protected void clip() {
  443. if (currentPath == null) {
  444. throw new IllegalStateException("No current path available!");
  445. }
  446. state.updateClip(currentPath);
  447. currentPath = null;
  448. }
  449. /** {@inheritDoc} */
  450. protected void closePath() {
  451. currentPath.closePath();
  452. }
  453. /** {@inheritDoc} */
  454. protected void lineTo(float x, float y) {
  455. if (currentPath == null) {
  456. currentPath = new GeneralPath();
  457. }
  458. currentPath.lineTo(x, y);
  459. }
  460. /** {@inheritDoc} */
  461. protected void moveTo(float x, float y) {
  462. if (currentPath == null) {
  463. currentPath = new GeneralPath();
  464. }
  465. currentPath.moveTo(x, y);
  466. }
  467. /** {@inheritDoc} */
  468. protected void clipRect(float x, float y, float width, float height) {
  469. state.updateClip(new Rectangle2D.Float(x, y, width, height));
  470. }
  471. /** {@inheritDoc} */
  472. protected void fillRect(float x, float y, float width, float height) {
  473. state.getGraph().fill(new Rectangle2D.Float(x, y, width, height));
  474. }
  475. /** {@inheritDoc} */
  476. protected void drawBorderLine( // CSOK: ParameterNumber
  477. float x1, float y1, float x2, float y2,
  478. boolean horz, boolean startOrBefore, int style, Color col) {
  479. Graphics2D g2d = state.getGraph();
  480. float width = x2 - x1;
  481. float height = y2 - y1;
  482. drawBorderLine(new Rectangle2D.Float(x1, y1, width, height),
  483. horz, startOrBefore, style, col, g2d);
  484. }
  485. /**
  486. * Draw a border segment of an XSL-FO style border.
  487. * @param lineRect the line defined by its bounding rectangle
  488. * @param horz true for horizontal border segments, false for vertical border segments
  489. * @param startOrBefore true for border segments on the start or before edge,
  490. * false for end or after.
  491. * @param style the border style (one of Constants.EN_DASHED etc.)
  492. * @param col the color for the border segment
  493. * @param g2d the Graphics2D instance to paint to
  494. */
  495. public static void drawBorderLine(Rectangle2D.Float lineRect,
  496. boolean horz, boolean startOrBefore, int style, Color col, Graphics2D g2d) {
  497. float x1 = lineRect.x;
  498. float y1 = lineRect.y;
  499. float x2 = x1 + lineRect.width;
  500. float y2 = y1 + lineRect.height;
  501. float w = lineRect.width;
  502. float h = lineRect.height;
  503. if ((w < 0) || (h < 0)) {
  504. log.error("Negative extent received. Border won't be painted.");
  505. return;
  506. }
  507. switch (style) {
  508. case Constants.EN_DASHED:
  509. g2d.setColor(col);
  510. if (horz) {
  511. float unit = Math.abs(2 * h);
  512. int rep = (int)(w / unit);
  513. if (rep % 2 == 0) {
  514. rep++;
  515. }
  516. unit = w / rep;
  517. float ym = y1 + (h / 2);
  518. BasicStroke s = new BasicStroke(h, BasicStroke.CAP_BUTT,
  519. BasicStroke.JOIN_MITER, 10.0f, new float[] {unit}, 0);
  520. g2d.setStroke(s);
  521. g2d.draw(new Line2D.Float(x1, ym, x2, ym));
  522. } else {
  523. float unit = Math.abs(2 * w);
  524. int rep = (int)(h / unit);
  525. if (rep % 2 == 0) {
  526. rep++;
  527. }
  528. unit = h / rep;
  529. float xm = x1 + (w / 2);
  530. BasicStroke s = new BasicStroke(w, BasicStroke.CAP_BUTT,
  531. BasicStroke.JOIN_MITER, 10.0f, new float[] {unit}, 0);
  532. g2d.setStroke(s);
  533. g2d.draw(new Line2D.Float(xm, y1, xm, y2));
  534. }
  535. break;
  536. case Constants.EN_DOTTED:
  537. g2d.setColor(col);
  538. if (horz) {
  539. float unit = Math.abs(2 * h);
  540. int rep = (int)(w / unit);
  541. if (rep % 2 == 0) {
  542. rep++;
  543. }
  544. unit = w / rep;
  545. float ym = y1 + (h / 2);
  546. BasicStroke s = new BasicStroke(h, BasicStroke.CAP_ROUND,
  547. BasicStroke.JOIN_MITER, 10.0f, new float[] {0, unit}, 0);
  548. g2d.setStroke(s);
  549. g2d.draw(new Line2D.Float(x1, ym, x2, ym));
  550. } else {
  551. float unit = Math.abs(2 * w);
  552. int rep = (int)(h / unit);
  553. if (rep % 2 == 0) {
  554. rep++;
  555. }
  556. unit = h / rep;
  557. float xm = x1 + (w / 2);
  558. BasicStroke s = new BasicStroke(w, BasicStroke.CAP_ROUND,
  559. BasicStroke.JOIN_MITER, 10.0f, new float[] {0, unit}, 0);
  560. g2d.setStroke(s);
  561. g2d.draw(new Line2D.Float(xm, y1, xm, y2));
  562. }
  563. break;
  564. case Constants.EN_DOUBLE:
  565. g2d.setColor(col);
  566. if (horz) {
  567. float h3 = h / 3;
  568. float ym1 = y1 + (h3 / 2);
  569. float ym2 = ym1 + h3 + h3;
  570. BasicStroke s = new BasicStroke(h3);
  571. g2d.setStroke(s);
  572. g2d.draw(new Line2D.Float(x1, ym1, x2, ym1));
  573. g2d.draw(new Line2D.Float(x1, ym2, x2, ym2));
  574. } else {
  575. float w3 = w / 3;
  576. float xm1 = x1 + (w3 / 2);
  577. float xm2 = xm1 + w3 + w3;
  578. BasicStroke s = new BasicStroke(w3);
  579. g2d.setStroke(s);
  580. g2d.draw(new Line2D.Float(xm1, y1, xm1, y2));
  581. g2d.draw(new Line2D.Float(xm2, y1, xm2, y2));
  582. }
  583. break;
  584. case Constants.EN_GROOVE:
  585. case Constants.EN_RIDGE:
  586. float colFactor = (style == EN_GROOVE ? 0.4f : -0.4f);
  587. if (horz) {
  588. Color uppercol = ColorUtil.lightenColor(col, -colFactor);
  589. Color lowercol = ColorUtil.lightenColor(col, colFactor);
  590. float h3 = h / 3;
  591. float ym1 = y1 + (h3 / 2);
  592. g2d.setStroke(new BasicStroke(h3));
  593. g2d.setColor(uppercol);
  594. g2d.draw(new Line2D.Float(x1, ym1, x2, ym1));
  595. g2d.setColor(col);
  596. g2d.draw(new Line2D.Float(x1, ym1 + h3, x2, ym1 + h3));
  597. g2d.setColor(lowercol);
  598. g2d.draw(new Line2D.Float(x1, ym1 + h3 + h3, x2, ym1 + h3 + h3));
  599. } else {
  600. Color leftcol = ColorUtil.lightenColor(col, -colFactor);
  601. Color rightcol = ColorUtil.lightenColor(col, colFactor);
  602. float w3 = w / 3;
  603. float xm1 = x1 + (w3 / 2);
  604. g2d.setStroke(new BasicStroke(w3));
  605. g2d.setColor(leftcol);
  606. g2d.draw(new Line2D.Float(xm1, y1, xm1, y2));
  607. g2d.setColor(col);
  608. g2d.draw(new Line2D.Float(xm1 + w3, y1, xm1 + w3, y2));
  609. g2d.setColor(rightcol);
  610. g2d.draw(new Line2D.Float(xm1 + w3 + w3, y1, xm1 + w3 + w3, y2));
  611. }
  612. break;
  613. case Constants.EN_INSET:
  614. case Constants.EN_OUTSET:
  615. colFactor = (style == EN_OUTSET ? 0.4f : -0.4f);
  616. if (horz) {
  617. col = ColorUtil.lightenColor(col, (startOrBefore ? 1 : -1) * colFactor);
  618. g2d.setStroke(new BasicStroke(h));
  619. float ym1 = y1 + (h / 2);
  620. g2d.setColor(col);
  621. g2d.draw(new Line2D.Float(x1, ym1, x2, ym1));
  622. } else {
  623. col = ColorUtil.lightenColor(col, (startOrBefore ? 1 : -1) * colFactor);
  624. float xm1 = x1 + (w / 2);
  625. g2d.setStroke(new BasicStroke(w));
  626. g2d.setColor(col);
  627. g2d.draw(new Line2D.Float(xm1, y1, xm1, y2));
  628. }
  629. break;
  630. case Constants.EN_HIDDEN:
  631. break;
  632. default:
  633. g2d.setColor(col);
  634. if (horz) {
  635. float ym = y1 + (h / 2);
  636. g2d.setStroke(new BasicStroke(h));
  637. g2d.draw(new Line2D.Float(x1, ym, x2, ym));
  638. } else {
  639. float xm = x1 + (w / 2);
  640. g2d.setStroke(new BasicStroke(w));
  641. g2d.draw(new Line2D.Float(xm, y1, xm, y2));
  642. }
  643. }
  644. }
  645. /** {@inheritDoc} */
  646. public void renderText(TextArea text) {
  647. renderInlineAreaBackAndBorders(text);
  648. int rx = currentIPPosition + text.getBorderAndPaddingWidthStart();
  649. int bl = currentBPPosition + text.getBlockProgressionOffset() + text.getBaselineOffset();
  650. int saveIP = currentIPPosition;
  651. Font font = getFontFromArea(text);
  652. state.updateFont(font.getFontName(), font.getFontSize());
  653. saveGraphicsState();
  654. AffineTransform at = new AffineTransform();
  655. at.translate(rx / 1000f, bl / 1000f);
  656. state.transform(at);
  657. renderText(text, state.getGraph(), font);
  658. restoreGraphicsState();
  659. currentIPPosition = saveIP + text.getAllocIPD();
  660. //super.renderText(text);
  661. // rendering text decorations
  662. Typeface tf = fontInfo.getFonts().get(font.getFontName());
  663. int fontsize = text.getTraitAsInteger(Trait.FONT_SIZE);
  664. renderTextDecoration(tf, fontsize, text, bl, rx);
  665. }
  666. /**
  667. * Renders a TextArea to a Graphics2D instance. Adjust the coordinate system so that the
  668. * start of the baseline of the first character is at coordinate (0,0).
  669. * @param text the TextArea
  670. * @param g2d the Graphics2D to render to
  671. * @param font the font to paint with
  672. */
  673. public static void renderText(TextArea text, Graphics2D g2d, Font font) {
  674. Color col = (Color) text.getTrait(Trait.COLOR);
  675. g2d.setColor(col);
  676. float textCursor = 0;
  677. Iterator iter = text.getChildAreas().iterator();
  678. while (iter.hasNext()) {
  679. InlineArea child = (InlineArea)iter.next();
  680. if (child instanceof WordArea) {
  681. WordArea word = (WordArea)child;
  682. String s = word.getWord();
  683. int[] letterAdjust = word.getLetterAdjustArray();
  684. GlyphVector gv = g2d.getFont().createGlyphVector(g2d.getFontRenderContext(), s);
  685. double additionalWidth = 0.0;
  686. if (letterAdjust == null
  687. && text.getTextLetterSpaceAdjust() == 0
  688. && text.getTextWordSpaceAdjust() == 0) {
  689. //nop
  690. } else {
  691. int[] offsets = getGlyphOffsets(s, font, text, letterAdjust);
  692. float cursor = 0.0f;
  693. for (int i = 0; i < offsets.length; i++) {
  694. Point2D pt = gv.getGlyphPosition(i);
  695. pt.setLocation(cursor, pt.getY());
  696. gv.setGlyphPosition(i, pt);
  697. cursor += offsets[i] / 1000f;
  698. }
  699. additionalWidth = cursor - gv.getLogicalBounds().getWidth();
  700. }
  701. g2d.drawGlyphVector(gv, textCursor, 0);
  702. textCursor += gv.getLogicalBounds().getWidth() + additionalWidth;
  703. } else if (child instanceof SpaceArea) {
  704. SpaceArea space = (SpaceArea)child;
  705. String s = space.getSpace();
  706. char sp = s.charAt(0);
  707. int tws = (space.isAdjustable()
  708. ? text.getTextWordSpaceAdjust()
  709. + 2 * text.getTextLetterSpaceAdjust()
  710. : 0);
  711. textCursor += (font.getCharWidth(sp) + tws) / 1000f;
  712. } else {
  713. throw new IllegalStateException("Unsupported child element: " + child);
  714. }
  715. }
  716. }
  717. private static int[] getGlyphOffsets(String s, Font font, TextArea text,
  718. int[] letterAdjust) {
  719. int textLen = s.length();
  720. int[] offsets = new int[textLen];
  721. for (int i = 0; i < textLen; i++) {
  722. final char c = s.charAt(i);
  723. final char mapped = font.mapChar(c);
  724. int wordSpace;
  725. if (CharUtilities.isAdjustableSpace(mapped)) {
  726. wordSpace = text.getTextWordSpaceAdjust();
  727. } else {
  728. wordSpace = 0;
  729. }
  730. int cw = font.getWidth(mapped);
  731. int ladj = (letterAdjust != null && i < textLen - 1 ? letterAdjust[i + 1] : 0);
  732. int tls = (i < textLen - 1 ? text.getTextLetterSpaceAdjust() : 0);
  733. offsets[i] = cw + ladj + tls + wordSpace;
  734. }
  735. return offsets;
  736. }
  737. /**
  738. * Render leader area. This renders a leader area which is an area with a
  739. * rule.
  740. *
  741. * @param area the leader area to render
  742. */
  743. public void renderLeader(Leader area) {
  744. renderInlineAreaBackAndBorders(area);
  745. // TODO leader-length: 25%, 50%, 75%, 100% not working yet
  746. // TODO Colors do not work on Leaders yet
  747. float startx = (currentIPPosition + area.getBorderAndPaddingWidthStart()) / 1000f;
  748. float starty = ((currentBPPosition + area.getBlockProgressionOffset()) / 1000f);
  749. float endx = (currentIPPosition + area.getBorderAndPaddingWidthStart()
  750. + area.getIPD()) / 1000f;
  751. Color col = (Color) area.getTrait(Trait.COLOR);
  752. state.updateColor(col);
  753. Line2D line = new Line2D.Float();
  754. line.setLine(startx, starty, endx, starty);
  755. float ruleThickness = area.getRuleThickness() / 1000f;
  756. int style = area.getRuleStyle();
  757. switch (style) {
  758. case EN_SOLID:
  759. case EN_DASHED:
  760. case EN_DOUBLE:
  761. drawBorderLine(startx, starty, endx, starty + ruleThickness,
  762. true, true, style, col);
  763. break;
  764. case EN_DOTTED:
  765. //TODO Dots should be shifted to the left by ruleThickness / 2
  766. state.updateStroke(ruleThickness, style);
  767. float rt2 = ruleThickness / 2f;
  768. line.setLine(line.getX1(), line.getY1() + rt2, line.getX2(), line.getY2() + rt2);
  769. state.getGraph().draw(line);
  770. break;
  771. case EN_GROOVE:
  772. case EN_RIDGE:
  773. float half = area.getRuleThickness() / 2000f;
  774. state.updateColor(ColorUtil.lightenColor(col, 0.6f));
  775. moveTo(startx, starty);
  776. lineTo(endx, starty);
  777. lineTo(endx, starty + 2 * half);
  778. lineTo(startx, starty + 2 * half);
  779. closePath();
  780. state.getGraph().fill(currentPath);
  781. currentPath = null;
  782. state.updateColor(col);
  783. if (style == EN_GROOVE) {
  784. moveTo(startx, starty);
  785. lineTo(endx, starty);
  786. lineTo(endx, starty + half);
  787. lineTo(startx + half, starty + half);
  788. lineTo(startx, starty + 2 * half);
  789. } else {
  790. moveTo(endx, starty);
  791. lineTo(endx, starty + 2 * half);
  792. lineTo(startx, starty + 2 * half);
  793. lineTo(startx, starty + half);
  794. lineTo(endx - half, starty + half);
  795. }
  796. closePath();
  797. state.getGraph().fill(currentPath);
  798. currentPath = null;
  799. case EN_NONE:
  800. // No rule is drawn
  801. break;
  802. default:
  803. } // end switch
  804. super.renderLeader(area);
  805. }
  806. /** {@inheritDoc} */
  807. public void renderImage(Image image, Rectangle2D pos) {
  808. // endTextObject();
  809. String url = image.getURL();
  810. drawImage(url, pos);
  811. }
  812. private static final ImageFlavor[] FLAVOURS = new ImageFlavor[]
  813. {ImageFlavor.GRAPHICS2D,
  814. ImageFlavor.BUFFERED_IMAGE,
  815. ImageFlavor.RENDERED_IMAGE,
  816. ImageFlavor.XML_DOM};
  817. /** {@inheritDoc} */
  818. protected void drawImage(String uri, Rectangle2D pos, Map foreignAttributes) {
  819. int x = currentIPPosition + (int)Math.round(pos.getX());
  820. int y = currentBPPosition + (int)Math.round(pos.getY());
  821. uri = URISpecification.getURL(uri);
  822. ImageManager manager = getUserAgent().getImageManager();
  823. ImageInfo info = null;
  824. try {
  825. ImageSessionContext sessionContext = getUserAgent().getImageSessionContext();
  826. info = manager.getImageInfo(uri, sessionContext);
  827. Map hints = ImageUtil.getDefaultHints(sessionContext);
  828. org.apache.xmlgraphics.image.loader.Image img = manager.getImage(
  829. info, FLAVOURS, hints, sessionContext);
  830. if (img instanceof ImageGraphics2D) {
  831. ImageGraphics2D imageG2D = (ImageGraphics2D)img;
  832. int width = (int)pos.getWidth();
  833. int height = (int)pos.getHeight();
  834. RendererContext context = createRendererContext(
  835. x, y, width, height, foreignAttributes);
  836. getGraphics2DAdapter().paintImage(imageG2D.getGraphics2DImagePainter(),
  837. context, x, y, width, height);
  838. } else if (img instanceof ImageRendered) {
  839. ImageRendered imgRend = (ImageRendered)img;
  840. AffineTransform at = new AffineTransform();
  841. at.translate(x / 1000f, y / 1000f);
  842. double sx = pos.getWidth() / info.getSize().getWidthMpt();
  843. double sy = pos.getHeight() / info.getSize().getHeightMpt();
  844. sx *= userAgent.getSourceResolution() / info.getSize().getDpiHorizontal();
  845. sy *= userAgent.getSourceResolution() / info.getSize().getDpiVertical();
  846. at.scale(sx, sy);
  847. state.getGraph().drawRenderedImage(imgRend.getRenderedImage(), at);
  848. } else if (img instanceof ImageXMLDOM) {
  849. ImageXMLDOM imgXML = (ImageXMLDOM)img;
  850. renderDocument(imgXML.getDocument(), imgXML.getRootNamespace(),
  851. pos, foreignAttributes);
  852. }
  853. } catch (ImageException ie) {
  854. ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get(
  855. getUserAgent().getEventBroadcaster());
  856. eventProducer.imageError(this, (info != null ? info.toString() : uri), ie, null);
  857. } catch (FileNotFoundException fe) {
  858. ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get(
  859. getUserAgent().getEventBroadcaster());
  860. eventProducer.imageNotFound(this, (info != null ? info.toString() : uri), fe, null);
  861. } catch (IOException ioe) {
  862. ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get(
  863. getUserAgent().getEventBroadcaster());
  864. eventProducer.imageIOError(this, (info != null ? info.toString() : uri), ioe, null);
  865. }
  866. }
  867. /** {@inheritDoc} */
  868. protected RendererContext createRendererContext(int x, int y, int width, int height,
  869. Map foreignAttributes) {
  870. RendererContext context = super.createRendererContext(
  871. x, y, width, height, foreignAttributes);
  872. context.setProperty(Java2DRendererContextConstants.JAVA2D_STATE, state);
  873. return context;
  874. }
  875. /** {@inheritDoc} */
  876. public int print(Graphics g, PageFormat pageFormat, int pageIndex)
  877. throws PrinterException {
  878. if (pageIndex >= getNumberOfPages()) {
  879. return NO_SUCH_PAGE;
  880. }
  881. if (state != null) {
  882. throw new IllegalStateException("state must be null");
  883. }
  884. Graphics2D graphics = (Graphics2D) g;
  885. try {
  886. PageViewport viewport = getPageViewport(pageIndex);
  887. AffineTransform at = graphics.getTransform();
  888. state = new Java2DGraphicsState(graphics, this.fontInfo, at);
  889. // reset the current Positions
  890. currentBPPosition = 0;
  891. currentIPPosition = 0;
  892. renderPageAreas(viewport.getPage());
  893. return PAGE_EXISTS;
  894. } catch (FOPException e) {
  895. log.error(e);
  896. return NO_SUCH_PAGE;
  897. } finally {
  898. state = null;
  899. }
  900. }
  901. /** {@inheritDoc} */
  902. protected void beginTextObject() {
  903. //not necessary in Java2D
  904. }
  905. /** {@inheritDoc} */
  906. protected void endTextObject() {
  907. //not necessary in Java2D
  908. }
  909. /**
  910. * Controls the page background.
  911. * @param transparentPageBackground true if the background should be transparent
  912. */
  913. public void setTransparentPageBackground(boolean transparentPageBackground) {
  914. this.transparentPageBackground = transparentPageBackground;
  915. }
  916. }