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

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