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.

PSRenderer.java 48KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289
  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.ps;
  19. // Java
  20. import java.awt.Color;
  21. import java.awt.Point;
  22. import java.awt.Rectangle;
  23. import java.awt.geom.AffineTransform;
  24. import java.awt.geom.Rectangle2D;
  25. import java.awt.image.RenderedImage;
  26. import java.io.File;
  27. import java.io.FileNotFoundException;
  28. import java.io.IOException;
  29. import java.io.InputStream;
  30. import java.io.OutputStream;
  31. import java.util.Collection;
  32. import java.util.Iterator;
  33. import java.util.List;
  34. import java.util.Map;
  35. import javax.xml.transform.Source;
  36. import org.apache.commons.io.IOUtils;
  37. import org.apache.commons.logging.Log;
  38. import org.apache.commons.logging.LogFactory;
  39. import org.apache.xmlgraphics.image.loader.ImageException;
  40. import org.apache.xmlgraphics.image.loader.ImageFlavor;
  41. import org.apache.xmlgraphics.image.loader.ImageInfo;
  42. import org.apache.xmlgraphics.image.loader.ImageManager;
  43. import org.apache.xmlgraphics.image.loader.ImageSessionContext;
  44. import org.apache.xmlgraphics.image.loader.util.ImageUtil;
  45. import org.apache.xmlgraphics.ps.DSCConstants;
  46. import org.apache.xmlgraphics.ps.PSDictionary;
  47. import org.apache.xmlgraphics.ps.PSDictionaryFormatException;
  48. import org.apache.xmlgraphics.ps.PSGenerator;
  49. import org.apache.xmlgraphics.ps.PSPageDeviceDictionary;
  50. import org.apache.xmlgraphics.ps.PSProcSets;
  51. import org.apache.xmlgraphics.ps.PSResource;
  52. import org.apache.xmlgraphics.ps.PSState;
  53. import org.apache.xmlgraphics.ps.dsc.DSCException;
  54. import org.apache.xmlgraphics.ps.dsc.ResourceTracker;
  55. import org.apache.xmlgraphics.ps.dsc.events.DSCCommentBoundingBox;
  56. import org.apache.xmlgraphics.ps.dsc.events.DSCCommentHiResBoundingBox;
  57. import org.apache.fop.ResourceEventProducer;
  58. import org.apache.fop.apps.FOPException;
  59. import org.apache.fop.apps.FOUserAgent;
  60. import org.apache.fop.area.Area;
  61. import org.apache.fop.area.BlockViewport;
  62. import org.apache.fop.area.CTM;
  63. import org.apache.fop.area.OffDocumentExtensionAttachment;
  64. import org.apache.fop.area.OffDocumentItem;
  65. import org.apache.fop.area.PageViewport;
  66. import org.apache.fop.area.RegionViewport;
  67. import org.apache.fop.area.Trait;
  68. import org.apache.fop.area.inline.AbstractTextArea;
  69. import org.apache.fop.area.inline.Image;
  70. import org.apache.fop.area.inline.InlineParent;
  71. import org.apache.fop.area.inline.Leader;
  72. import org.apache.fop.area.inline.SpaceArea;
  73. import org.apache.fop.area.inline.TextArea;
  74. import org.apache.fop.area.inline.WordArea;
  75. import org.apache.fop.datatypes.URISpecification;
  76. import org.apache.fop.fo.extensions.ExtensionAttachment;
  77. import org.apache.fop.fonts.Font;
  78. import org.apache.fop.fonts.LazyFont;
  79. import org.apache.fop.fonts.SingleByteFont;
  80. import org.apache.fop.fonts.Typeface;
  81. import org.apache.fop.render.AbstractPathOrientedRenderer;
  82. import org.apache.fop.render.Graphics2DAdapter;
  83. import org.apache.fop.render.ImageAdapter;
  84. import org.apache.fop.render.ImageHandler;
  85. import org.apache.fop.render.ImageHandlerRegistry;
  86. import org.apache.fop.render.RendererContext;
  87. import org.apache.fop.render.RendererEventProducer;
  88. import org.apache.fop.render.ps.extensions.PSCommentAfter;
  89. import org.apache.fop.render.ps.extensions.PSCommentBefore;
  90. import org.apache.fop.render.ps.extensions.PSExtensionAttachment;
  91. import org.apache.fop.render.ps.extensions.PSSetPageDevice;
  92. import org.apache.fop.render.ps.extensions.PSSetupCode;
  93. import org.apache.fop.traits.RuleStyle;
  94. import org.apache.fop.util.CharUtilities;
  95. /**
  96. * Renderer that renders to PostScript.
  97. * <br>
  98. * This class currently generates PostScript Level 2 code. The only exception
  99. * is the FlateEncode filter which is a Level 3 feature. The filters in use
  100. * are hardcoded at the moment.
  101. * <br>
  102. * This class follows the Document Structuring Conventions (DSC) version 3.0.
  103. * If anyone modifies this renderer please make
  104. * sure to also follow the DSC to make it simpler to programmatically modify
  105. * the generated Postscript files (ex. extract pages etc.).
  106. * <br>
  107. * This renderer inserts FOP-specific comments into the PostScript stream which
  108. * may help certain users to do certain types of post-processing of the output.
  109. * These comments all start with "%FOP".
  110. *
  111. * @author <a href="mailto:fop-dev@xmlgraphics.apache.org">Apache FOP Development Team</a>
  112. * @version $Id$
  113. */
  114. public class PSRenderer extends AbstractPathOrientedRenderer
  115. implements ImageAdapter, PSSupportedFlavors, PSConfigurationConstants {
  116. /** logging instance */
  117. private static Log log = LogFactory.getLog(PSRenderer.class);
  118. /** The MIME type for PostScript */
  119. public static final String MIME_TYPE = "application/postscript";
  120. /** The application producing the PostScript */
  121. private int currentPageNumber = 0;
  122. /** the OutputStream the PS file is written to */
  123. private OutputStream outputStream;
  124. /** the temporary file in case of two-pass processing */
  125. private File tempFile;
  126. /** The PostScript generator used to output the PostScript */
  127. protected PSGenerator gen;
  128. private boolean ioTrouble = false;
  129. private boolean inTextMode = false;
  130. /** Used to temporarily store PSSetupCode instance until they can be written. */
  131. private List setupCodeList;
  132. /** This is a map of PSResource instances of all fonts defined (key: font key) */
  133. private Map fontResources;
  134. /** This is a map of PSResource instances of all forms (key: uri) */
  135. private Map formResources;
  136. /** encapsulation of dictionary used in setpagedevice instruction **/
  137. private PSPageDeviceDictionary pageDeviceDictionary;
  138. /**
  139. * Utility class which enables all sorts of features that are not directly connected to the
  140. * normal rendering process.
  141. */
  142. protected PSRenderingUtil psUtil;
  143. private PSBorderPainter borderPainter;
  144. /** Is used to determine the document's bounding box */
  145. private Rectangle2D documentBoundingBox;
  146. /** This is a collection holding all document header comments */
  147. private Collection headerComments;
  148. /** This is a collection holding all document footer comments */
  149. private Collection footerComments;
  150. /** {@inheritDoc} */
  151. public void setUserAgent(FOUserAgent agent) {
  152. super.setUserAgent(agent);
  153. this.psUtil = new PSRenderingUtil(getUserAgent());
  154. }
  155. PSRenderingUtil getPSUtil() {
  156. return this.psUtil;
  157. }
  158. /**
  159. * Sets the landscape mode for this renderer.
  160. * @param value false will normally generate a "pseudo-portrait" page, true will rotate
  161. * a "wider-than-long" page by 90 degrees.
  162. */
  163. public void setAutoRotateLandscape(boolean value) {
  164. getPSUtil().setAutoRotateLandscape(value);
  165. }
  166. /** @return true if the renderer is configured to rotate landscape pages */
  167. public boolean isAutoRotateLandscape() {
  168. return getPSUtil().isAutoRotateLandscape();
  169. }
  170. /**
  171. * Sets the PostScript language level that the renderer should produce.
  172. * @param level the language level (currently allowed: 2 or 3)
  173. */
  174. public void setLanguageLevel(int level) {
  175. getPSUtil().setLanguageLevel(level);
  176. }
  177. /**
  178. * Return the PostScript language level that the renderer produces.
  179. * @return the language level
  180. */
  181. public int getLanguageLevel() {
  182. return getPSUtil().getLanguageLevel();
  183. }
  184. /**
  185. * Sets the resource optimization mode. If set to true, the renderer does two passes to
  186. * only embed the necessary resources in the PostScript file. This is slower, but produces
  187. * smaller files.
  188. * @param value true to enable the resource optimization
  189. */
  190. public void setOptimizeResources(boolean value) {
  191. getPSUtil().setOptimizeResources(value);
  192. }
  193. /** @return true if the renderer does two passes to optimize PostScript resources */
  194. public boolean isOptimizeResources() {
  195. return getPSUtil().isOptimizeResources();
  196. }
  197. /** {@inheritDoc} */
  198. public Graphics2DAdapter getGraphics2DAdapter() {
  199. return new PSGraphics2DAdapter(this);
  200. }
  201. /** {@inheritDoc} */
  202. public ImageAdapter getImageAdapter() {
  203. return this;
  204. }
  205. /**
  206. * Write out a command
  207. * @param cmd PostScript command
  208. */
  209. protected void writeln(String cmd) {
  210. try {
  211. gen.writeln(cmd);
  212. } catch (IOException ioe) {
  213. handleIOTrouble(ioe);
  214. }
  215. }
  216. /**
  217. * Central exception handler for I/O exceptions.
  218. * @param ioe IOException to handle
  219. */
  220. protected void handleIOTrouble(IOException ioe) {
  221. if (!ioTrouble) {
  222. RendererEventProducer eventProducer = RendererEventProducer.Provider.get(
  223. getUserAgent().getEventBroadcaster());
  224. eventProducer.ioError(this, ioe);
  225. ioTrouble = true;
  226. }
  227. }
  228. /**
  229. * Write out a comment
  230. * @param comment Comment to write
  231. */
  232. protected void comment(String comment) {
  233. try {
  234. if (comment.startsWith("%")) {
  235. gen.commentln(comment);
  236. writeln(comment);
  237. } else {
  238. gen.commentln("%" + comment);
  239. }
  240. } catch (IOException ioe) {
  241. handleIOTrouble(ioe);
  242. }
  243. }
  244. /**
  245. * Make sure the cursor is in the right place.
  246. */
  247. protected void movetoCurrPosition() {
  248. moveTo(this.currentIPPosition, this.currentBPPosition);
  249. }
  250. /** {@inheritDoc} */
  251. protected void clip() {
  252. writeln("clip newpath");
  253. }
  254. /** {@inheritDoc} */
  255. protected void clipRect(float x, float y, float width, float height) {
  256. try {
  257. gen.defineRect(x, y, width, height);
  258. clip();
  259. } catch (IOException ioe) {
  260. handleIOTrouble(ioe);
  261. }
  262. }
  263. /** {@inheritDoc} */
  264. protected void moveTo(float x, float y) {
  265. writeln(gen.formatDouble(x) + " " + gen.formatDouble(y) + " M");
  266. }
  267. /**
  268. * Moves the current point by (x, y) relative to the current position,
  269. * omitting any connecting line segment.
  270. * @param x x coordinate
  271. * @param y y coordinate
  272. */
  273. protected void rmoveTo(float x, float y) {
  274. writeln(gen.formatDouble(x) + " " + gen.formatDouble(y) + " RM");
  275. }
  276. /** {@inheritDoc} */
  277. protected void lineTo(float x, float y) {
  278. writeln(gen.formatDouble(x) + " " + gen.formatDouble(y) + " lineto");
  279. }
  280. /** {@inheritDoc} */
  281. protected void closePath() {
  282. writeln("cp");
  283. }
  284. /** {@inheritDoc} */
  285. protected void fillRect(float x, float y, float width, float height) {
  286. if (width != 0 && height != 0) {
  287. try {
  288. gen.defineRect(x, y, width, height);
  289. gen.writeln("fill");
  290. } catch (IOException ioe) {
  291. handleIOTrouble(ioe);
  292. }
  293. }
  294. }
  295. /** {@inheritDoc} */
  296. protected void updateColor(Color col, boolean fill) {
  297. try {
  298. useColor(col);
  299. } catch (IOException ioe) {
  300. handleIOTrouble(ioe);
  301. }
  302. }
  303. /** {@inheritDoc} */
  304. protected void drawImage(String uri, Rectangle2D pos, Map foreignAttributes) {
  305. endTextObject();
  306. int x = currentIPPosition + (int)Math.round(pos.getX());
  307. int y = currentBPPosition + (int)Math.round(pos.getY());
  308. uri = URISpecification.getURL(uri);
  309. if (log.isDebugEnabled()) {
  310. log.debug("Handling image: " + uri);
  311. }
  312. int width = (int)pos.getWidth();
  313. int height = (int)pos.getHeight();
  314. Rectangle targetRect = new Rectangle(x, y, width, height);
  315. ImageManager manager = getUserAgent().getFactory().getImageManager();
  316. ImageInfo info = null;
  317. try {
  318. ImageSessionContext sessionContext = getUserAgent().getImageSessionContext();
  319. info = manager.getImageInfo(uri, sessionContext);
  320. PSRenderingContext renderingContext = new PSRenderingContext(
  321. getUserAgent(), gen, getFontInfo());
  322. if (!isOptimizeResources()
  323. || PSImageUtils.isImageInlined(info, renderingContext)) {
  324. if (log.isDebugEnabled()) {
  325. log.debug("Image " + info + " is inlined");
  326. }
  327. //Determine supported flavors
  328. ImageFlavor[] flavors;
  329. ImageHandlerRegistry imageHandlerRegistry
  330. = userAgent.getFactory().getImageHandlerRegistry();
  331. flavors = imageHandlerRegistry.getSupportedFlavors(renderingContext);
  332. //Only now fully load/prepare the image
  333. Map hints = ImageUtil.getDefaultHints(sessionContext);
  334. org.apache.xmlgraphics.image.loader.Image img = manager.getImage(
  335. info, flavors, hints, sessionContext);
  336. //Get handler for image
  337. ImageHandler basicHandler = imageHandlerRegistry.getHandler(renderingContext, img);
  338. //...and embed as inline image
  339. basicHandler.handleImage(renderingContext, img, targetRect);
  340. } else {
  341. if (log.isDebugEnabled()) {
  342. log.debug("Image " + info + " is embedded as a form later");
  343. }
  344. //Don't load image at this time, just put a form placeholder in the stream
  345. PSResource form = getFormForImage(info.getOriginalURI());
  346. PSImageUtils.drawForm(form, info, targetRect, gen);
  347. }
  348. } catch (ImageException ie) {
  349. ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get(
  350. getUserAgent().getEventBroadcaster());
  351. eventProducer.imageError(this, (info != null ? info.toString() : uri), ie, null);
  352. } catch (FileNotFoundException fe) {
  353. ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get(
  354. getUserAgent().getEventBroadcaster());
  355. eventProducer.imageNotFound(this, (info != null ? info.toString() : uri), fe, null);
  356. } catch (IOException ioe) {
  357. ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get(
  358. getUserAgent().getEventBroadcaster());
  359. eventProducer.imageIOError(this, (info != null ? info.toString() : uri), ioe, null);
  360. }
  361. }
  362. /**
  363. * Returns a PSResource instance representing a image as a PostScript form.
  364. * @param uri the image URI
  365. * @return a PSResource instance
  366. */
  367. protected PSResource getFormForImage(String uri) {
  368. if (uri == null || "".equals(uri)) {
  369. throw new IllegalArgumentException("uri must not be empty or null");
  370. }
  371. if (this.formResources == null) {
  372. this.formResources = new java.util.HashMap();
  373. }
  374. PSResource form = (PSResource)this.formResources.get(uri);
  375. if (form == null) {
  376. form = new PSImageFormResource(this.formResources.size() + 1, uri);
  377. this.formResources.put(uri, form);
  378. }
  379. return form;
  380. }
  381. /** {@inheritDoc} */
  382. public void paintImage(RenderedImage image, RendererContext context,
  383. int x, int y, int width, int height) throws IOException {
  384. float fx = x / 1000f;
  385. x += currentIPPosition / 1000f;
  386. float fy = y / 1000f;
  387. y += currentBPPosition / 1000f;
  388. float fw = width / 1000f;
  389. float fh = height / 1000f;
  390. PSImageUtils.renderBitmapImage(image, fx, fy, fw, fh, gen);
  391. }
  392. /**
  393. * Draw a line.
  394. *
  395. * @param startx the start x position
  396. * @param starty the start y position
  397. * @param endx the x end position
  398. * @param endy the y end position
  399. */
  400. private void drawLine(float startx, float starty, float endx, float endy) {
  401. writeln(gen.formatDouble(startx) + " "
  402. + gen.formatDouble(starty) + " M "
  403. + gen.formatDouble(endx) + " "
  404. + gen.formatDouble(endy) + " lineto stroke newpath");
  405. }
  406. /** Saves the graphics state of the rendering engine. */
  407. public void saveGraphicsState() {
  408. endTextObject();
  409. try {
  410. //delegate
  411. gen.saveGraphicsState();
  412. } catch (IOException ioe) {
  413. handleIOTrouble(ioe);
  414. }
  415. }
  416. /** Restores the last graphics state of the rendering engine. */
  417. public void restoreGraphicsState() {
  418. try {
  419. endTextObject();
  420. //delegate
  421. gen.restoreGraphicsState();
  422. } catch (IOException ioe) {
  423. handleIOTrouble(ioe);
  424. }
  425. }
  426. /**
  427. * Concats the transformation matrix.
  428. * @param a A part
  429. * @param b B part
  430. * @param c C part
  431. * @param d D part
  432. * @param e E part
  433. * @param f F part
  434. */
  435. protected void concatMatrix(double a, double b,
  436. double c, double d,
  437. double e, double f) {
  438. try {
  439. gen.concatMatrix(a, b, c, d, e, f);
  440. } catch (IOException ioe) {
  441. handleIOTrouble(ioe);
  442. }
  443. }
  444. /**
  445. * Concats the transformations matrix.
  446. * @param matrix Matrix to use
  447. */
  448. protected void concatMatrix(double[] matrix) {
  449. try {
  450. gen.concatMatrix(matrix);
  451. } catch (IOException ioe) {
  452. handleIOTrouble(ioe);
  453. }
  454. }
  455. /** {@inheritDoc} */
  456. protected void concatenateTransformationMatrix(AffineTransform at) {
  457. try {
  458. gen.concatMatrix(at);
  459. } catch (IOException ioe) {
  460. handleIOTrouble(ioe);
  461. }
  462. }
  463. private String getPostScriptNameForFontKey(String key) {
  464. int pos = key.indexOf('_');
  465. String postFix = null;
  466. if (pos > 0) {
  467. postFix = key.substring(pos);
  468. key = key.substring(0, pos);
  469. }
  470. Map fonts = fontInfo.getFonts();
  471. Typeface tf = (Typeface)fonts.get(key);
  472. if (tf instanceof LazyFont) {
  473. tf = ((LazyFont)tf).getRealFont();
  474. }
  475. if (tf == null) {
  476. throw new IllegalStateException("Font not available: " + key);
  477. }
  478. if (postFix == null) {
  479. return tf.getFontName();
  480. } else {
  481. return tf.getFontName() + postFix;
  482. }
  483. }
  484. /**
  485. * Returns the PSResource for the given font key.
  486. * @param key the font key ("F*")
  487. * @return the matching PSResource
  488. */
  489. protected PSResource getPSResourceForFontKey(String key) {
  490. PSResource res = null;
  491. if (this.fontResources != null) {
  492. res = (PSResource)this.fontResources.get(key);
  493. } else {
  494. this.fontResources = new java.util.HashMap();
  495. }
  496. if (res == null) {
  497. res = new PSResource(PSResource.TYPE_FONT, getPostScriptNameForFontKey(key));
  498. this.fontResources.put(key, res);
  499. }
  500. return res;
  501. }
  502. /**
  503. * Changes the currently used font.
  504. * @param key key of the font ("F*")
  505. * @param size font size
  506. */
  507. protected void useFont(String key, int size) {
  508. try {
  509. PSResource res = getPSResourceForFontKey(key);
  510. gen.useFont("/" + res.getName(), size / 1000f);
  511. gen.getResourceTracker().notifyResourceUsageOnPage(res);
  512. } catch (IOException ioe) {
  513. handleIOTrouble(ioe);
  514. }
  515. }
  516. private void useColor(Color col) throws IOException {
  517. gen.useColor(col);
  518. }
  519. /** {@inheritDoc} */
  520. protected void drawBackAndBorders(Area area, float startx, float starty,
  521. float width, float height) {
  522. if (area.hasTrait(Trait.BACKGROUND)
  523. || area.hasTrait(Trait.BORDER_BEFORE)
  524. || area.hasTrait(Trait.BORDER_AFTER)
  525. || area.hasTrait(Trait.BORDER_START)
  526. || area.hasTrait(Trait.BORDER_END)) {
  527. comment("%FOPBeginBackgroundAndBorder: "
  528. + startx + " " + starty + " " + width + " " + height);
  529. super.drawBackAndBorders(area, startx, starty, width, height);
  530. comment("%FOPEndBackgroundAndBorder");
  531. }
  532. }
  533. /** {@inheritDoc} */
  534. protected void drawBorderLine(float x1, float y1, float x2, float y2,
  535. boolean horz, boolean startOrBefore, int style, Color col) {
  536. try {
  537. PSBorderPainter.drawBorderLine(gen, x1, y1, x2, y2, horz, startOrBefore, style, col);
  538. } catch (IOException ioe) {
  539. handleIOTrouble(ioe);
  540. }
  541. }
  542. /** {@inheritDoc} */
  543. public void startRenderer(OutputStream outputStream)
  544. throws IOException {
  545. log.debug("Rendering areas to PostScript...");
  546. this.outputStream = outputStream;
  547. OutputStream out;
  548. if (isOptimizeResources()) {
  549. this.tempFile = File.createTempFile("fop", null);
  550. out = new java.io.FileOutputStream(this.tempFile);
  551. out = new java.io.BufferedOutputStream(out);
  552. } else {
  553. out = this.outputStream;
  554. }
  555. //Setup for PostScript generation
  556. this.gen = new PSGenerator(out) {
  557. /** Need to subclass PSGenerator to have better URI resolution */
  558. public Source resolveURI(String uri) {
  559. return userAgent.resolveURI(uri);
  560. }
  561. };
  562. this.gen.setPSLevel(getLanguageLevel());
  563. this.borderPainter = new PSBorderPainter(this.gen);
  564. this.currentPageNumber = 0;
  565. //Initial default page device dictionary settings
  566. this.pageDeviceDictionary = new PSPageDeviceDictionary();
  567. pageDeviceDictionary.setFlushOnRetrieval(!getPSUtil().isDSCComplianceEnabled());
  568. pageDeviceDictionary.put("/ImagingBBox", "null");
  569. }
  570. private void writeHeader() throws IOException {
  571. //PostScript Header
  572. writeln(DSCConstants.PS_ADOBE_30);
  573. gen.writeDSCComment(DSCConstants.CREATOR, new String[] {userAgent.getProducer()});
  574. gen.writeDSCComment(DSCConstants.CREATION_DATE, new Object[] {new java.util.Date()});
  575. gen.writeDSCComment(DSCConstants.LANGUAGE_LEVEL, new Integer(gen.getPSLevel()));
  576. gen.writeDSCComment(DSCConstants.PAGES, new Object[] {DSCConstants.ATEND});
  577. gen.writeDSCComment(DSCConstants.BBOX, DSCConstants.ATEND);
  578. gen.writeDSCComment(DSCConstants.HIRES_BBOX, DSCConstants.ATEND);
  579. this.documentBoundingBox = new Rectangle2D.Double();
  580. gen.writeDSCComment(DSCConstants.DOCUMENT_SUPPLIED_RESOURCES,
  581. new Object[] {DSCConstants.ATEND});
  582. if (headerComments != null) {
  583. for (Iterator iter = headerComments.iterator(); iter.hasNext();) {
  584. PSExtensionAttachment comment = (PSExtensionAttachment)iter.next();
  585. gen.writeln("%" + comment.getContent());
  586. }
  587. }
  588. gen.writeDSCComment(DSCConstants.END_COMMENTS);
  589. //Defaults
  590. gen.writeDSCComment(DSCConstants.BEGIN_DEFAULTS);
  591. gen.writeDSCComment(DSCConstants.END_DEFAULTS);
  592. //Prolog and Setup written right before the first page-sequence, see startPageSequence()
  593. //Do this only once, as soon as we have all the content for the Setup section!
  594. //Prolog
  595. gen.writeDSCComment(DSCConstants.BEGIN_PROLOG);
  596. PSProcSets.writeStdProcSet(gen);
  597. PSProcSets.writeEPSProcSet(gen);
  598. gen.writeDSCComment(DSCConstants.END_PROLOG);
  599. //Setup
  600. gen.writeDSCComment(DSCConstants.BEGIN_SETUP);
  601. PSRenderingUtil.writeSetupCodeList(gen, setupCodeList, "SetupCode");
  602. if (!isOptimizeResources()) {
  603. this.fontResources = PSFontUtils.writeFontDict(gen, fontInfo);
  604. } else {
  605. gen.commentln("%FOPFontSetup"); //Place-holder, will be replaced in the second pass
  606. }
  607. gen.writeDSCComment(DSCConstants.END_SETUP);
  608. }
  609. /** {@inheritDoc} */
  610. public void stopRenderer() throws IOException {
  611. //Write trailer
  612. gen.writeDSCComment(DSCConstants.TRAILER);
  613. if (footerComments != null) {
  614. for (Iterator iter = footerComments.iterator(); iter.hasNext();) {
  615. PSExtensionAttachment comment = (PSExtensionAttachment)iter.next();
  616. gen.commentln("%" + comment.getContent());
  617. }
  618. footerComments.clear();
  619. }
  620. gen.writeDSCComment(DSCConstants.PAGES, new Integer(this.currentPageNumber));
  621. new DSCCommentBoundingBox(this.documentBoundingBox).generate(gen);
  622. new DSCCommentHiResBoundingBox(this.documentBoundingBox).generate(gen);
  623. gen.getResourceTracker().writeResources(false, gen);
  624. gen.writeDSCComment(DSCConstants.EOF);
  625. gen.flush();
  626. log.debug("Rendering to PostScript complete.");
  627. if (isOptimizeResources()) {
  628. IOUtils.closeQuietly(gen.getOutputStream());
  629. rewritePostScriptFile();
  630. }
  631. if (footerComments != null) {
  632. headerComments.clear();
  633. }
  634. if (pageDeviceDictionary != null) {
  635. pageDeviceDictionary.clear();
  636. }
  637. this.borderPainter = null;
  638. this.gen = null;
  639. }
  640. /**
  641. * Used for two-pass production. This will rewrite the PostScript file from the temporary
  642. * file while adding all needed resources.
  643. * @throws IOException In case of an I/O error.
  644. */
  645. private void rewritePostScriptFile() throws IOException {
  646. log.debug("Processing PostScript resources...");
  647. long startTime = System.currentTimeMillis();
  648. ResourceTracker resTracker = gen.getResourceTracker();
  649. InputStream in = new java.io.FileInputStream(this.tempFile);
  650. in = new java.io.BufferedInputStream(in);
  651. try {
  652. try {
  653. ResourceHandler handler = new ResourceHandler(this.userAgent, this.fontInfo,
  654. resTracker, this.formResources);
  655. handler.process(in, this.outputStream,
  656. this.currentPageNumber, this.documentBoundingBox);
  657. this.outputStream.flush();
  658. } catch (DSCException e) {
  659. throw new RuntimeException(e.getMessage());
  660. }
  661. } finally {
  662. IOUtils.closeQuietly(in);
  663. if (!this.tempFile.delete()) {
  664. this.tempFile.deleteOnExit();
  665. log.warn("Could not delete temporary file: " + this.tempFile);
  666. }
  667. }
  668. if (log.isDebugEnabled()) {
  669. long duration = System.currentTimeMillis() - startTime;
  670. log.debug("Resource Processing complete in " + duration + " ms.");
  671. }
  672. }
  673. /** {@inheritDoc} */
  674. public void processOffDocumentItem(OffDocumentItem oDI) {
  675. if (log.isDebugEnabled()) {
  676. log.debug("Handling OffDocumentItem: " + oDI.getName());
  677. }
  678. if (oDI instanceof OffDocumentExtensionAttachment) {
  679. ExtensionAttachment attachment = ((OffDocumentExtensionAttachment)oDI).getAttachment();
  680. if (attachment != null) {
  681. if (PSExtensionAttachment.CATEGORY.equals(attachment.getCategory())) {
  682. if (attachment instanceof PSSetupCode) {
  683. if (setupCodeList == null) {
  684. setupCodeList = new java.util.ArrayList();
  685. }
  686. if (!setupCodeList.contains(attachment)) {
  687. setupCodeList.add(attachment);
  688. }
  689. } else if (attachment instanceof PSSetPageDevice) {
  690. /**
  691. * Extract all PSSetPageDevice instances from the
  692. * attachment list on the s-p-m and add all dictionary
  693. * entries to our internal representation of the the
  694. * page device dictionary.
  695. */
  696. PSSetPageDevice setPageDevice = (PSSetPageDevice)attachment;
  697. String content = setPageDevice.getContent();
  698. if (content != null) {
  699. try {
  700. this.pageDeviceDictionary.putAll(PSDictionary.valueOf(content));
  701. } catch (PSDictionaryFormatException e) {
  702. PSEventProducer eventProducer = PSEventProducer.Provider.get(
  703. getUserAgent().getEventBroadcaster());
  704. eventProducer.postscriptDictionaryParseError(this, content, e);
  705. }
  706. }
  707. } else if (attachment instanceof PSCommentBefore) {
  708. if (headerComments == null) {
  709. headerComments = new java.util.ArrayList();
  710. }
  711. headerComments.add(attachment);
  712. } else if (attachment instanceof PSCommentAfter) {
  713. if (footerComments == null) {
  714. footerComments = new java.util.ArrayList();
  715. }
  716. footerComments.add(attachment);
  717. }
  718. }
  719. }
  720. }
  721. super.processOffDocumentItem(oDI);
  722. }
  723. /** {@inheritDoc} */
  724. public void renderPage(PageViewport page)
  725. throws IOException, FOPException {
  726. log.debug("renderPage(): " + page);
  727. if (this.currentPageNumber == 0) {
  728. writeHeader();
  729. }
  730. this.currentPageNumber++;
  731. gen.getResourceTracker().notifyStartNewPage();
  732. gen.getResourceTracker().notifyResourceUsageOnPage(PSProcSets.STD_PROCSET);
  733. gen.writeDSCComment(DSCConstants.PAGE, new Object[]
  734. {page.getPageNumberString(),
  735. new Integer(this.currentPageNumber)});
  736. double pageWidth = page.getViewArea().width / 1000f;
  737. double pageHeight = page.getViewArea().height / 1000f;
  738. boolean rotate = false;
  739. List pageSizes = new java.util.ArrayList();
  740. if (getPSUtil().isAutoRotateLandscape() && (pageHeight < pageWidth)) {
  741. rotate = true;
  742. pageSizes.add(new Long(Math.round(pageHeight)));
  743. pageSizes.add(new Long(Math.round(pageWidth)));
  744. } else {
  745. pageSizes.add(new Long(Math.round(pageWidth)));
  746. pageSizes.add(new Long(Math.round(pageHeight)));
  747. }
  748. pageDeviceDictionary.put("/PageSize", pageSizes);
  749. if (page.hasExtensionAttachments()) {
  750. for (Iterator iter = page.getExtensionAttachments().iterator();
  751. iter.hasNext();) {
  752. ExtensionAttachment attachment = (ExtensionAttachment) iter.next();
  753. if (attachment instanceof PSSetPageDevice) {
  754. /**
  755. * Extract all PSSetPageDevice instances from the
  756. * attachment list on the s-p-m and add all
  757. * dictionary entries to our internal representation
  758. * of the the page device dictionary.
  759. */
  760. PSSetPageDevice setPageDevice = (PSSetPageDevice)attachment;
  761. String content = setPageDevice.getContent();
  762. if (content != null) {
  763. try {
  764. pageDeviceDictionary.putAll(PSDictionary.valueOf(content));
  765. } catch (PSDictionaryFormatException e) {
  766. PSEventProducer eventProducer = PSEventProducer.Provider.get(
  767. getUserAgent().getEventBroadcaster());
  768. eventProducer.postscriptDictionaryParseError(this, content, e);
  769. }
  770. }
  771. }
  772. }
  773. }
  774. try {
  775. if (setupCodeList != null) {
  776. PSRenderingUtil.writeEnclosedExtensionAttachments(gen, setupCodeList);
  777. setupCodeList.clear();
  778. }
  779. } catch (IOException e) {
  780. log.error(e.getMessage());
  781. }
  782. final Integer zero = new Integer(0);
  783. Rectangle2D pageBoundingBox = new Rectangle2D.Double();
  784. if (rotate) {
  785. pageBoundingBox.setRect(0, 0, pageHeight, pageWidth);
  786. gen.writeDSCComment(DSCConstants.PAGE_BBOX, new Object[] {
  787. zero, zero, new Long(Math.round(pageHeight)),
  788. new Long(Math.round(pageWidth)) });
  789. gen.writeDSCComment(DSCConstants.PAGE_HIRES_BBOX, new Object[] {
  790. zero, zero, new Double(pageHeight),
  791. new Double(pageWidth) });
  792. gen.writeDSCComment(DSCConstants.PAGE_ORIENTATION, "Landscape");
  793. } else {
  794. pageBoundingBox.setRect(0, 0, pageWidth, pageHeight);
  795. gen.writeDSCComment(DSCConstants.PAGE_BBOX, new Object[] {
  796. zero, zero, new Long(Math.round(pageWidth)),
  797. new Long(Math.round(pageHeight)) });
  798. gen.writeDSCComment(DSCConstants.PAGE_HIRES_BBOX, new Object[] {
  799. zero, zero, new Double(pageWidth),
  800. new Double(pageHeight) });
  801. if (getPSUtil().isAutoRotateLandscape()) {
  802. gen.writeDSCComment(DSCConstants.PAGE_ORIENTATION,
  803. "Portrait");
  804. }
  805. }
  806. this.documentBoundingBox.add(pageBoundingBox);
  807. gen.writeDSCComment(DSCConstants.PAGE_RESOURCES,
  808. new Object[] {DSCConstants.ATEND});
  809. gen.commentln("%FOPSimplePageMaster: " + page.getSimplePageMasterName());
  810. gen.writeDSCComment(DSCConstants.BEGIN_PAGE_SETUP);
  811. if (page.hasExtensionAttachments()) {
  812. List extensionAttachments = page.getExtensionAttachments();
  813. for (int i = 0; i < extensionAttachments.size(); i++) {
  814. Object attObj = extensionAttachments.get(i);
  815. if (attObj instanceof PSExtensionAttachment) {
  816. PSExtensionAttachment attachment = (PSExtensionAttachment)attObj;
  817. if (attachment instanceof PSCommentBefore) {
  818. gen.commentln("%" + attachment.getContent());
  819. } else if (attachment instanceof PSSetupCode) {
  820. gen.writeln(attachment.getContent());
  821. }
  822. }
  823. }
  824. }
  825. // Write any unwritten changes to page device dictionary
  826. if (!pageDeviceDictionary.isEmpty()) {
  827. String content = pageDeviceDictionary.getContent();
  828. if (getPSUtil().isSafeSetPageDevice()) {
  829. content += " SSPD";
  830. } else {
  831. content += " setpagedevice";
  832. }
  833. PSRenderingUtil.writeEnclosedExtensionAttachment(gen, new PSSetPageDevice(content));
  834. }
  835. if (rotate) {
  836. gen.writeln(Math.round(pageHeight) + " 0 translate");
  837. gen.writeln("90 rotate");
  838. }
  839. concatMatrix(1, 0, 0, -1, 0, pageHeight);
  840. gen.writeDSCComment(DSCConstants.END_PAGE_SETUP);
  841. //Process page
  842. super.renderPage(page);
  843. //Show page
  844. gen.showPage();
  845. gen.writeDSCComment(DSCConstants.PAGE_TRAILER);
  846. if (page.hasExtensionAttachments()) {
  847. List extensionAttachments = page.getExtensionAttachments();
  848. for (int i = 0; i < extensionAttachments.size(); i++) {
  849. Object attObj = extensionAttachments.get(i);
  850. if (attObj instanceof PSExtensionAttachment) {
  851. PSExtensionAttachment attachment = (PSExtensionAttachment)attObj;
  852. if (attachment instanceof PSCommentAfter) {
  853. gen.commentln("%" + attachment.getContent());
  854. }
  855. }
  856. }
  857. }
  858. gen.getResourceTracker().writeResources(true, gen);
  859. }
  860. /** {@inheritDoc} */
  861. protected void renderRegionViewport(RegionViewport port) {
  862. if (port != null) {
  863. comment("%FOPBeginRegionViewport: " + port.getRegionReference().getRegionName());
  864. super.renderRegionViewport(port);
  865. comment("%FOPEndRegionViewport");
  866. }
  867. }
  868. /** Indicates the beginning of a text object. */
  869. protected void beginTextObject() {
  870. if (!inTextMode) {
  871. saveGraphicsState();
  872. writeln("BT");
  873. inTextMode = true;
  874. }
  875. }
  876. /** Indicates the end of a text object. */
  877. protected void endTextObject() {
  878. if (inTextMode) {
  879. inTextMode = false; //set before restoreGraphicsState() to avoid recursion
  880. writeln("ET");
  881. restoreGraphicsState();
  882. }
  883. }
  884. /** {@inheritDoc} */
  885. public void renderText(TextArea area) {
  886. renderInlineAreaBackAndBorders(area);
  887. String fontkey = getInternalFontNameForArea(area);
  888. int fontsize = area.getTraitAsInteger(Trait.FONT_SIZE);
  889. // This assumes that *all* CIDFonts use a /ToUnicode mapping
  890. Typeface tf = (Typeface) fontInfo.getFonts().get(fontkey);
  891. //Determine position
  892. int rx = currentIPPosition + area.getBorderAndPaddingWidthStart();
  893. int bl = currentBPPosition + area.getOffset() + area.getBaselineOffset();
  894. Color ct = (Color)area.getTrait(Trait.COLOR);
  895. if (ct != null) {
  896. try {
  897. useColor(ct);
  898. } catch (IOException ioe) {
  899. handleIOTrouble(ioe);
  900. }
  901. }
  902. beginTextObject();
  903. writeln("1 0 0 -1 " + gen.formatDouble(rx / 1000f)
  904. + " " + gen.formatDouble(bl / 1000f) + " Tm");
  905. super.renderText(area); //Updates IPD
  906. renderTextDecoration(tf, fontsize, area, bl, rx);
  907. }
  908. /** {@inheritDoc} */
  909. protected void renderWord(WordArea word) {
  910. renderText((TextArea)word.getParentArea(), word.getWord(), word.getLetterAdjustArray());
  911. super.renderWord(word);
  912. }
  913. /** {@inheritDoc} */
  914. protected void renderSpace(SpaceArea space) {
  915. AbstractTextArea textArea = (AbstractTextArea)space.getParentArea();
  916. String s = space.getSpace();
  917. char sp = s.charAt(0);
  918. Font font = getFontFromArea(textArea);
  919. int tws = (space.isAdjustable()
  920. ? ((TextArea) space.getParentArea()).getTextWordSpaceAdjust()
  921. + 2 * textArea.getTextLetterSpaceAdjust()
  922. : 0);
  923. rmoveTo((font.getCharWidth(sp) + tws) / 1000f, 0);
  924. super.renderSpace(space);
  925. }
  926. private Typeface getTypeface(String fontName) {
  927. Typeface tf = (Typeface)fontInfo.getFonts().get(fontName);
  928. if (tf instanceof LazyFont) {
  929. tf = ((LazyFont)tf).getRealFont();
  930. }
  931. return tf;
  932. }
  933. private void renderText(AbstractTextArea area, String text, int[] letterAdjust) {
  934. String fontkey = getInternalFontNameForArea(area);
  935. int fontSize = area.getTraitAsInteger(Trait.FONT_SIZE);
  936. Font font = getFontFromArea(area);
  937. Typeface tf = getTypeface(font.getFontName());
  938. SingleByteFont singleByteFont = null;
  939. if (tf instanceof SingleByteFont) {
  940. singleByteFont = (SingleByteFont)tf;
  941. }
  942. int textLen = text.length();
  943. if (singleByteFont != null && singleByteFont.hasAdditionalEncodings()) {
  944. int start = 0;
  945. int currentEncoding = -1;
  946. for (int i = 0; i < textLen; i++) {
  947. char c = text.charAt(i);
  948. char mapped = tf.mapChar(c);
  949. int encoding = mapped / 256;
  950. if (currentEncoding != encoding) {
  951. if (i > 0) {
  952. writeText(area, text, start, i - start, letterAdjust, fontSize, tf);
  953. }
  954. if (encoding == 0) {
  955. useFont(fontkey, fontSize);
  956. } else {
  957. useFont(fontkey + "_" + Integer.toString(encoding), fontSize);
  958. }
  959. currentEncoding = encoding;
  960. start = i;
  961. }
  962. }
  963. writeText(area, text, start, textLen - start, letterAdjust, fontSize, tf);
  964. } else {
  965. useFont(fontkey, fontSize);
  966. writeText(area, text, 0, textLen, letterAdjust, fontSize, tf);
  967. }
  968. }
  969. private void writeText(AbstractTextArea area, String text, int start, int len,
  970. int[] letterAdjust, int fontsize, Typeface tf) {
  971. int end = start + len;
  972. int initialSize = text.length();
  973. initialSize += initialSize / 2;
  974. StringBuffer sb = new StringBuffer(initialSize);
  975. if (letterAdjust == null
  976. && area.getTextLetterSpaceAdjust() == 0
  977. && area.getTextWordSpaceAdjust() == 0) {
  978. sb.append("(");
  979. for (int i = start; i < end; i++) {
  980. final char c = text.charAt(i);
  981. final char mapped = (char)(tf.mapChar(c) % 256);
  982. PSGenerator.escapeChar(mapped, sb);
  983. }
  984. sb.append(") t");
  985. } else {
  986. sb.append("(");
  987. int[] offsets = new int[len];
  988. for (int i = start; i < end; i++) {
  989. final char c = text.charAt(i);
  990. final char mapped = tf.mapChar(c);
  991. char codepoint = (char)(mapped % 256);
  992. int wordSpace;
  993. if (CharUtilities.isAdjustableSpace(mapped)) {
  994. wordSpace = area.getTextWordSpaceAdjust();
  995. } else {
  996. wordSpace = 0;
  997. }
  998. int cw = tf.getWidth(mapped, fontsize) / 1000;
  999. int ladj = (letterAdjust != null && i < end - 1 ? letterAdjust[i + 1] : 0);
  1000. int tls = (i < end - 1 ? area.getTextLetterSpaceAdjust() : 0);
  1001. offsets[i - start] = cw + ladj + tls + wordSpace;
  1002. PSGenerator.escapeChar(codepoint, sb);
  1003. }
  1004. sb.append(")" + PSGenerator.LF + "[");
  1005. for (int i = 0; i < len; i++) {
  1006. if (i > 0) {
  1007. if (i % 8 == 0) {
  1008. sb.append(PSGenerator.LF);
  1009. } else {
  1010. sb.append(" ");
  1011. }
  1012. }
  1013. sb.append(gen.formatDouble(offsets[i] / 1000f));
  1014. }
  1015. sb.append("]" + PSGenerator.LF + "xshow");
  1016. }
  1017. writeln(sb.toString());
  1018. }
  1019. /** {@inheritDoc} */
  1020. protected List breakOutOfStateStack() {
  1021. try {
  1022. List breakOutList = new java.util.ArrayList();
  1023. PSState state;
  1024. while (true) {
  1025. if (breakOutList.size() == 0) {
  1026. endTextObject();
  1027. comment("------ break out!");
  1028. }
  1029. state = gen.getCurrentState();
  1030. if (!gen.restoreGraphicsState()) {
  1031. break;
  1032. }
  1033. breakOutList.add(0, state); //Insert because of stack-popping
  1034. }
  1035. return breakOutList;
  1036. } catch (IOException ioe) {
  1037. handleIOTrouble(ioe);
  1038. return null;
  1039. }
  1040. }
  1041. /** {@inheritDoc} */
  1042. protected void restoreStateStackAfterBreakOut(List breakOutList) {
  1043. try {
  1044. comment("------ restoring context after break-out...");
  1045. PSState state;
  1046. Iterator i = breakOutList.iterator();
  1047. while (i.hasNext()) {
  1048. state = (PSState)i.next();
  1049. saveGraphicsState();
  1050. state.reestablish(gen);
  1051. }
  1052. comment("------ done.");
  1053. } catch (IOException ioe) {
  1054. handleIOTrouble(ioe);
  1055. }
  1056. }
  1057. /**
  1058. * {@inheritDoc}
  1059. */
  1060. protected void startVParea(CTM ctm, Rectangle2D clippingRect) {
  1061. saveGraphicsState();
  1062. if (clippingRect != null) {
  1063. clipRect((float)clippingRect.getX() / 1000f,
  1064. (float)clippingRect.getY() / 1000f,
  1065. (float)clippingRect.getWidth() / 1000f,
  1066. (float)clippingRect.getHeight() / 1000f);
  1067. }
  1068. // multiply with current CTM
  1069. final double[] matrix = ctm.toArray();
  1070. matrix[4] /= 1000f;
  1071. matrix[5] /= 1000f;
  1072. concatMatrix(matrix);
  1073. }
  1074. /**
  1075. * {@inheritDoc}
  1076. */
  1077. protected void endVParea() {
  1078. restoreGraphicsState();
  1079. }
  1080. /** {@inheritDoc} */
  1081. protected void renderBlockViewport(BlockViewport bv, List children) {
  1082. comment("%FOPBeginBlockViewport: " + bv.toString());
  1083. super.renderBlockViewport(bv, children);
  1084. comment("%FOPEndBlockViewport");
  1085. }
  1086. /** {@inheritDoc} */
  1087. protected void renderInlineParent(InlineParent ip) {
  1088. super.renderInlineParent(ip);
  1089. }
  1090. /** {@inheritDoc} */
  1091. public void renderLeader(Leader area) {
  1092. renderInlineAreaBackAndBorders(area);
  1093. int style = area.getRuleStyle();
  1094. int ruleThickness = area.getRuleThickness();
  1095. int startx = currentIPPosition + area.getBorderAndPaddingWidthStart();
  1096. int starty = currentBPPosition + area.getOffset() + (ruleThickness / 2);
  1097. int endx = currentIPPosition
  1098. + area.getBorderAndPaddingWidthStart()
  1099. + area.getIPD();
  1100. Color col = (Color)area.getTrait(Trait.COLOR);
  1101. endTextObject();
  1102. try {
  1103. borderPainter.drawLine(new Point(startx, starty), new Point(endx, starty),
  1104. ruleThickness, col, RuleStyle.valueOf(style));
  1105. } catch (IOException ioe) {
  1106. handleIOTrouble(ioe);
  1107. }
  1108. super.renderLeader(area);
  1109. }
  1110. /**
  1111. * {@inheritDoc}
  1112. */
  1113. public void renderImage(Image image, Rectangle2D pos) {
  1114. drawImage(image.getURL(), pos, image.getForeignAttributes());
  1115. }
  1116. /**
  1117. * {@inheritDoc}
  1118. */
  1119. protected RendererContext createRendererContext(int x, int y, int width, int height,
  1120. Map foreignAttributes) {
  1121. RendererContext context = super.createRendererContext(
  1122. x, y, width, height, foreignAttributes);
  1123. context.setProperty(PSRendererContextConstants.PS_GENERATOR, this.gen);
  1124. context.setProperty(PSRendererContextConstants.PS_FONT_INFO, fontInfo);
  1125. return context;
  1126. }
  1127. /** {@inheritDoc} */
  1128. public String getMimeType() {
  1129. return MIME_TYPE;
  1130. }
  1131. /**
  1132. * Sets whether or not the safe set page device macro should be used
  1133. * (as opposed to directly invoking setpagedevice) when setting the
  1134. * postscript page device.
  1135. *
  1136. * This option is a useful option when you want to guard against the possibility
  1137. * of invalid/unsupported postscript key/values being placed in the page device.
  1138. *
  1139. * @param safeSetPageDevice setting to false and the renderer will make a
  1140. * standard "setpagedevice" call, setting to true will make a safe set page
  1141. * device macro call (default is false).
  1142. */
  1143. public void setSafeSetPageDevice(boolean safeSetPageDevice) {
  1144. getPSUtil().setSafeSetPageDevice(safeSetPageDevice);
  1145. }
  1146. /**
  1147. * Sets whether or not PostScript Document Structuring Conventions (dsc) compliance are
  1148. * enforced.
  1149. * <p>
  1150. * It can cause problems (unwanted PostScript subsystem initgraphics/erasepage calls)
  1151. * on some printers when the pagedevice is set. If this causes problems on a
  1152. * particular implementation then use this setting with a 'false' value to try and
  1153. * minimize the number of setpagedevice calls in the postscript document output.
  1154. * <p>
  1155. * Set this value to false if you experience unwanted blank pages in your
  1156. * postscript output.
  1157. * @param dscCompliant boolean value (default is true)
  1158. */
  1159. public void setDSCCompliant(boolean dscCompliant) {
  1160. getPSUtil().setDSCComplianceEnabled(dscCompliant);
  1161. }
  1162. }