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.

PCLRenderer.java 59KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514
  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.pcl;
  19. //Java
  20. import java.awt.BasicStroke;
  21. import java.awt.Color;
  22. import java.awt.Dimension;
  23. import java.awt.Graphics2D;
  24. import java.awt.Point;
  25. import java.awt.Rectangle;
  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.RenderedImage;
  32. import java.io.FileNotFoundException;
  33. import java.io.IOException;
  34. import java.io.OutputStream;
  35. import java.util.List;
  36. import java.util.Map;
  37. import java.util.Stack;
  38. import org.w3c.dom.Document;
  39. import org.apache.commons.logging.Log;
  40. import org.apache.commons.logging.LogFactory;
  41. import org.apache.xmlgraphics.image.loader.ImageException;
  42. import org.apache.xmlgraphics.image.loader.ImageFlavor;
  43. import org.apache.xmlgraphics.image.loader.ImageInfo;
  44. import org.apache.xmlgraphics.image.loader.ImageManager;
  45. import org.apache.xmlgraphics.image.loader.ImageSessionContext;
  46. import org.apache.xmlgraphics.image.loader.ImageSize;
  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.java2d.GraphicContext;
  52. import org.apache.xmlgraphics.java2d.Graphics2DImagePainter;
  53. import org.apache.xmlgraphics.util.UnitConv;
  54. import org.apache.fop.ResourceEventProducer;
  55. import org.apache.fop.apps.FOPException;
  56. import org.apache.fop.apps.FOUserAgent;
  57. import org.apache.fop.apps.MimeConstants;
  58. import org.apache.fop.area.Area;
  59. import org.apache.fop.area.Block;
  60. import org.apache.fop.area.BlockViewport;
  61. import org.apache.fop.area.CTM;
  62. import org.apache.fop.area.NormalFlow;
  63. import org.apache.fop.area.PageViewport;
  64. import org.apache.fop.area.RegionViewport;
  65. import org.apache.fop.area.Trait;
  66. import org.apache.fop.area.inline.AbstractTextArea;
  67. import org.apache.fop.area.inline.ForeignObject;
  68. import org.apache.fop.area.inline.Image;
  69. import org.apache.fop.area.inline.InlineArea;
  70. import org.apache.fop.area.inline.Leader;
  71. import org.apache.fop.area.inline.SpaceArea;
  72. import org.apache.fop.area.inline.TextArea;
  73. import org.apache.fop.area.inline.Viewport;
  74. import org.apache.fop.area.inline.WordArea;
  75. import org.apache.fop.datatypes.URISpecification;
  76. import org.apache.fop.fonts.Font;
  77. import org.apache.fop.fonts.FontCollection;
  78. import org.apache.fop.fonts.FontInfo;
  79. import org.apache.fop.fonts.FontMetrics;
  80. import org.apache.fop.render.Graphics2DAdapter;
  81. import org.apache.fop.render.ImageHandlerUtil;
  82. import org.apache.fop.render.PrintRenderer;
  83. import org.apache.fop.render.RendererContext;
  84. import org.apache.fop.render.RendererContextConstants;
  85. import org.apache.fop.render.RendererEventProducer;
  86. import org.apache.fop.render.java2d.Base14FontCollection;
  87. import org.apache.fop.render.java2d.ConfiguredFontCollection;
  88. import org.apache.fop.render.java2d.FontMetricsMapper;
  89. import org.apache.fop.render.java2d.InstalledFontCollection;
  90. import org.apache.fop.render.java2d.Java2DFontMetrics;
  91. import org.apache.fop.render.java2d.Java2DRenderer;
  92. import org.apache.fop.render.pcl.extensions.PCLElementMapping;
  93. import org.apache.fop.traits.BorderProps;
  94. /* Note:
  95. * There are some commonalities with AbstractPathOrientedRenderer but it's not possible
  96. * to derive from it due to PCL's restrictions. We may need an additional common subclass to
  97. * avoid methods copied from AbstractPathOrientedRenderer. Or we wait until after the IF redesign.
  98. */
  99. /**
  100. * Renderer for the PCL 5 printer language. It also uses HP GL/2 for certain graphic elements.
  101. */
  102. public class PCLRenderer extends PrintRenderer implements PCLConstants {
  103. /** logging instance */
  104. private static Log log = LogFactory.getLog(PCLRenderer.class);
  105. /** The MIME type for PCL */
  106. public static final String MIME_TYPE = MimeConstants.MIME_PCL_ALT;
  107. /** The OutputStream to write the PCL stream to */
  108. protected OutputStream out;
  109. /** The PCL generator */
  110. protected PCLGenerator gen;
  111. private boolean ioTrouble = false;
  112. private final Stack graphicContextStack = new Stack();
  113. private GraphicContext graphicContext = new GraphicContext();
  114. private PCLPageDefinition currentPageDefinition;
  115. private int currentPrintDirection = 0;
  116. private GeneralPath currentPath = null;
  117. private java.awt.Color currentFillColor = null;
  118. /**
  119. * Utility class which enables all sorts of features that are not directly connected to the
  120. * normal rendering process.
  121. */
  122. private PCLRenderingUtil pclUtil;
  123. /** contains the pageWith of the last printed page */
  124. private long pageWidth = 0;
  125. /** contains the pageHeight of the last printed page */
  126. private long pageHeight = 0;
  127. /**
  128. * Create the PCL renderer
  129. */
  130. public PCLRenderer() {
  131. }
  132. /** {@inheritDoc} */
  133. public void setUserAgent(FOUserAgent agent) {
  134. super.setUserAgent(agent);
  135. this.pclUtil = new PCLRenderingUtil(getUserAgent());
  136. }
  137. PCLRenderingUtil getPCLUtil() {
  138. return this.pclUtil;
  139. }
  140. /**
  141. * Configures the renderer to trade speed for quality if desired. One example here is the way
  142. * that borders are rendered.
  143. * @param qualityBeforeSpeed true if quality is more important than speed
  144. */
  145. public void setQualityBeforeSpeed(boolean qualityBeforeSpeed) {
  146. pclUtil.setRenderingMode(qualityBeforeSpeed
  147. ? PCLRenderingMode.QUALITY : PCLRenderingMode.SPEED);
  148. }
  149. /**
  150. * Controls whether PJL commands shall be generated by the PCL renderer.
  151. * @param disable true to disable PJL commands
  152. */
  153. public void setPJLDisabled(boolean disable) {
  154. pclUtil.setPJLDisabled(disable);
  155. }
  156. /**
  157. * Indicates whether PJL generation is disabled.
  158. * @return true if PJL generation is disabled.
  159. */
  160. public boolean isPJLDisabled() {
  161. return pclUtil.isPJLDisabled();
  162. }
  163. /**
  164. * Controls whether all text should be generated as bitmaps or only text for which there's
  165. * no native font.
  166. * @param allTextAsBitmaps true if all text should be painted as bitmaps
  167. */
  168. public void setAllTextAsBitmaps(boolean allTextAsBitmaps) {
  169. pclUtil.setAllTextAsBitmaps(allTextAsBitmaps);
  170. }
  171. /**
  172. * {@inheritDoc}
  173. */
  174. public void setupFontInfo(FontInfo inFontInfo) {
  175. //Don't call super.setupFontInfo() here!
  176. //The PCLRenderer uses the Java2D FontSetup which needs a special font setup
  177. //create a temp Image to test font metrics on
  178. fontInfo = inFontInfo;
  179. Graphics2D graphics2D = Java2DFontMetrics.createFontMetricsGraphics2D();
  180. FontCollection[] fontCollections = new FontCollection[] {
  181. new Base14FontCollection(graphics2D),
  182. new InstalledFontCollection(graphics2D),
  183. new ConfiguredFontCollection(getFontResolver(), getFontList())
  184. };
  185. userAgent.getFactory().getFontManager().setup(
  186. getFontInfo(), fontCollections);
  187. }
  188. /**
  189. * Central exception handler for I/O exceptions.
  190. * @param ioe IOException to handle
  191. */
  192. protected void handleIOTrouble(IOException ioe) {
  193. if (!ioTrouble) {
  194. RendererEventProducer eventProducer = RendererEventProducer.Provider.get(
  195. getUserAgent().getEventBroadcaster());
  196. eventProducer.ioError(this, ioe);
  197. ioTrouble = true;
  198. }
  199. }
  200. /** {@inheritDoc} */
  201. public Graphics2DAdapter getGraphics2DAdapter() {
  202. return new PCLGraphics2DAdapter();
  203. }
  204. /** @return the GraphicContext used to track coordinate system transformations */
  205. public GraphicContext getGraphicContext() {
  206. return this.graphicContext;
  207. }
  208. /** @return the target resolution */
  209. protected int getResolution() {
  210. int resolution = Math.round(userAgent.getTargetResolution());
  211. if (resolution <= 300) {
  212. return 300;
  213. } else {
  214. return 600;
  215. }
  216. }
  217. /** {@inheritDoc} */
  218. public void startRenderer(OutputStream outputStream) throws IOException {
  219. log.debug("Rendering areas to PCL...");
  220. this.out = outputStream;
  221. this.gen = new PCLGenerator(out, getResolution());
  222. if (!isPJLDisabled()) {
  223. gen.universalEndOfLanguage();
  224. gen.writeText("@PJL COMMENT Produced by " + userAgent.getProducer() + "\n");
  225. if (userAgent.getTitle() != null) {
  226. gen.writeText("@PJL JOB NAME = \"" + userAgent.getTitle() + "\"\n");
  227. }
  228. gen.writeText("@PJL SET RESOLUTION = " + getResolution() + "\n");
  229. gen.writeText("@PJL ENTER LANGUAGE = PCL\n");
  230. }
  231. gen.resetPrinter();
  232. gen.setUnitOfMeasure(getResolution());
  233. gen.setRasterGraphicsResolution(getResolution());
  234. }
  235. /** {@inheritDoc} */
  236. public void stopRenderer() throws IOException {
  237. gen.separateJobs();
  238. gen.resetPrinter();
  239. if (!isPJLDisabled()) {
  240. gen.universalEndOfLanguage();
  241. }
  242. }
  243. /** {@inheritDoc} */
  244. public String getMimeType() {
  245. return MIME_TYPE;
  246. }
  247. /** {@inheritDoc} */
  248. public void renderPage(PageViewport page) throws IOException, FOPException {
  249. saveGraphicsState();
  250. //Paper source
  251. String paperSource = page.getForeignAttributeValue(PCLElementMapping.PCL_PAPER_SOURCE);
  252. if (paperSource != null) {
  253. gen.selectPaperSource(Integer.parseInt(paperSource));
  254. }
  255. //Output bin
  256. String outputBin = page.getForeignAttributeValue(PCLElementMapping.PCL_OUTPUT_BIN);
  257. if (outputBin != null) {
  258. gen.selectOutputBin(Integer.parseInt(outputBin));
  259. }
  260. // Is Page duplex?
  261. String pageDuplex = page.getForeignAttributeValue(PCLElementMapping.PCL_DUPLEX_MODE);
  262. if (pageDuplex != null) {
  263. gen.selectDuplexMode(Integer.parseInt(pageDuplex));
  264. }
  265. //Page size
  266. final long pagewidth = Math.round(page.getViewArea().getWidth());
  267. final long pageheight = Math.round(page.getViewArea().getHeight());
  268. selectPageFormat(pagewidth, pageheight);
  269. super.renderPage(page);
  270. //Eject page
  271. gen.formFeed();
  272. restoreGraphicsState();
  273. }
  274. private void selectPageFormat(long pagewidth, long pageheight) throws IOException {
  275. //Only set the page format if it changes (otherwise duplex printing won't work)
  276. if ((pagewidth != this.pageWidth) || (pageheight != this.pageHeight)) {
  277. this.pageWidth = pagewidth;
  278. this.pageHeight = pageheight;
  279. this.currentPageDefinition = PCLPageDefinition.getPageDefinition(
  280. pagewidth, pageheight, 1000);
  281. if (this.currentPageDefinition == null) {
  282. this.currentPageDefinition = PCLPageDefinition.getDefaultPageDefinition();
  283. log.warn("Paper type could not be determined. Falling back to: "
  284. + this.currentPageDefinition.getName());
  285. }
  286. if (log.isDebugEnabled()) {
  287. log.debug("page size: " + currentPageDefinition.getPhysicalPageSize());
  288. log.debug("logical page: " + currentPageDefinition.getLogicalPageRect());
  289. }
  290. if (this.currentPageDefinition.isLandscapeFormat()) {
  291. gen.writeCommand("&l1O"); //Landscape Orientation
  292. } else {
  293. gen.writeCommand("&l0O"); //Portrait Orientation
  294. }
  295. gen.selectPageSize(this.currentPageDefinition.getSelector());
  296. gen.clearHorizontalMargins();
  297. gen.setTopMargin(0);
  298. }
  299. }
  300. /** Saves the current graphics state on the stack. */
  301. protected void saveGraphicsState() {
  302. graphicContextStack.push(graphicContext);
  303. graphicContext = (GraphicContext)graphicContext.clone();
  304. }
  305. /** Restores the last graphics state from the stack. */
  306. protected void restoreGraphicsState() {
  307. graphicContext = (GraphicContext)graphicContextStack.pop();
  308. }
  309. /**
  310. * Clip an area. write a clipping operation given coordinates in the current
  311. * transform. Coordinates are in points.
  312. *
  313. * @param x the x coordinate
  314. * @param y the y coordinate
  315. * @param width the width of the area
  316. * @param height the height of the area
  317. */
  318. protected void clipRect(float x, float y, float width, float height) {
  319. //PCL cannot clip (only HP GL/2 can)
  320. }
  321. private Point2D transformedPoint(float x, float y) {
  322. return transformedPoint(Math.round(x), Math.round(y));
  323. }
  324. private Point2D transformedPoint(int x, int y) {
  325. return PCLRenderingUtil.transformedPoint(x, y, graphicContext.getTransform(),
  326. currentPageDefinition, currentPrintDirection);
  327. }
  328. private void changePrintDirection() {
  329. AffineTransform at = graphicContext.getTransform();
  330. int newDir;
  331. try {
  332. newDir = PCLRenderingUtil.determinePrintDirection(at);
  333. if (newDir != this.currentPrintDirection) {
  334. this.currentPrintDirection = newDir;
  335. gen.changePrintDirection(this.currentPrintDirection);
  336. }
  337. } catch (IOException ioe) {
  338. handleIOTrouble(ioe);
  339. }
  340. }
  341. /**
  342. * {@inheritDoc}
  343. */
  344. protected void startVParea(CTM ctm, Rectangle2D clippingRect) {
  345. saveGraphicsState();
  346. AffineTransform at = new AffineTransform(ctm.toArray());
  347. graphicContext.transform(at);
  348. changePrintDirection();
  349. if (log.isDebugEnabled()) {
  350. log.debug("startVPArea: " + at + " --> " + graphicContext.getTransform());
  351. }
  352. }
  353. /**
  354. * {@inheritDoc}
  355. */
  356. protected void endVParea() {
  357. restoreGraphicsState();
  358. changePrintDirection();
  359. if (log.isDebugEnabled()) {
  360. log.debug("endVPArea() --> " + graphicContext.getTransform());
  361. }
  362. }
  363. /**
  364. * Handle block traits.
  365. * The block could be any sort of block with any positioning
  366. * so this should render the traits such as border and background
  367. * in its position.
  368. *
  369. * @param block the block to render the traits
  370. */
  371. protected void handleBlockTraits(Block block) {
  372. int borderPaddingStart = block.getBorderAndPaddingWidthStart();
  373. int borderPaddingBefore = block.getBorderAndPaddingWidthBefore();
  374. float startx = currentIPPosition / 1000f;
  375. float starty = currentBPPosition / 1000f;
  376. float width = block.getIPD() / 1000f;
  377. float height = block.getBPD() / 1000f;
  378. startx += block.getStartIndent() / 1000f;
  379. startx -= block.getBorderAndPaddingWidthStart() / 1000f;
  380. width += borderPaddingStart / 1000f;
  381. width += block.getBorderAndPaddingWidthEnd() / 1000f;
  382. height += borderPaddingBefore / 1000f;
  383. height += block.getBorderAndPaddingWidthAfter() / 1000f;
  384. drawBackAndBorders(block, startx, starty, width, height);
  385. }
  386. /**
  387. * {@inheritDoc}
  388. * @todo Copied from AbstractPathOrientedRenderer
  389. */
  390. protected void handleRegionTraits(RegionViewport region) {
  391. Rectangle2D viewArea = region.getViewArea();
  392. float startx = (float)(viewArea.getX() / 1000f);
  393. float starty = (float)(viewArea.getY() / 1000f);
  394. float width = (float)(viewArea.getWidth() / 1000f);
  395. float height = (float)(viewArea.getHeight() / 1000f);
  396. if (region.getRegionReference().getRegionClass() == FO_REGION_BODY) {
  397. currentBPPosition = region.getBorderAndPaddingWidthBefore();
  398. currentIPPosition = region.getBorderAndPaddingWidthStart();
  399. }
  400. drawBackAndBorders(region, startx, starty, width, height);
  401. }
  402. /**
  403. * {@inheritDoc}
  404. */
  405. protected void renderText(final TextArea text) {
  406. renderInlineAreaBackAndBorders(text);
  407. String fontname = getInternalFontNameForArea(text);
  408. final int fontsize = text.getTraitAsInteger(Trait.FONT_SIZE);
  409. //Determine position
  410. int saveIP = currentIPPosition;
  411. final int rx = currentIPPosition + text.getBorderAndPaddingWidthStart();
  412. int bl = currentBPPosition + text.getOffset() + text.getBaselineOffset();
  413. try {
  414. final Color col = (Color)text.getTrait(Trait.COLOR);
  415. boolean pclFont = pclUtil.isAllTextAsBitmaps()
  416. ? false
  417. : HardcodedFonts.setFont(gen, fontname, fontsize, text.getText());
  418. if (pclFont) {
  419. //this.currentFill = col;
  420. if (col != null) {
  421. //useColor(ct);
  422. gen.setTransparencyMode(true, false);
  423. gen.selectGrayscale(col);
  424. }
  425. saveGraphicsState();
  426. graphicContext.translate(rx, bl);
  427. setCursorPos(0, 0);
  428. gen.setTransparencyMode(true, true);
  429. if (text.hasUnderline()) {
  430. gen.writeCommand("&d0D");
  431. }
  432. super.renderText(text); //Updates IPD and renders words and spaces
  433. if (text.hasUnderline()) {
  434. gen.writeCommand("&d@");
  435. }
  436. restoreGraphicsState();
  437. } else {
  438. //Use Java2D to paint different fonts via bitmap
  439. final Font font = getFontFromArea(text);
  440. final int baseline = text.getBaselineOffset();
  441. //for cursive fonts, so the text isn't clipped
  442. int extraWidth = font.getFontSize() / 3;
  443. final FontMetricsMapper mapper = (FontMetricsMapper)fontInfo.getMetricsFor(
  444. font.getFontName());
  445. int maxAscent = mapper.getMaxAscent(font.getFontSize()) / 1000;
  446. final int additionalBPD = maxAscent - baseline;
  447. Graphics2DAdapter g2a = getGraphics2DAdapter();
  448. final Rectangle paintRect = new Rectangle(
  449. rx, currentBPPosition + text.getOffset() - additionalBPD,
  450. text.getIPD() + extraWidth, text.getBPD() + additionalBPD);
  451. RendererContext rc = createRendererContext(paintRect.x, paintRect.y,
  452. paintRect.width, paintRect.height, null);
  453. Map atts = new java.util.HashMap();
  454. atts.put(ImageHandlerUtil.CONVERSION_MODE, ImageHandlerUtil.CONVERSION_MODE_BITMAP);
  455. atts.put(SRC_TRANSPARENCY, "true");
  456. rc.setProperty(RendererContextConstants.FOREIGN_ATTRIBUTES, atts);
  457. Graphics2DImagePainter painter = new Graphics2DImagePainter() {
  458. public void paint(Graphics2D g2d, Rectangle2D area) {
  459. g2d.setFont(mapper.getFont(font.getFontSize()));
  460. g2d.translate(0, baseline + additionalBPD);
  461. g2d.scale(1000, 1000);
  462. g2d.setColor(col);
  463. Java2DRenderer.renderText(text, g2d, font);
  464. renderTextDecoration(g2d, mapper, fontsize, text, 0, 0);
  465. }
  466. public Dimension getImageSize() {
  467. return paintRect.getSize();
  468. }
  469. };
  470. g2a.paintImage(painter, rc,
  471. paintRect.x, paintRect.y, paintRect.width, paintRect.height);
  472. currentIPPosition = saveIP + text.getAllocIPD();
  473. }
  474. } catch (IOException ioe) {
  475. handleIOTrouble(ioe);
  476. }
  477. }
  478. /**
  479. * Paints the text decoration marks.
  480. * @param g2d Graphics2D instance to paint to
  481. * @param fm Current typeface
  482. * @param fontsize Current font size
  483. * @param inline inline area to paint the marks for
  484. * @param baseline position of the baseline
  485. * @param startx start IPD
  486. */
  487. private static void renderTextDecoration(Graphics2D g2d,
  488. FontMetrics fm, int fontsize, InlineArea inline,
  489. int baseline, int startx) {
  490. boolean hasTextDeco = inline.hasUnderline()
  491. || inline.hasOverline()
  492. || inline.hasLineThrough();
  493. if (hasTextDeco) {
  494. float descender = fm.getDescender(fontsize) / 1000f;
  495. float capHeight = fm.getCapHeight(fontsize) / 1000f;
  496. float lineWidth = (descender / -4f) / 1000f;
  497. float endx = (startx + inline.getIPD()) / 1000f;
  498. if (inline.hasUnderline()) {
  499. Color ct = (Color) inline.getTrait(Trait.UNDERLINE_COLOR);
  500. g2d.setColor(ct);
  501. float y = baseline - descender / 2f;
  502. g2d.setStroke(new BasicStroke(lineWidth));
  503. g2d.draw(new Line2D.Float(startx / 1000f, y / 1000f,
  504. endx, y / 1000f));
  505. }
  506. if (inline.hasOverline()) {
  507. Color ct = (Color) inline.getTrait(Trait.OVERLINE_COLOR);
  508. g2d.setColor(ct);
  509. float y = (float)(baseline - (1.1 * capHeight));
  510. g2d.setStroke(new BasicStroke(lineWidth));
  511. g2d.draw(new Line2D.Float(startx / 1000f, y / 1000f,
  512. endx, y / 1000f));
  513. }
  514. if (inline.hasLineThrough()) {
  515. Color ct = (Color) inline.getTrait(Trait.LINETHROUGH_COLOR);
  516. g2d.setColor(ct);
  517. float y = (float)(baseline - (0.45 * capHeight));
  518. g2d.setStroke(new BasicStroke(lineWidth));
  519. g2d.draw(new Line2D.Float(startx / 1000f, y / 1000f,
  520. endx, y / 1000f));
  521. }
  522. }
  523. }
  524. /**
  525. * Sets the current cursor position. The coordinates are transformed to the absolute position
  526. * on the logical PCL page and then passed on to the PCLGenerator.
  527. * @param x the x coordinate (in millipoints)
  528. * @param y the y coordinate (in millipoints)
  529. */
  530. void setCursorPos(float x, float y) {
  531. try {
  532. Point2D transPoint = transformedPoint(x, y);
  533. gen.setCursorPos(transPoint.getX(), transPoint.getY());
  534. } catch (IOException ioe) {
  535. handleIOTrouble(ioe);
  536. }
  537. }
  538. /** Clip using the current path. */
  539. protected void clip() {
  540. if (currentPath == null) {
  541. throw new IllegalStateException("No current path available!");
  542. }
  543. //TODO Find a good way to do clipping. PCL itself cannot clip.
  544. currentPath = null;
  545. }
  546. /**
  547. * Closes the current subpath by appending a straight line segment from
  548. * the current point to the starting point of the subpath.
  549. */
  550. protected void closePath() {
  551. currentPath.closePath();
  552. }
  553. /**
  554. * Appends a straight line segment from the current point to (x, y). The
  555. * new current point is (x, y).
  556. * @param x x coordinate
  557. * @param y y coordinate
  558. */
  559. protected void lineTo(float x, float y) {
  560. if (currentPath == null) {
  561. currentPath = new GeneralPath();
  562. }
  563. currentPath.lineTo(x, y);
  564. }
  565. /**
  566. * Moves the current point to (x, y), omitting any connecting line segment.
  567. * @param x x coordinate
  568. * @param y y coordinate
  569. */
  570. protected void moveTo(float x, float y) {
  571. if (currentPath == null) {
  572. currentPath = new GeneralPath();
  573. }
  574. currentPath.moveTo(x, y);
  575. }
  576. /**
  577. * Fill a rectangular area.
  578. * @param x the x coordinate (in pt)
  579. * @param y the y coordinate (in pt)
  580. * @param width the width of the rectangle
  581. * @param height the height of the rectangle
  582. */
  583. protected void fillRect(float x, float y, float width, float height) {
  584. try {
  585. setCursorPos(x * 1000, y * 1000);
  586. gen.fillRect((int)(width * 1000), (int)(height * 1000),
  587. this.currentFillColor);
  588. } catch (IOException ioe) {
  589. handleIOTrouble(ioe);
  590. }
  591. }
  592. /**
  593. * Sets the new current fill color.
  594. * @param color the color
  595. */
  596. protected void updateFillColor(java.awt.Color color) {
  597. this.currentFillColor = color;
  598. }
  599. /**
  600. * {@inheritDoc}
  601. */
  602. protected void renderWord(WordArea word) {
  603. //Font font = getFontFromArea(word.getParentArea());
  604. String s = word.getWord();
  605. try {
  606. gen.writeText(s);
  607. } catch (IOException ioe) {
  608. handleIOTrouble(ioe);
  609. }
  610. super.renderWord(word);
  611. }
  612. /**
  613. * {@inheritDoc}
  614. */
  615. protected void renderSpace(SpaceArea space) {
  616. AbstractTextArea textArea = (AbstractTextArea)space.getParentArea();
  617. String s = space.getSpace();
  618. char sp = s.charAt(0);
  619. Font font = getFontFromArea(textArea);
  620. int tws = (space.isAdjustable()
  621. ? textArea.getTextWordSpaceAdjust()
  622. + 2 * textArea.getTextLetterSpaceAdjust()
  623. : 0);
  624. double dx = (font.getCharWidth(sp) + tws) / 100f;
  625. try {
  626. gen.writeCommand("&a+" + gen.formatDouble2(dx) + "H");
  627. } catch (IOException ioe) {
  628. handleIOTrouble(ioe);
  629. }
  630. super.renderSpace(space);
  631. }
  632. /**
  633. * Render an inline viewport.
  634. * This renders an inline viewport by clipping if necessary.
  635. * @param viewport the viewport to handle
  636. * @todo Copied from AbstractPathOrientedRenderer
  637. */
  638. public void renderViewport(Viewport viewport) {
  639. float x = currentIPPosition / 1000f;
  640. float y = (currentBPPosition + viewport.getOffset()) / 1000f;
  641. float width = viewport.getIPD() / 1000f;
  642. float height = viewport.getBPD() / 1000f;
  643. // TODO: Calculate the border rect correctly.
  644. float borderPaddingStart = viewport.getBorderAndPaddingWidthStart() / 1000f;
  645. float borderPaddingBefore = viewport.getBorderAndPaddingWidthBefore() / 1000f;
  646. float bpwidth = borderPaddingStart
  647. + (viewport.getBorderAndPaddingWidthEnd() / 1000f);
  648. float bpheight = borderPaddingBefore
  649. + (viewport.getBorderAndPaddingWidthAfter() / 1000f);
  650. drawBackAndBorders(viewport, x, y, width + bpwidth, height + bpheight);
  651. if (viewport.getClip()) {
  652. saveGraphicsState();
  653. clipRect(x + borderPaddingStart, y + borderPaddingBefore, width, height);
  654. }
  655. super.renderViewport(viewport);
  656. if (viewport.getClip()) {
  657. restoreGraphicsState();
  658. }
  659. }
  660. /**
  661. * {@inheritDoc}
  662. */
  663. protected void renderBlockViewport(BlockViewport bv, List children) {
  664. // clip and position viewport if necessary
  665. // save positions
  666. int saveIP = currentIPPosition;
  667. int saveBP = currentBPPosition;
  668. CTM ctm = bv.getCTM();
  669. int borderPaddingStart = bv.getBorderAndPaddingWidthStart();
  670. int borderPaddingBefore = bv.getBorderAndPaddingWidthBefore();
  671. //This is the content-rect
  672. float width = bv.getIPD() / 1000f;
  673. float height = bv.getBPD() / 1000f;
  674. if (bv.getPositioning() == Block.ABSOLUTE
  675. || bv.getPositioning() == Block.FIXED) {
  676. //For FIXED, we need to break out of the current viewports to the
  677. //one established by the page. We save the state stack for restoration
  678. //after the block-container has been painted. See below.
  679. List breakOutList = null;
  680. if (bv.getPositioning() == Block.FIXED) {
  681. breakOutList = breakOutOfStateStack();
  682. }
  683. AffineTransform positionTransform = new AffineTransform();
  684. positionTransform.translate(bv.getXOffset(), bv.getYOffset());
  685. //"left/"top" (bv.getX/YOffset()) specify the position of the content rectangle
  686. positionTransform.translate(-borderPaddingStart, -borderPaddingBefore);
  687. saveGraphicsState();
  688. //Viewport position
  689. concatenateTransformationMatrix(UnitConv.mptToPt(positionTransform));
  690. //Background and borders
  691. float bpwidth = (borderPaddingStart + bv.getBorderAndPaddingWidthEnd()) / 1000f;
  692. float bpheight = (borderPaddingBefore + bv.getBorderAndPaddingWidthAfter()) / 1000f;
  693. drawBackAndBorders(bv, 0, 0, width + bpwidth, height + bpheight);
  694. //Shift to content rectangle after border painting
  695. AffineTransform contentRectTransform = new AffineTransform();
  696. contentRectTransform.translate(borderPaddingStart, borderPaddingBefore);
  697. concatenateTransformationMatrix(UnitConv.mptToPt(contentRectTransform));
  698. //Clipping
  699. if (bv.getClip()) {
  700. clipRect(0f, 0f, width, height);
  701. }
  702. saveGraphicsState();
  703. //Set up coordinate system for content rectangle
  704. AffineTransform contentTransform = ctm.toAffineTransform();
  705. concatenateTransformationMatrix(UnitConv.mptToPt(contentTransform));
  706. currentIPPosition = 0;
  707. currentBPPosition = 0;
  708. renderBlocks(bv, children);
  709. restoreGraphicsState();
  710. restoreGraphicsState();
  711. if (breakOutList != null) {
  712. restoreStateStackAfterBreakOut(breakOutList);
  713. }
  714. currentIPPosition = saveIP;
  715. currentBPPosition = saveBP;
  716. } else {
  717. currentBPPosition += bv.getSpaceBefore();
  718. //borders and background in the old coordinate system
  719. handleBlockTraits(bv);
  720. //Advance to start of content area
  721. currentIPPosition += bv.getStartIndent();
  722. CTM tempctm = new CTM(containingIPPosition, currentBPPosition);
  723. ctm = tempctm.multiply(ctm);
  724. //Now adjust for border/padding
  725. currentBPPosition += borderPaddingBefore;
  726. Rectangle2D clippingRect = null;
  727. if (bv.getClip()) {
  728. clippingRect = new Rectangle(currentIPPosition, currentBPPosition,
  729. bv.getIPD(), bv.getBPD());
  730. }
  731. startVParea(ctm, clippingRect);
  732. currentIPPosition = 0;
  733. currentBPPosition = 0;
  734. renderBlocks(bv, children);
  735. endVParea();
  736. currentIPPosition = saveIP;
  737. currentBPPosition = saveBP;
  738. currentBPPosition += (bv.getAllocBPD());
  739. }
  740. //currentFontName = saveFontName;
  741. }
  742. /** {@inheritDoc} */
  743. protected void renderReferenceArea(Block block) {
  744. //TODO This is the same code as in AbstractPathOrientedRenderer
  745. //So there's some optimization potential but not otherwise PCLRenderer is a little
  746. //difficult to derive from AbstractPathOrientedRenderer. Maybe an additional layer
  747. //between PrintRenderer and AbstractPathOrientedRenderer is necessary.
  748. // save position and offset
  749. int saveIP = currentIPPosition;
  750. int saveBP = currentBPPosition;
  751. //Establish a new coordinate system
  752. AffineTransform at = new AffineTransform();
  753. at.translate(currentIPPosition, currentBPPosition);
  754. at.translate(block.getXOffset(), block.getYOffset());
  755. at.translate(0, block.getSpaceBefore());
  756. if (!at.isIdentity()) {
  757. saveGraphicsState();
  758. concatenateTransformationMatrix(UnitConv.mptToPt(at));
  759. }
  760. currentIPPosition = 0;
  761. currentBPPosition = 0;
  762. handleBlockTraits(block);
  763. List children = block.getChildAreas();
  764. if (children != null) {
  765. renderBlocks(block, children);
  766. }
  767. if (!at.isIdentity()) {
  768. restoreGraphicsState();
  769. }
  770. // stacked and relative blocks effect stacking
  771. currentIPPosition = saveIP;
  772. currentBPPosition = saveBP;
  773. }
  774. /** {@inheritDoc} */
  775. protected void renderFlow(NormalFlow flow) {
  776. //TODO This is the same code as in AbstractPathOrientedRenderer
  777. //So there's some optimization potential but not otherwise PCLRenderer is a little
  778. //difficult to derive from AbstractPathOrientedRenderer. Maybe an additional layer
  779. //between PrintRenderer and AbstractPathOrientedRenderer is necessary.
  780. // save position and offset
  781. int saveIP = currentIPPosition;
  782. int saveBP = currentBPPosition;
  783. //Establish a new coordinate system
  784. AffineTransform at = new AffineTransform();
  785. at.translate(currentIPPosition, currentBPPosition);
  786. if (!at.isIdentity()) {
  787. saveGraphicsState();
  788. concatenateTransformationMatrix(UnitConv.mptToPt(at));
  789. }
  790. currentIPPosition = 0;
  791. currentBPPosition = 0;
  792. super.renderFlow(flow);
  793. if (!at.isIdentity()) {
  794. restoreGraphicsState();
  795. }
  796. // stacked and relative blocks effect stacking
  797. currentIPPosition = saveIP;
  798. currentBPPosition = saveBP;
  799. }
  800. /**
  801. * Concatenates the current transformation matrix with the given one, therefore establishing
  802. * a new coordinate system.
  803. * @param at the transformation matrix to process (coordinates in points)
  804. */
  805. protected void concatenateTransformationMatrix(AffineTransform at) {
  806. if (!at.isIdentity()) {
  807. graphicContext.transform(UnitConv.ptToMpt(at));
  808. changePrintDirection();
  809. }
  810. }
  811. private List breakOutOfStateStack() {
  812. log.debug("Block.FIXED --> break out");
  813. List breakOutList = new java.util.ArrayList();
  814. while (!this.graphicContextStack.empty()) {
  815. breakOutList.add(0, this.graphicContext);
  816. restoreGraphicsState();
  817. }
  818. return breakOutList;
  819. }
  820. private void restoreStateStackAfterBreakOut(List breakOutList) {
  821. log.debug("Block.FIXED --> restoring context after break-out");
  822. for (int i = 0, c = breakOutList.size(); i < c; i++) {
  823. saveGraphicsState();
  824. this.graphicContext = (GraphicContext)breakOutList.get(i);
  825. }
  826. }
  827. /** {@inheritDoc} */
  828. protected RendererContext createRendererContext(int x, int y, int width, int height,
  829. Map foreignAttributes) {
  830. RendererContext context = super.createRendererContext(
  831. x, y, width, height, foreignAttributes);
  832. context.setProperty(PCLRendererContextConstants.PCL_COLOR_CANVAS,
  833. Boolean.valueOf(pclUtil.isColorCanvasEnabled()));
  834. return context;
  835. }
  836. /** {@inheritDoc} */
  837. public void renderImage(Image image, Rectangle2D pos) {
  838. drawImage(image.getURL(), pos, image.getForeignAttributes());
  839. }
  840. private static final ImageFlavor[] FLAVORS = new ImageFlavor[]
  841. {ImageFlavor.GRAPHICS2D,
  842. ImageFlavor.BUFFERED_IMAGE,
  843. ImageFlavor.RENDERED_IMAGE,
  844. ImageFlavor.XML_DOM};
  845. /**
  846. * Draw an image at the indicated location.
  847. * @param uri the URI/URL of the image
  848. * @param pos the position of the image
  849. * @param foreignAttributes an optional Map with foreign attributes, may be null
  850. */
  851. protected void drawImage(String uri, Rectangle2D pos, Map foreignAttributes) {
  852. uri = URISpecification.getURL(uri);
  853. Rectangle posInt = new Rectangle(
  854. (int)pos.getX(),
  855. (int)pos.getY(),
  856. (int)pos.getWidth(),
  857. (int)pos.getHeight());
  858. Point origin = new Point(currentIPPosition, currentBPPosition);
  859. int x = origin.x + posInt.x;
  860. int y = origin.y + posInt.y;
  861. ImageManager manager = getUserAgent().getFactory().getImageManager();
  862. ImageInfo info = null;
  863. try {
  864. ImageSessionContext sessionContext = getUserAgent().getImageSessionContext();
  865. info = manager.getImageInfo(uri, sessionContext);
  866. //Only now fully load/prepare the image
  867. Map hints = ImageUtil.getDefaultHints(sessionContext);
  868. org.apache.xmlgraphics.image.loader.Image img = manager.getImage(
  869. info, FLAVORS, hints, sessionContext);
  870. //...and process the image
  871. if (img instanceof ImageGraphics2D) {
  872. ImageGraphics2D imageG2D = (ImageGraphics2D)img;
  873. RendererContext context = createRendererContext(
  874. posInt.x, posInt.y,
  875. posInt.width, posInt.height, foreignAttributes);
  876. getGraphics2DAdapter().paintImage(imageG2D.getGraphics2DImagePainter(),
  877. context, x, y, posInt.width, posInt.height);
  878. } else if (img instanceof ImageRendered) {
  879. ImageRendered imgRend = (ImageRendered)img;
  880. RenderedImage ri = imgRend.getRenderedImage();
  881. setCursorPos(x, y);
  882. gen.paintBitmap(ri,
  883. new Dimension(posInt.width, posInt.height),
  884. false);
  885. } else if (img instanceof ImageXMLDOM) {
  886. ImageXMLDOM imgXML = (ImageXMLDOM)img;
  887. renderDocument(imgXML.getDocument(), imgXML.getRootNamespace(),
  888. pos, foreignAttributes);
  889. } else {
  890. throw new UnsupportedOperationException("Unsupported image type: " + img);
  891. }
  892. } catch (ImageException ie) {
  893. ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get(
  894. getUserAgent().getEventBroadcaster());
  895. eventProducer.imageError(this, (info != null ? info.toString() : uri), ie, null);
  896. } catch (FileNotFoundException fe) {
  897. ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get(
  898. getUserAgent().getEventBroadcaster());
  899. eventProducer.imageNotFound(this, (info != null ? info.toString() : uri), fe, null);
  900. } catch (IOException ioe) {
  901. ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get(
  902. getUserAgent().getEventBroadcaster());
  903. eventProducer.imageIOError(this, (info != null ? info.toString() : uri), ioe, null);
  904. }
  905. }
  906. /** {@inheritDoc} */
  907. public void renderForeignObject(ForeignObject fo, Rectangle2D pos) {
  908. Document doc = fo.getDocument();
  909. String ns = fo.getNameSpace();
  910. renderDocument(doc, ns, pos, fo.getForeignAttributes());
  911. }
  912. /**
  913. * Common method to render the background and borders for any inline area.
  914. * The all borders and padding are drawn outside the specified area.
  915. * @param area the inline area for which the background, border and padding is to be
  916. * rendered
  917. * @todo Copied from AbstractPathOrientedRenderer
  918. */
  919. protected void renderInlineAreaBackAndBorders(InlineArea area) {
  920. float x = currentIPPosition / 1000f;
  921. float y = (currentBPPosition + area.getOffset()) / 1000f;
  922. float width = area.getIPD() / 1000f;
  923. float height = area.getBPD() / 1000f;
  924. float borderPaddingStart = area.getBorderAndPaddingWidthStart() / 1000f;
  925. float borderPaddingBefore = area.getBorderAndPaddingWidthBefore() / 1000f;
  926. float bpwidth = borderPaddingStart
  927. + (area.getBorderAndPaddingWidthEnd() / 1000f);
  928. float bpheight = borderPaddingBefore
  929. + (area.getBorderAndPaddingWidthAfter() / 1000f);
  930. if (height != 0.0f || bpheight != 0.0f && bpwidth != 0.0f) {
  931. drawBackAndBorders(area, x, y - borderPaddingBefore
  932. , width + bpwidth
  933. , height + bpheight);
  934. }
  935. }
  936. /**
  937. * Draw the background and borders. This draws the background and border
  938. * traits for an area given the position.
  939. *
  940. * @param area the area whose traits are used
  941. * @param startx the start x position
  942. * @param starty the start y position
  943. * @param width the width of the area
  944. * @param height the height of the area
  945. */
  946. protected void drawBackAndBorders(Area area, float startx, float starty,
  947. float width, float height) {
  948. BorderProps bpsBefore = (BorderProps) area.getTrait(Trait.BORDER_BEFORE);
  949. BorderProps bpsAfter = (BorderProps) area.getTrait(Trait.BORDER_AFTER);
  950. BorderProps bpsStart = (BorderProps) area.getTrait(Trait.BORDER_START);
  951. BorderProps bpsEnd = (BorderProps) area.getTrait(Trait.BORDER_END);
  952. // draw background
  953. Trait.Background back;
  954. back = (Trait.Background) area.getTrait(Trait.BACKGROUND);
  955. if (back != null) {
  956. // Calculate padding rectangle
  957. float sx = startx;
  958. float sy = starty;
  959. float paddRectWidth = width;
  960. float paddRectHeight = height;
  961. if (bpsStart != null) {
  962. sx += bpsStart.width / 1000f;
  963. paddRectWidth -= bpsStart.width / 1000f;
  964. }
  965. if (bpsBefore != null) {
  966. sy += bpsBefore.width / 1000f;
  967. paddRectHeight -= bpsBefore.width / 1000f;
  968. }
  969. if (bpsEnd != null) {
  970. paddRectWidth -= bpsEnd.width / 1000f;
  971. }
  972. if (bpsAfter != null) {
  973. paddRectHeight -= bpsAfter.width / 1000f;
  974. }
  975. if (back.getColor() != null) {
  976. updateFillColor(back.getColor());
  977. fillRect(sx, sy, paddRectWidth, paddRectHeight);
  978. }
  979. // background image
  980. if (back.getImageInfo() != null) {
  981. ImageSize imageSize = back.getImageInfo().getSize();
  982. saveGraphicsState();
  983. clipRect(sx, sy, paddRectWidth, paddRectHeight);
  984. int horzCount = (int) ((paddRectWidth * 1000 / imageSize.getWidthMpt()) + 1.0f);
  985. int vertCount = (int) ((paddRectHeight * 1000 / imageSize.getHeightMpt()) + 1.0f);
  986. if (back.getRepeat() == EN_NOREPEAT) {
  987. horzCount = 1;
  988. vertCount = 1;
  989. } else if (back.getRepeat() == EN_REPEATX) {
  990. vertCount = 1;
  991. } else if (back.getRepeat() == EN_REPEATY) {
  992. horzCount = 1;
  993. }
  994. // change from points to millipoints
  995. sx *= 1000;
  996. sy *= 1000;
  997. if (horzCount == 1) {
  998. sx += back.getHoriz();
  999. }
  1000. if (vertCount == 1) {
  1001. sy += back.getVertical();
  1002. }
  1003. for (int x = 0; x < horzCount; x++) {
  1004. for (int y = 0; y < vertCount; y++) {
  1005. // place once
  1006. Rectangle2D pos;
  1007. // Image positions are relative to the currentIP/BP
  1008. pos = new Rectangle2D.Float(
  1009. sx - currentIPPosition
  1010. + (x * imageSize.getWidthMpt()),
  1011. sy - currentBPPosition
  1012. + (y * imageSize.getHeightMpt()),
  1013. imageSize.getWidthMpt(),
  1014. imageSize.getHeightMpt());
  1015. drawImage(back.getURL(), pos, null);
  1016. }
  1017. }
  1018. restoreGraphicsState();
  1019. }
  1020. }
  1021. Rectangle2D.Float borderRect = new Rectangle2D.Float(startx, starty, width, height);
  1022. drawBorders(borderRect, bpsBefore, bpsAfter, bpsStart, bpsEnd);
  1023. }
  1024. /**
  1025. * Draws borders.
  1026. * @param borderRect the border rectangle
  1027. * @param bpsBefore the border specification on the before side
  1028. * @param bpsAfter the border specification on the after side
  1029. * @param bpsStart the border specification on the start side
  1030. * @param bpsEnd the border specification on the end side
  1031. */
  1032. protected void drawBorders(Rectangle2D.Float borderRect,
  1033. final BorderProps bpsBefore, final BorderProps bpsAfter,
  1034. final BorderProps bpsStart, final BorderProps bpsEnd) {
  1035. if (bpsBefore == null && bpsAfter == null && bpsStart == null && bpsEnd == null) {
  1036. return; //no borders to paint
  1037. }
  1038. if (PCLRenderingMode.SPEED == pclUtil.getRenderingMode()) {
  1039. drawFastBorders(borderRect, bpsBefore, bpsAfter, bpsStart, bpsEnd);
  1040. } else {
  1041. drawQualityBorders(borderRect, bpsBefore, bpsAfter, bpsStart, bpsEnd);
  1042. }
  1043. }
  1044. /**
  1045. * Draws borders. Borders are drawn as shaded rectangles with no clipping.
  1046. * @param borderRect the border rectangle
  1047. * @param bpsBefore the border specification on the before side
  1048. * @param bpsAfter the border specification on the after side
  1049. * @param bpsStart the border specification on the start side
  1050. * @param bpsEnd the border specification on the end side
  1051. */
  1052. protected void drawFastBorders(Rectangle2D.Float borderRect,
  1053. final BorderProps bpsBefore, final BorderProps bpsAfter,
  1054. final BorderProps bpsStart, final BorderProps bpsEnd) {
  1055. float startx = borderRect.x;
  1056. float starty = borderRect.y;
  1057. float width = borderRect.width;
  1058. float height = borderRect.height;
  1059. if (bpsBefore != null) {
  1060. float borderWidth = bpsBefore.width / 1000f;
  1061. updateFillColor(bpsBefore.color);
  1062. fillRect(startx, starty, width, borderWidth);
  1063. }
  1064. if (bpsAfter != null) {
  1065. float borderWidth = bpsAfter.width / 1000f;
  1066. updateFillColor(bpsAfter.color);
  1067. fillRect(startx, (starty + height - borderWidth),
  1068. width, borderWidth);
  1069. }
  1070. if (bpsStart != null) {
  1071. float borderWidth = bpsStart.width / 1000f;
  1072. updateFillColor(bpsStart.color);
  1073. fillRect(startx, starty, borderWidth, height);
  1074. }
  1075. if (bpsEnd != null) {
  1076. float borderWidth = bpsEnd.width / 1000f;
  1077. updateFillColor(bpsEnd.color);
  1078. fillRect((startx + width - borderWidth), starty, borderWidth, height);
  1079. }
  1080. }
  1081. /**
  1082. * Draws borders. Borders are drawn in-memory and painted as a bitmap.
  1083. * @param borderRect the border rectangle
  1084. * @param bpsBefore the border specification on the before side
  1085. * @param bpsAfter the border specification on the after side
  1086. * @param bpsStart the border specification on the start side
  1087. * @param bpsEnd the border specification on the end side
  1088. */
  1089. protected void drawQualityBorders(Rectangle2D.Float borderRect,
  1090. final BorderProps bpsBefore, final BorderProps bpsAfter,
  1091. final BorderProps bpsStart, final BorderProps bpsEnd) {
  1092. Graphics2DAdapter g2a = getGraphics2DAdapter();
  1093. final Rectangle.Float effBorderRect = new Rectangle2D.Float(
  1094. 0,
  1095. 0,
  1096. borderRect.width,
  1097. borderRect.height);
  1098. final Rectangle paintRect = new Rectangle(
  1099. Math.round(borderRect.x * 1000f),
  1100. Math.round(borderRect.y * 1000f),
  1101. (int)Math.floor(borderRect.width * 1000f) + 1,
  1102. (int)Math.floor(borderRect.height * 1000f) + 1);
  1103. //Add one pixel wide safety margin around the paint area
  1104. int pixelWidth = (int)Math.round(UnitConv.in2mpt(1) / userAgent.getTargetResolution());
  1105. final int xoffset = Math.round(-effBorderRect.x * 1000f) + pixelWidth;
  1106. final int yoffset = pixelWidth;
  1107. paintRect.x += xoffset;
  1108. paintRect.y += yoffset;
  1109. paintRect.width += 2 * pixelWidth;
  1110. paintRect.height += 2 * pixelWidth;
  1111. RendererContext rc = createRendererContext(paintRect.x, paintRect.y,
  1112. paintRect.width, paintRect.height, null);
  1113. Map atts = new java.util.HashMap();
  1114. atts.put(ImageHandlerUtil.CONVERSION_MODE, ImageHandlerUtil.CONVERSION_MODE_BITMAP);
  1115. atts.put(SRC_TRANSPARENCY, "true");
  1116. rc.setProperty(RendererContextConstants.FOREIGN_ATTRIBUTES, atts);
  1117. Graphics2DImagePainter painter = new Graphics2DImagePainter() {
  1118. public void paint(Graphics2D g2d, Rectangle2D area) {
  1119. g2d.translate(xoffset, yoffset);
  1120. g2d.scale(1000, 1000);
  1121. float startx = effBorderRect.x;
  1122. float starty = effBorderRect.y;
  1123. float width = effBorderRect.width;
  1124. float height = effBorderRect.height;
  1125. boolean[] b = new boolean[] {
  1126. (bpsBefore != null), (bpsEnd != null),
  1127. (bpsAfter != null), (bpsStart != null)};
  1128. if (!b[0] && !b[1] && !b[2] && !b[3]) {
  1129. return;
  1130. }
  1131. float[] bw = new float[] {
  1132. (b[0] ? bpsBefore.width / 1000f : 0.0f),
  1133. (b[1] ? bpsEnd.width / 1000f : 0.0f),
  1134. (b[2] ? bpsAfter.width / 1000f : 0.0f),
  1135. (b[3] ? bpsStart.width / 1000f : 0.0f)};
  1136. float[] clipw = new float[] {
  1137. BorderProps.getClippedWidth(bpsBefore) / 1000f,
  1138. BorderProps.getClippedWidth(bpsEnd) / 1000f,
  1139. BorderProps.getClippedWidth(bpsAfter) / 1000f,
  1140. BorderProps.getClippedWidth(bpsStart) / 1000f};
  1141. starty += clipw[0];
  1142. height -= clipw[0];
  1143. height -= clipw[2];
  1144. startx += clipw[3];
  1145. width -= clipw[3];
  1146. width -= clipw[1];
  1147. boolean[] slant = new boolean[] {
  1148. (b[3] && b[0]), (b[0] && b[1]), (b[1] && b[2]), (b[2] && b[3])};
  1149. if (bpsBefore != null) {
  1150. //endTextObject();
  1151. float sx1 = startx;
  1152. float sx2 = (slant[0] ? sx1 + bw[3] - clipw[3] : sx1);
  1153. float ex1 = startx + width;
  1154. float ex2 = (slant[1] ? ex1 - bw[1] + clipw[1] : ex1);
  1155. float outery = starty - clipw[0];
  1156. float clipy = outery + clipw[0];
  1157. float innery = outery + bw[0];
  1158. //saveGraphicsState();
  1159. Graphics2D g = (Graphics2D)g2d.create();
  1160. moveTo(sx1, clipy);
  1161. float sx1a = sx1;
  1162. float ex1a = ex1;
  1163. if (bpsBefore.mode == BorderProps.COLLAPSE_OUTER) {
  1164. if (bpsStart != null && bpsStart.mode == BorderProps.COLLAPSE_OUTER) {
  1165. sx1a -= clipw[3];
  1166. }
  1167. if (bpsEnd != null && bpsEnd.mode == BorderProps.COLLAPSE_OUTER) {
  1168. ex1a += clipw[1];
  1169. }
  1170. lineTo(sx1a, outery);
  1171. lineTo(ex1a, outery);
  1172. }
  1173. lineTo(ex1, clipy);
  1174. lineTo(ex2, innery);
  1175. lineTo(sx2, innery);
  1176. closePath();
  1177. //clip();
  1178. g.clip(currentPath);
  1179. currentPath = null;
  1180. Rectangle2D.Float lineRect = new Rectangle2D.Float(
  1181. sx1a, outery, ex1a - sx1a, innery - outery);
  1182. Java2DRenderer.drawBorderLine(lineRect, true, true,
  1183. bpsBefore.style, bpsBefore.color, g);
  1184. //restoreGraphicsState();
  1185. }
  1186. if (bpsEnd != null) {
  1187. //endTextObject();
  1188. float sy1 = starty;
  1189. float sy2 = (slant[1] ? sy1 + bw[0] - clipw[0] : sy1);
  1190. float ey1 = starty + height;
  1191. float ey2 = (slant[2] ? ey1 - bw[2] + clipw[2] : ey1);
  1192. float outerx = startx + width + clipw[1];
  1193. float clipx = outerx - clipw[1];
  1194. float innerx = outerx - bw[1];
  1195. //saveGraphicsState();
  1196. Graphics2D g = (Graphics2D)g2d.create();
  1197. moveTo(clipx, sy1);
  1198. float sy1a = sy1;
  1199. float ey1a = ey1;
  1200. if (bpsEnd.mode == BorderProps.COLLAPSE_OUTER) {
  1201. if (bpsBefore != null && bpsBefore.mode == BorderProps.COLLAPSE_OUTER) {
  1202. sy1a -= clipw[0];
  1203. }
  1204. if (bpsAfter != null && bpsAfter.mode == BorderProps.COLLAPSE_OUTER) {
  1205. ey1a += clipw[2];
  1206. }
  1207. lineTo(outerx, sy1a);
  1208. lineTo(outerx, ey1a);
  1209. }
  1210. lineTo(clipx, ey1);
  1211. lineTo(innerx, ey2);
  1212. lineTo(innerx, sy2);
  1213. closePath();
  1214. //clip();
  1215. g.setClip(currentPath);
  1216. currentPath = null;
  1217. Rectangle2D.Float lineRect = new Rectangle2D.Float(
  1218. innerx, sy1a, outerx - innerx, ey1a - sy1a);
  1219. Java2DRenderer.drawBorderLine(lineRect, false, false,
  1220. bpsEnd.style, bpsEnd.color, g);
  1221. //restoreGraphicsState();
  1222. }
  1223. if (bpsAfter != null) {
  1224. //endTextObject();
  1225. float sx1 = startx;
  1226. float sx2 = (slant[3] ? sx1 + bw[3] - clipw[3] : sx1);
  1227. float ex1 = startx + width;
  1228. float ex2 = (slant[2] ? ex1 - bw[1] + clipw[1] : ex1);
  1229. float outery = starty + height + clipw[2];
  1230. float clipy = outery - clipw[2];
  1231. float innery = outery - bw[2];
  1232. //saveGraphicsState();
  1233. Graphics2D g = (Graphics2D)g2d.create();
  1234. moveTo(ex1, clipy);
  1235. float sx1a = sx1;
  1236. float ex1a = ex1;
  1237. if (bpsAfter.mode == BorderProps.COLLAPSE_OUTER) {
  1238. if (bpsStart != null && bpsStart.mode == BorderProps.COLLAPSE_OUTER) {
  1239. sx1a -= clipw[3];
  1240. }
  1241. if (bpsEnd != null && bpsEnd.mode == BorderProps.COLLAPSE_OUTER) {
  1242. ex1a += clipw[1];
  1243. }
  1244. lineTo(ex1a, outery);
  1245. lineTo(sx1a, outery);
  1246. }
  1247. lineTo(sx1, clipy);
  1248. lineTo(sx2, innery);
  1249. lineTo(ex2, innery);
  1250. closePath();
  1251. //clip();
  1252. g.setClip(currentPath);
  1253. currentPath = null;
  1254. Rectangle2D.Float lineRect = new Rectangle2D.Float(
  1255. sx1a, innery, ex1a - sx1a, outery - innery);
  1256. Java2DRenderer.drawBorderLine(lineRect, true, false,
  1257. bpsAfter.style, bpsAfter.color, g);
  1258. //restoreGraphicsState();
  1259. }
  1260. if (bpsStart != null) {
  1261. //endTextObject();
  1262. float sy1 = starty;
  1263. float sy2 = (slant[0] ? sy1 + bw[0] - clipw[0] : sy1);
  1264. float ey1 = sy1 + height;
  1265. float ey2 = (slant[3] ? ey1 - bw[2] + clipw[2] : ey1);
  1266. float outerx = startx - clipw[3];
  1267. float clipx = outerx + clipw[3];
  1268. float innerx = outerx + bw[3];
  1269. //saveGraphicsState();
  1270. Graphics2D g = (Graphics2D)g2d.create();
  1271. moveTo(clipx, ey1);
  1272. float sy1a = sy1;
  1273. float ey1a = ey1;
  1274. if (bpsStart.mode == BorderProps.COLLAPSE_OUTER) {
  1275. if (bpsBefore != null && bpsBefore.mode == BorderProps.COLLAPSE_OUTER) {
  1276. sy1a -= clipw[0];
  1277. }
  1278. if (bpsAfter != null && bpsAfter.mode == BorderProps.COLLAPSE_OUTER) {
  1279. ey1a += clipw[2];
  1280. }
  1281. lineTo(outerx, ey1a);
  1282. lineTo(outerx, sy1a);
  1283. }
  1284. lineTo(clipx, sy1);
  1285. lineTo(innerx, sy2);
  1286. lineTo(innerx, ey2);
  1287. closePath();
  1288. //clip();
  1289. g.setClip(currentPath);
  1290. currentPath = null;
  1291. Rectangle2D.Float lineRect = new Rectangle2D.Float(
  1292. outerx, sy1a, innerx - outerx, ey1a - sy1a);
  1293. Java2DRenderer.drawBorderLine(lineRect, false, false,
  1294. bpsStart.style, bpsStart.color, g);
  1295. //restoreGraphicsState();
  1296. }
  1297. }
  1298. public Dimension getImageSize() {
  1299. return paintRect.getSize();
  1300. }
  1301. };
  1302. try {
  1303. g2a.paintImage(painter, rc,
  1304. paintRect.x - xoffset, paintRect.y, paintRect.width, paintRect.height);
  1305. } catch (IOException ioe) {
  1306. handleIOTrouble(ioe);
  1307. }
  1308. }
  1309. /** {@inheritDoc} */
  1310. public void renderLeader(Leader area) {
  1311. renderInlineAreaBackAndBorders(area);
  1312. saveGraphicsState();
  1313. int style = area.getRuleStyle();
  1314. float startx = (currentIPPosition + area.getBorderAndPaddingWidthStart()) / 1000f;
  1315. float starty = (currentBPPosition + area.getOffset()) / 1000f;
  1316. float endx = (currentIPPosition + area.getBorderAndPaddingWidthStart()
  1317. + area.getIPD()) / 1000f;
  1318. float ruleThickness = area.getRuleThickness() / 1000f;
  1319. Color col = (Color)area.getTrait(Trait.COLOR);
  1320. switch (style) {
  1321. case EN_SOLID:
  1322. case EN_DASHED: //TODO Improve me and following (this is just a quick-fix ATM)
  1323. case EN_DOUBLE:
  1324. case EN_DOTTED:
  1325. case EN_GROOVE:
  1326. case EN_RIDGE:
  1327. updateFillColor(col);
  1328. fillRect(startx, starty, endx - startx, ruleThickness);
  1329. break;
  1330. default:
  1331. throw new UnsupportedOperationException("rule style not supported");
  1332. }
  1333. restoreGraphicsState();
  1334. super.renderLeader(area);
  1335. }
  1336. }