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

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