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

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