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

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