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

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