Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

Java2DRenderer.java 37KB

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