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

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