You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

PCLRenderer.java 62KB

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