PageRenderTime 72ms CodeModel.GetById 29ms RepoModel.GetById 0ms app.codeStats 1ms

/jdk/src/share/classes/sun/print/PSPrinterJob.java

https://bitbucket.org/nkabir/jdk-6
Java | 2210 lines | 1309 code | 307 blank | 594 comment | 255 complexity | 5774c67d37b8a6cfb2789f7442ced070 MD5 | raw file
Possible License(s): LGPL-3.0, GPL-2.0, BSD-3-Clause-No-Nuclear-License-2014, BSD-3-Clause
  1. /*
  2. * Copyright (c) 1998, 2012, Oracle and/or its affiliates. All rights reserved.
  3. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4. *
  5. * This code is free software; you can redistribute it and/or modify it
  6. * under the terms of the GNU General Public License version 2 only, as
  7. * published by the Free Software Foundation. Oracle designates this
  8. * particular file as subject to the "Classpath" exception as provided
  9. * by Oracle in the LICENSE file that accompanied this code.
  10. *
  11. * This code is distributed in the hope that it will be useful, but WITHOUT
  12. * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13. * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
  14. * version 2 for more details (a copy is included in the LICENSE file that
  15. * accompanied this code).
  16. *
  17. * You should have received a copy of the GNU General Public License version
  18. * 2 along with this work; if not, write to the Free Software Foundation,
  19. * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20. *
  21. * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22. * or visit www.oracle.com if you need additional information or have any
  23. * questions.
  24. */
  25. package sun.print;
  26. import java.awt.Color;
  27. import java.awt.Component;
  28. import java.awt.Font;
  29. import java.awt.FontMetrics;
  30. import java.awt.GraphicsEnvironment;
  31. import java.awt.Graphics;
  32. import java.awt.Graphics2D;
  33. import java.awt.HeadlessException;
  34. import java.awt.Rectangle;
  35. import java.awt.Shape;
  36. import java.awt.image.BufferedImage;
  37. import java.awt.font.FontRenderContext;
  38. import java.awt.geom.AffineTransform;
  39. import java.awt.geom.PathIterator;
  40. import java.awt.geom.Rectangle2D;
  41. import java.awt.image.BufferedImage;
  42. import java.awt.print.Pageable;
  43. import java.awt.print.PageFormat;
  44. import java.awt.print.Paper;
  45. import java.awt.print.Printable;
  46. import java.awt.print.PrinterException;
  47. import java.awt.print.PrinterIOException;
  48. import java.awt.print.PrinterJob;
  49. import javax.print.DocFlavor;
  50. import javax.print.PrintService;
  51. import javax.print.StreamPrintService;
  52. import javax.print.attribute.HashPrintRequestAttributeSet;
  53. import javax.print.attribute.PrintRequestAttributeSet;
  54. import javax.print.attribute.standard.Chromaticity;
  55. import javax.print.attribute.standard.Copies;
  56. import javax.print.attribute.standard.Destination;
  57. import javax.print.attribute.standard.JobName;
  58. import javax.print.attribute.standard.Sides;
  59. import java.io.BufferedInputStream;
  60. import java.io.BufferedOutputStream;
  61. import java.io.CharConversionException;
  62. import java.io.File;
  63. import java.io.InputStream;
  64. import java.io.IOException;
  65. import java.io.FileInputStream;
  66. import java.io.FileOutputStream;
  67. import java.io.OutputStream;
  68. import java.io.PrintStream;
  69. import java.util.ArrayList;
  70. import java.util.Enumeration;
  71. import java.util.Locale;
  72. import java.util.Properties;
  73. import sun.awt.CharsetString;
  74. import sun.awt.FontConfiguration;
  75. import sun.awt.FontDescriptor;
  76. import sun.awt.PlatformFont;
  77. import sun.awt.SunToolkit;
  78. import java.nio.charset.*;
  79. import java.nio.CharBuffer;
  80. import java.nio.ByteBuffer;
  81. //REMIND: Remove use of this class when IPPPrintService is moved to share directory.
  82. import java.lang.reflect.Method;
  83. /**
  84. * A class which initiates and executes a PostScript printer job.
  85. *
  86. * @author Richard Blanchard
  87. */
  88. public class PSPrinterJob extends RasterPrinterJob {
  89. /* Class Constants */
  90. /**
  91. * Passed to the <code>setFillMode</code>
  92. * method this value forces fills to be
  93. * done using the even-odd fill rule.
  94. */
  95. protected static final int FILL_EVEN_ODD = 1;
  96. /**
  97. * Passed to the <code>setFillMode</code>
  98. * method this value forces fills to be
  99. * done using the non-zero winding rule.
  100. */
  101. protected static final int FILL_WINDING = 2;
  102. /* PostScript has a 64K maximum on its strings.
  103. */
  104. private static final int MAX_PSSTR = (1024 * 64 - 1);
  105. private static final int RED_MASK = 0x00ff0000;
  106. private static final int GREEN_MASK = 0x0000ff00;
  107. private static final int BLUE_MASK = 0x000000ff;
  108. private static final int RED_SHIFT = 16;
  109. private static final int GREEN_SHIFT = 8;
  110. private static final int BLUE_SHIFT = 0;
  111. private static final int LOWNIBBLE_MASK = 0x0000000f;
  112. private static final int HINIBBLE_MASK = 0x000000f0;
  113. private static final int HINIBBLE_SHIFT = 4;
  114. private static final byte hexDigits[] = {
  115. (byte)'0', (byte)'1', (byte)'2', (byte)'3',
  116. (byte)'4', (byte)'5', (byte)'6', (byte)'7',
  117. (byte)'8', (byte)'9', (byte)'A', (byte)'B',
  118. (byte)'C', (byte)'D', (byte)'E', (byte)'F'
  119. };
  120. private static final int PS_XRES = 300;
  121. private static final int PS_YRES = 300;
  122. private static final String ADOBE_PS_STR = "%!PS-Adobe-3.0";
  123. private static final String EOF_COMMENT = "%%EOF";
  124. private static final String PAGE_COMMENT = "%%Page: ";
  125. private static final String READIMAGEPROC = "/imStr 0 def /imageSrc " +
  126. "{currentfile /ASCII85Decode filter /RunLengthDecode filter " +
  127. " imStr readstring pop } def";
  128. private static final String COPIES = "/#copies exch def";
  129. private static final String PAGE_SAVE = "/pgSave save def";
  130. private static final String PAGE_RESTORE = "pgSave restore";
  131. private static final String SHOWPAGE = "showpage";
  132. private static final String IMAGE_SAVE = "/imSave save def";
  133. private static final String IMAGE_STR = " string /imStr exch def";
  134. private static final String IMAGE_RESTORE = "imSave restore";
  135. private static final String COORD_PREP = " 0 exch translate "
  136. + "1 -1 scale"
  137. + "[72 " + PS_XRES + " div "
  138. + "0 0 "
  139. + "72 " + PS_YRES + " div "
  140. + "0 0]concat";
  141. private static final String SetFontName = "F";
  142. private static final String DrawStringName = "S";
  143. /**
  144. * The PostScript invocation to fill a path using the
  145. * even-odd rule. (eofill)
  146. */
  147. private static final String EVEN_ODD_FILL_STR = "EF";
  148. /**
  149. * The PostScript invocation to fill a path using the
  150. * non-zero winding rule. (fill)
  151. */
  152. private static final String WINDING_FILL_STR = "WF";
  153. /**
  154. * The PostScript to set the clip to be the current path
  155. * using the even odd rule. (eoclip)
  156. */
  157. private static final String EVEN_ODD_CLIP_STR = "EC";
  158. /**
  159. * The PostScript to set the clip to be the current path
  160. * using the non-zero winding rule. (clip)
  161. */
  162. private static final String WINDING_CLIP_STR = "WC";
  163. /**
  164. * Expecting two numbers on the PostScript stack, this
  165. * invocation moves the current pen position. (moveto)
  166. */
  167. private static final String MOVETO_STR = " M";
  168. /**
  169. * Expecting two numbers on the PostScript stack, this
  170. * invocation draws a PS line from the current pen
  171. * position to the point on the stack. (lineto)
  172. */
  173. private static final String LINETO_STR = " L";
  174. /**
  175. * This PostScript operator takes two control points
  176. * and an ending point and using the current pen
  177. * position as a starting point adds a bezier
  178. * curve to the current path. (curveto)
  179. */
  180. private static final String CURVETO_STR = " C";
  181. /**
  182. * The PostScript to pop a state off of the printer's
  183. * gstate stack. (grestore)
  184. */
  185. private static final String GRESTORE_STR = "R";
  186. /**
  187. * The PostScript to push a state on to the printer's
  188. * gstate stack. (gsave)
  189. */
  190. private static final String GSAVE_STR = "G";
  191. /**
  192. * Make the current PostScript path an empty path. (newpath)
  193. */
  194. private static final String NEWPATH_STR = "N";
  195. /**
  196. * Close the current subpath by generating a line segment
  197. * from the current position to the start of the subpath. (closepath)
  198. */
  199. private static final String CLOSEPATH_STR = "P";
  200. /**
  201. * Use the three numbers on top of the PS operator
  202. * stack to set the rgb color. (setrgbcolor)
  203. */
  204. private static final String SETRGBCOLOR_STR = " SC";
  205. /**
  206. * Use the top number on the stack to set the printer's
  207. * current gray value. (setgray)
  208. */
  209. private static final String SETGRAY_STR = " SG";
  210. /* Instance Variables */
  211. private int mDestType;
  212. private String mDestination = "lp";
  213. private boolean mNoJobSheet = false;
  214. private String mOptions;
  215. private Font mLastFont;
  216. private Color mLastColor;
  217. private Shape mLastClip;
  218. private AffineTransform mLastTransform;
  219. /* non-null if printing EPS for Java Plugin */
  220. private EPSPrinter epsPrinter = null;
  221. /**
  222. * The metrics for the font currently set.
  223. */
  224. FontMetrics mCurMetrics;
  225. /**
  226. * The output stream to which the generated PostScript
  227. * is written.
  228. */
  229. PrintStream mPSStream;
  230. /* The temporary file to which we spool before sending to the printer */
  231. File spoolFile;
  232. /**
  233. * This string holds the PostScript operator to
  234. * be used to fill a path. It can be changed
  235. * by the <code>setFillMode</code> method.
  236. */
  237. private String mFillOpStr = WINDING_FILL_STR;
  238. /**
  239. * This string holds the PostScript operator to
  240. * be used to clip to a path. It can be changed
  241. * by the <code>setFillMode</code> method.
  242. */
  243. private String mClipOpStr = WINDING_CLIP_STR;
  244. /**
  245. * A stack that represents the PostScript gstate stack.
  246. */
  247. ArrayList mGStateStack = new ArrayList();
  248. /**
  249. * The x coordinate of the current pen position.
  250. */
  251. private float mPenX;
  252. /**
  253. * The y coordinate of the current pen position.
  254. */
  255. private float mPenY;
  256. /**
  257. * The x coordinate of the starting point of
  258. * the current subpath.
  259. */
  260. private float mStartPathX;
  261. /**
  262. * The y coordinate of the starting point of
  263. * the current subpath.
  264. */
  265. private float mStartPathY;
  266. /**
  267. * An optional mapping of fonts to PostScript names.
  268. */
  269. private static Properties mFontProps = null;
  270. /* Class static initialiser block */
  271. static {
  272. //enable priviledges so initProps can access system properties,
  273. // open the property file, etc.
  274. java.security.AccessController.doPrivileged(
  275. new java.security.PrivilegedAction() {
  276. public Object run() {
  277. mFontProps = initProps();
  278. return null;
  279. }
  280. });
  281. }
  282. /*
  283. * Initialize PostScript font properties.
  284. * Copied from PSPrintStream
  285. */
  286. private static Properties initProps() {
  287. // search psfont.properties for fonts
  288. // and create and initialize fontProps if it exist.
  289. String jhome = System.getProperty("java.home");
  290. if (jhome != null){
  291. String ulocale = SunToolkit.getStartupLocale().getLanguage();
  292. try {
  293. File f = new File(jhome + File.separator +
  294. "lib" + File.separator +
  295. "psfontj2d.properties." + ulocale);
  296. if (!f.canRead()){
  297. f = new File(jhome + File.separator +
  298. "lib" + File.separator +
  299. "psfont.properties." + ulocale);
  300. if (!f.canRead()){
  301. f = new File(jhome + File.separator + "lib" +
  302. File.separator + "psfontj2d.properties");
  303. if (!f.canRead()){
  304. f = new File(jhome + File.separator + "lib" +
  305. File.separator + "psfont.properties");
  306. if (!f.canRead()){
  307. return (Properties)null;
  308. }
  309. }
  310. }
  311. }
  312. // Load property file
  313. InputStream in =
  314. new BufferedInputStream(new FileInputStream(f.getPath()));
  315. Properties props = new Properties();
  316. props.load(in);
  317. in.close();
  318. return props;
  319. } catch (Exception e){
  320. return (Properties)null;
  321. }
  322. }
  323. return (Properties)null;
  324. }
  325. /* Constructors */
  326. public PSPrinterJob()
  327. {
  328. }
  329. /* Instance Methods */
  330. /**
  331. * Presents the user a dialog for changing properties of the
  332. * print job interactively.
  333. * @returns false if the user cancels the dialog and
  334. * true otherwise.
  335. * @exception HeadlessException if GraphicsEnvironment.isHeadless()
  336. * returns true.
  337. * @see java.awt.GraphicsEnvironment#isHeadless
  338. */
  339. public boolean printDialog() throws HeadlessException {
  340. if (GraphicsEnvironment.isHeadless()) {
  341. throw new HeadlessException();
  342. }
  343. if (attributes == null) {
  344. attributes = new HashPrintRequestAttributeSet();
  345. }
  346. attributes.add(new Copies(getCopies()));
  347. attributes.add(new JobName(getJobName(), null));
  348. boolean doPrint = false;
  349. DialogTypeSelection dts =
  350. (DialogTypeSelection)attributes.get(DialogTypeSelection.class);
  351. if (dts == DialogTypeSelection.NATIVE) {
  352. // Remove DialogTypeSelection.NATIVE to prevent infinite loop in
  353. // RasterPrinterJob.
  354. attributes.remove(DialogTypeSelection.class);
  355. doPrint = printDialog(attributes);
  356. // restore attribute
  357. attributes.add(DialogTypeSelection.NATIVE);
  358. } else {
  359. doPrint = printDialog(attributes);
  360. }
  361. if (doPrint) {
  362. JobName jobName = (JobName)attributes.get(JobName.class);
  363. if (jobName != null) {
  364. setJobName(jobName.getValue());
  365. }
  366. Copies copies = (Copies)attributes.get(Copies.class);
  367. if (copies != null) {
  368. setCopies(copies.getValue());
  369. }
  370. Destination dest = (Destination)attributes.get(Destination.class);
  371. if (dest != null) {
  372. try {
  373. mDestType = RasterPrinterJob.FILE;
  374. mDestination = (new File(dest.getURI())).getPath();
  375. } catch (Exception e) {
  376. mDestination = "out.ps";
  377. }
  378. } else {
  379. mDestType = RasterPrinterJob.PRINTER;
  380. PrintService pServ = getPrintService();
  381. if (pServ != null) {
  382. mDestination = pServ.getName();
  383. }
  384. }
  385. }
  386. return doPrint;
  387. }
  388. /**
  389. * Invoked by the RasterPrinterJob super class
  390. * this method is called to mark the start of a
  391. * document.
  392. */
  393. protected void startDoc() throws PrinterException {
  394. // A security check has been performed in the
  395. // java.awt.print.printerJob.getPrinterJob method.
  396. // We use an inner class to execute the privilged open operations.
  397. // Note that we only open a file if it has been nominated by
  398. // the end-user in a dialog that we ouselves put up.
  399. OutputStream output;
  400. if (epsPrinter == null) {
  401. if (getPrintService() instanceof PSStreamPrintService) {
  402. StreamPrintService sps = (StreamPrintService)getPrintService();
  403. mDestType = RasterPrinterJob.STREAM;
  404. if (sps.isDisposed()) {
  405. throw new PrinterException("service is disposed");
  406. }
  407. output = sps.getOutputStream();
  408. if (output == null) {
  409. throw new PrinterException("Null output stream");
  410. }
  411. } else {
  412. /* REMIND: This needs to be more maintainable */
  413. mNoJobSheet = super.noJobSheet;
  414. if (super.destinationAttr != null) {
  415. mDestType = RasterPrinterJob.FILE;
  416. mDestination = super.destinationAttr;
  417. }
  418. if (mDestType == RasterPrinterJob.FILE) {
  419. try {
  420. spoolFile = new File(mDestination);
  421. output = new FileOutputStream(spoolFile);
  422. } catch (IOException ex) {
  423. throw new PrinterIOException(ex);
  424. }
  425. } else {
  426. PrinterOpener po = new PrinterOpener();
  427. java.security.AccessController.doPrivileged(po);
  428. if (po.pex != null) {
  429. throw po.pex;
  430. }
  431. output = po.result;
  432. }
  433. }
  434. mPSStream = new PrintStream(new BufferedOutputStream(output));
  435. mPSStream.println(ADOBE_PS_STR);
  436. }
  437. mPSStream.println("%%BeginProlog");
  438. mPSStream.println(READIMAGEPROC);
  439. mPSStream.println("/BD {bind def} bind def");
  440. mPSStream.println("/D {def} BD");
  441. mPSStream.println("/C {curveto} BD");
  442. mPSStream.println("/L {lineto} BD");
  443. mPSStream.println("/M {moveto} BD");
  444. mPSStream.println("/R {grestore} BD");
  445. mPSStream.println("/G {gsave} BD");
  446. mPSStream.println("/N {newpath} BD");
  447. mPSStream.println("/P {closepath} BD");
  448. mPSStream.println("/EC {eoclip} BD");
  449. mPSStream.println("/WC {clip} BD");
  450. mPSStream.println("/EF {eofill} BD");
  451. mPSStream.println("/WF {fill} BD");
  452. mPSStream.println("/SG {setgray} BD");
  453. mPSStream.println("/SC {setrgbcolor} BD");
  454. mPSStream.println("/ISOF {");
  455. mPSStream.println(" dup findfont dup length 1 add dict begin {");
  456. mPSStream.println(" 1 index /FID eq {pop pop} {D} ifelse");
  457. mPSStream.println(" } forall /Encoding ISOLatin1Encoding D");
  458. mPSStream.println(" currentdict end definefont");
  459. mPSStream.println("} BD");
  460. mPSStream.println("/NZ {dup 1 lt {pop 1} if} BD");
  461. /* The following procedure takes args: string, x, y, desiredWidth.
  462. * It calculates using stringwidth the width of the string in the
  463. * current font and subtracts it from the desiredWidth and divides
  464. * this by stringLen-1. This gives us a per-glyph adjustment in
  465. * the spacing needed (either +ve or -ve) to make the string
  466. * print at the desiredWidth. The ashow procedure call takes this
  467. * per-glyph adjustment as an argument. This is necessary for WYSIWYG
  468. */
  469. mPSStream.println("/"+DrawStringName +" {");
  470. mPSStream.println(" moveto 1 index stringwidth pop NZ sub");
  471. mPSStream.println(" 1 index length 1 sub NZ div 0");
  472. mPSStream.println(" 3 2 roll ashow newpath} BD");
  473. mPSStream.println("/FL [");
  474. if (mFontProps == null){
  475. mPSStream.println(" /Helvetica ISOF");
  476. mPSStream.println(" /Helvetica-Bold ISOF");
  477. mPSStream.println(" /Helvetica-Oblique ISOF");
  478. mPSStream.println(" /Helvetica-BoldOblique ISOF");
  479. mPSStream.println(" /Times-Roman ISOF");
  480. mPSStream.println(" /Times-Bold ISOF");
  481. mPSStream.println(" /Times-Italic ISOF");
  482. mPSStream.println(" /Times-BoldItalic ISOF");
  483. mPSStream.println(" /Courier ISOF");
  484. mPSStream.println(" /Courier-Bold ISOF");
  485. mPSStream.println(" /Courier-Oblique ISOF");
  486. mPSStream.println(" /Courier-BoldOblique ISOF");
  487. } else {
  488. int cnt = Integer.parseInt(mFontProps.getProperty("font.num", "9"));
  489. for (int i = 0; i < cnt; i++){
  490. mPSStream.println(" /" + mFontProps.getProperty
  491. ("font." + String.valueOf(i), "Courier ISOF"));
  492. }
  493. }
  494. mPSStream.println("] D");
  495. mPSStream.println("/"+SetFontName +" {");
  496. mPSStream.println(" FL exch get exch scalefont");
  497. mPSStream.println(" [1 0 0 -1 0 0] makefont setfont} BD");
  498. mPSStream.println("%%EndProlog");
  499. mPSStream.println("%%BeginSetup");
  500. if (epsPrinter == null) {
  501. // Set Page Size using first page's format.
  502. PageFormat pageFormat = getPageable().getPageFormat(0);
  503. double paperHeight = pageFormat.getPaper().getHeight();
  504. double paperWidth = pageFormat.getPaper().getWidth();
  505. /* PostScript printers can always generate uncollated copies.
  506. */
  507. mPSStream.print("<< /PageSize [" +
  508. paperWidth + " "+ paperHeight+"]");
  509. final PrintService pservice = getPrintService();
  510. Boolean isPS = (Boolean)java.security.AccessController.doPrivileged(
  511. new java.security.PrivilegedAction() {
  512. public Object run() {
  513. try {
  514. Class psClass = Class.forName("sun.print.IPPPrintService");
  515. if (psClass.isInstance(pservice)) {
  516. Method isPSMethod = psClass.getMethod("isPostscript",
  517. (Class[])null);
  518. return (Boolean)isPSMethod.invoke(pservice, (Object[])null);
  519. }
  520. } catch (Throwable t) {
  521. }
  522. return Boolean.TRUE;
  523. }
  524. }
  525. );
  526. if (isPS) {
  527. mPSStream.print(" /DeferredMediaSelection true");
  528. }
  529. mPSStream.print(" /ImagingBBox null /ManualFeed false");
  530. mPSStream.print(isCollated() ? " /Collate true":"");
  531. mPSStream.print(" /NumCopies " +getCopiesInt());
  532. if (sidesAttr != Sides.ONE_SIDED) {
  533. if (sidesAttr == Sides.TWO_SIDED_LONG_EDGE) {
  534. mPSStream.print(" /Duplex true ");
  535. } else if (sidesAttr == Sides.TWO_SIDED_SHORT_EDGE) {
  536. mPSStream.print(" /Duplex true /Tumble true ");
  537. }
  538. }
  539. mPSStream.println(" >> setpagedevice ");
  540. }
  541. mPSStream.println("%%EndSetup");
  542. }
  543. // Inner class to run "privileged" to open the printer output stream.
  544. private class PrinterOpener implements java.security.PrivilegedAction {
  545. PrinterException pex;
  546. OutputStream result;
  547. public Object run() {
  548. try {
  549. /* Write to a temporary file which will be spooled to
  550. * the printer then deleted. In the case that the file
  551. * is not removed for some reason, request that it is
  552. * removed when the VM exits.
  553. */
  554. spoolFile = sun.misc.IOUtils.createTempFile("javaprint", ".ps", null);
  555. spoolFile.deleteOnExit();
  556. result = new FileOutputStream(spoolFile);
  557. return result;
  558. } catch (IOException ex) {
  559. // If there is an IOError we subvert it to a PrinterException.
  560. pex = new PrinterIOException(ex);
  561. }
  562. return null;
  563. }
  564. }
  565. // Inner class to run "privileged" to invoke the system print command
  566. private class PrinterSpooler implements java.security.PrivilegedAction {
  567. PrinterException pex;
  568. public Object run() {
  569. try {
  570. /**
  571. * Spool to the printer.
  572. */
  573. if (spoolFile == null || !spoolFile.exists()) {
  574. pex = new PrinterException("No spool file");
  575. return null;
  576. }
  577. String fileName = spoolFile.getAbsolutePath();
  578. String execCmd[] = printExecCmd(mDestination, mOptions,
  579. mNoJobSheet, getJobNameInt(),
  580. 1, fileName);
  581. Process process = Runtime.getRuntime().exec(execCmd);
  582. process.waitFor();
  583. spoolFile.delete();
  584. } catch (IOException ex) {
  585. pex = new PrinterIOException(ex);
  586. } catch (InterruptedException ie) {
  587. pex = new PrinterException(ie.toString());
  588. }
  589. return null;
  590. }
  591. }
  592. /**
  593. * Invoked if the application cancelled the printjob.
  594. */
  595. protected void abortDoc() {
  596. if (mPSStream != null && mDestType != RasterPrinterJob.STREAM) {
  597. mPSStream.close();
  598. }
  599. java.security.AccessController.doPrivileged(
  600. new java.security.PrivilegedAction() {
  601. public Object run() {
  602. if (spoolFile != null && spoolFile.exists()) {
  603. spoolFile.delete();
  604. }
  605. return null;
  606. }
  607. });
  608. }
  609. /**
  610. * Invoked by the RasterPrintJob super class
  611. * this method is called after that last page
  612. * has been imaged.
  613. */
  614. protected void endDoc() throws PrinterException {
  615. if (mPSStream != null) {
  616. mPSStream.println(EOF_COMMENT);
  617. mPSStream.flush();
  618. if (mDestType != RasterPrinterJob.STREAM) {
  619. mPSStream.close();
  620. }
  621. }
  622. if (mDestType == RasterPrinterJob.PRINTER) {
  623. if (getPrintService() != null) {
  624. mDestination = getPrintService().getName();
  625. }
  626. PrinterSpooler spooler = new PrinterSpooler();
  627. java.security.AccessController.doPrivileged(spooler);
  628. if (spooler.pex != null) {
  629. throw spooler.pex;
  630. }
  631. }
  632. }
  633. /**
  634. * The RasterPrintJob super class calls this method
  635. * at the start of each page.
  636. */
  637. protected void startPage(PageFormat pageFormat, Printable painter,
  638. int index, boolean paperChanged)
  639. throws PrinterException
  640. {
  641. double paperHeight = pageFormat.getPaper().getHeight();
  642. double paperWidth = pageFormat.getPaper().getWidth();
  643. int pageNumber = index + 1;
  644. /* Place an initial gstate on to our gstate stack.
  645. * It will have the default PostScript gstate
  646. * attributes.
  647. */
  648. mGStateStack = new ArrayList();
  649. mGStateStack.add(new GState());
  650. mPSStream.println(PAGE_COMMENT + pageNumber + " " + pageNumber);
  651. /* Check current page's pageFormat against the previous pageFormat,
  652. */
  653. if (index > 0 && paperChanged) {
  654. mPSStream.print("<< /PageSize [" +
  655. paperWidth + " " + paperHeight + "]");
  656. final PrintService pservice = getPrintService();
  657. Boolean isPS =
  658. (Boolean)java.security.AccessController.doPrivileged(
  659. new java.security.PrivilegedAction() {
  660. public Object run() {
  661. try {
  662. Class psClass =
  663. Class.forName("sun.print.IPPPrintService");
  664. if (psClass.isInstance(pservice)) {
  665. Method isPSMethod =
  666. psClass.getMethod("isPostscript",
  667. (Class[])null);
  668. return (Boolean)
  669. isPSMethod.invoke(pservice,
  670. (Object[])null);
  671. }
  672. } catch (Throwable t) {
  673. }
  674. return Boolean.TRUE;
  675. }
  676. }
  677. );
  678. if (isPS) {
  679. mPSStream.print(" /DeferredMediaSelection true");
  680. }
  681. mPSStream.println(" >> setpagedevice");
  682. }
  683. mPSStream.println(PAGE_SAVE);
  684. mPSStream.println(paperHeight + COORD_PREP);
  685. }
  686. /**
  687. * The RastePrintJob super class calls this method
  688. * at the end of each page.
  689. */
  690. protected void endPage(PageFormat format, Printable painter,
  691. int index)
  692. throws PrinterException
  693. {
  694. mPSStream.println(PAGE_RESTORE);
  695. mPSStream.println(SHOWPAGE);
  696. }
  697. /**
  698. * Convert the 24 bit BGR image buffer represented by
  699. * <code>image</code> to PostScript. The image is drawn at
  700. * <code>(destX, destY)</code> in device coordinates.
  701. * The image is scaled into a square of size
  702. * specified by <code>destWidth</code> and
  703. * <code>destHeight</code>. The portion of the
  704. * source image copied into that square is specified
  705. * by <code>srcX</code>, <code>srcY</code>,
  706. * <code>srcWidth</code>, and srcHeight.
  707. */
  708. protected void drawImageBGR(byte[] bgrData,
  709. float destX, float destY,
  710. float destWidth, float destHeight,
  711. float srcX, float srcY,
  712. float srcWidth, float srcHeight,
  713. int srcBitMapWidth, int srcBitMapHeight) {
  714. /* We draw images at device resolution so we probably need
  715. * to change the current PostScript transform.
  716. */
  717. setTransform(new AffineTransform());
  718. prepDrawing();
  719. int intSrcWidth = (int) srcWidth;
  720. int intSrcHeight = (int) srcHeight;
  721. mPSStream.println(IMAGE_SAVE);
  722. /* Create a PS string big enough to hold a row of pixels.
  723. */
  724. int psBytesPerRow = 3 * (int) intSrcWidth;
  725. while (psBytesPerRow > MAX_PSSTR) {
  726. psBytesPerRow /= 2;
  727. }
  728. mPSStream.println(psBytesPerRow + IMAGE_STR);
  729. /* Scale and translate the unit image.
  730. */
  731. mPSStream.println("[" + destWidth + " 0 "
  732. + "0 " + destHeight
  733. + " " + destX + " " + destY
  734. +"]concat");
  735. /* Color Image invocation.
  736. */
  737. mPSStream.println(intSrcWidth + " " + intSrcHeight + " " + 8 + "["
  738. + intSrcWidth + " 0 "
  739. + "0 " + intSrcHeight
  740. + " 0 " + 0 + "]"
  741. + "/imageSrc load false 3 colorimage");
  742. /* Image data.
  743. */
  744. int index = 0;
  745. byte[] rgbData = new byte[intSrcWidth * 3];
  746. try {
  747. /* Skip the parts of the image that are not part
  748. * of the source rectangle.
  749. */
  750. index = (int) srcY * srcBitMapWidth;
  751. for(int i = 0; i < intSrcHeight; i++) {
  752. /* Skip the left part of the image that is not
  753. * part of the source rectangle.
  754. */
  755. index += (int) srcX;
  756. index = swapBGRtoRGB(bgrData, index, rgbData);
  757. byte[] encodedData = rlEncode(rgbData);
  758. byte[] asciiData = ascii85Encode(encodedData);
  759. mPSStream.write(asciiData);
  760. mPSStream.println("");
  761. }
  762. /*
  763. * If there is an IOError we subvert it to a PrinterException.
  764. * Fix: There has got to be a better way, maybe define
  765. * a PrinterIOException and then throw that?
  766. */
  767. } catch (IOException e) {
  768. //throw new PrinterException(e.toString());
  769. }
  770. mPSStream.println(IMAGE_RESTORE);
  771. }
  772. /**
  773. * Prints the contents of the array of ints, 'data'
  774. * to the current page. The band is placed at the
  775. * location (x, y) in device coordinates on the
  776. * page. The width and height of the band is
  777. * specified by the caller. Currently the data
  778. * is 24 bits per pixel in BGR format.
  779. */
  780. protected void printBand(byte[] bgrData, int x, int y,
  781. int width, int height)
  782. throws PrinterException
  783. {
  784. mPSStream.println(IMAGE_SAVE);
  785. /* Create a PS string big enough to hold a row of pixels.
  786. */
  787. int psBytesPerRow = 3 * width;
  788. while (psBytesPerRow > MAX_PSSTR) {
  789. psBytesPerRow /= 2;
  790. }
  791. mPSStream.println(psBytesPerRow + IMAGE_STR);
  792. /* Scale and translate the unit image.
  793. */
  794. mPSStream.println("[" + width + " 0 "
  795. + "0 " + height
  796. + " " + x + " " + y
  797. +"]concat");
  798. /* Color Image invocation.
  799. */
  800. mPSStream.println(width + " " + height + " " + 8 + "["
  801. + width + " 0 "
  802. + "0 " + -height
  803. + " 0 " + height + "]"
  804. + "/imageSrc load false 3 colorimage");
  805. /* Image data.
  806. */
  807. int index = 0;
  808. byte[] rgbData = new byte[width*3];
  809. try {
  810. for(int i = 0; i < height; i++) {
  811. index = swapBGRtoRGB(bgrData, index, rgbData);
  812. byte[] encodedData = rlEncode(rgbData);
  813. byte[] asciiData = ascii85Encode(encodedData);
  814. mPSStream.write(asciiData);
  815. mPSStream.println("");
  816. }
  817. } catch (IOException e) {
  818. throw new PrinterIOException(e);
  819. }
  820. mPSStream.println(IMAGE_RESTORE);
  821. }
  822. /**
  823. * Examine the metrics captured by the
  824. * <code>PeekGraphics</code> instance and
  825. * if capable of directly converting this
  826. * print job to the printer's control language
  827. * or the native OS's graphics primitives, then
  828. * return a <code>PSPathGraphics</code> to perform
  829. * that conversion. If there is not an object
  830. * capable of the conversion then return
  831. * <code>null</code>. Returning <code>null</code>
  832. * causes the print job to be rasterized.
  833. */
  834. protected Graphics2D createPathGraphics(PeekGraphics peekGraphics,
  835. PrinterJob printerJob,
  836. Printable painter,
  837. PageFormat pageFormat,
  838. int pageIndex) {
  839. PSPathGraphics pathGraphics;
  840. PeekMetrics metrics = peekGraphics.getMetrics();
  841. /* If the application has drawn anything that
  842. * out PathGraphics class can not handle then
  843. * return a null PathGraphics.
  844. */
  845. if (forcePDL == false && (forceRaster == true
  846. || metrics.hasNonSolidColors()
  847. || metrics.hasCompositing())) {
  848. pathGraphics = null;
  849. } else {
  850. BufferedImage bufferedImage = new BufferedImage(8, 8,
  851. BufferedImage.TYPE_INT_RGB);
  852. Graphics2D bufferedGraphics = bufferedImage.createGraphics();
  853. boolean canRedraw = peekGraphics.getAWTDrawingOnly() == false;
  854. pathGraphics = new PSPathGraphics(bufferedGraphics, printerJob,
  855. painter, pageFormat, pageIndex,
  856. canRedraw);
  857. }
  858. return pathGraphics;
  859. }
  860. /**
  861. * Intersect the gstate's current path with the
  862. * current clip and make the result the new clip.
  863. */
  864. protected void selectClipPath() {
  865. mPSStream.println(mClipOpStr);
  866. }
  867. protected void setClip(Shape clip) {
  868. mLastClip = clip;
  869. }
  870. protected void setTransform(AffineTransform transform) {
  871. mLastTransform = transform;
  872. }
  873. /**
  874. * Set the current PostScript font.
  875. * Taken from outFont in PSPrintStream.
  876. */
  877. protected boolean setFont(Font font) {
  878. mLastFont = font;
  879. return true;
  880. }
  881. /**
  882. * Given an array of CharsetStrings that make up a run
  883. * of text, this routine converts each CharsetString to
  884. * an index into our PostScript font list. If one or more
  885. * CharsetStrings can not be represented by a PostScript
  886. * font, then this routine will return a null array.
  887. */
  888. private int[] getPSFontIndexArray(Font font, CharsetString[] charSet) {
  889. int[] psFont = null;
  890. if (mFontProps != null) {
  891. psFont = new int[charSet.length];
  892. }
  893. for (int i = 0; i < charSet.length && psFont != null; i++){
  894. /* Get the encoding of the run of text.
  895. */
  896. CharsetString cs = charSet[i];
  897. CharsetEncoder fontCS = cs.fontDescriptor.encoder;
  898. String charsetName = cs.fontDescriptor.getFontCharsetName();
  899. /*
  900. * sun.awt.Symbol perhaps should return "symbol" for encoding.
  901. * Similarly X11Dingbats should return "dingbats"
  902. * Forced to check for win32 & x/unix names for these converters.
  903. */
  904. if ("Symbol".equals(charsetName)) {
  905. charsetName = "symbol";
  906. } else if ("WingDings".equals(charsetName) ||
  907. "X11Dingbats".equals(charsetName)) {
  908. charsetName = "dingbats";
  909. } else {
  910. charsetName = makeCharsetName(charsetName, cs.charsetChars);
  911. }
  912. int styleMask = font.getStyle() |
  913. sun.font.FontManager.getFont2D(font).getStyle();
  914. String style = FontConfiguration.getStyleString(styleMask);
  915. /* First we map the font name through the properties file.
  916. * This mapping provides alias names for fonts, for example,
  917. * "timesroman" is mapped to "serif".
  918. */
  919. String fontName = font.getFamily().toLowerCase(Locale.ENGLISH);
  920. fontName = fontName.replace(' ', '_');
  921. String name = mFontProps.getProperty(fontName, "");
  922. /* Now map the alias name, character set name, and style
  923. * to a PostScript name.
  924. */
  925. String psName =
  926. mFontProps.getProperty(name + "." + charsetName + "." + style,
  927. null);
  928. if (psName != null) {
  929. /* Get the PostScript font index for the PostScript font.
  930. */
  931. try {
  932. psFont[i] =
  933. Integer.parseInt(mFontProps.getProperty(psName));
  934. /* If there is no PostScript font for this font name,
  935. * then we want to termintate the loop and the method
  936. * indicating our failure. Setting the array to null
  937. * is used to indicate these failures.
  938. */
  939. } catch(NumberFormatException e){
  940. psFont = null;
  941. }
  942. /* There was no PostScript name for the font, character set,
  943. * and style so give up.
  944. */
  945. } else {
  946. psFont = null;
  947. }
  948. }
  949. return psFont;
  950. }
  951. private static String escapeParens(String str) {
  952. if (str.indexOf('(') == -1 && str.indexOf(')') == -1 ) {
  953. return str;
  954. } else {
  955. int count = 0;
  956. int pos = 0;
  957. while ((pos = str.indexOf('(', pos)) != -1) {
  958. count++;
  959. pos++;
  960. }
  961. pos = 0;
  962. while ((pos = str.indexOf(')', pos)) != -1) {
  963. count++;
  964. pos++;
  965. }
  966. char []inArr = str.toCharArray();
  967. char []outArr = new char[inArr.length+count];
  968. pos = 0;
  969. for (int i=0;i<inArr.length;i++) {
  970. if (inArr[i] == '(' || inArr[i] == ')') {
  971. outArr[pos++] = '\\';
  972. }
  973. outArr[pos++] = inArr[i];
  974. }
  975. return new String(outArr);
  976. }
  977. }
  978. /* return of 0 means unsupported. Other return indicates the number
  979. * of distinct PS fonts needed to draw this text. This saves us
  980. * doing this processing one extra time.
  981. */
  982. protected int platformFontCount(Font font, String str) {
  983. if (mFontProps == null) {
  984. return 0;
  985. }
  986. CharsetString[] acs =
  987. ((PlatformFont)(font.getPeer())).makeMultiCharsetString(str,false);
  988. if (acs == null) {
  989. /* AWT can't convert all chars so use 2D path */
  990. return 0;
  991. }
  992. int[] psFonts = getPSFontIndexArray(font, acs);
  993. return (psFonts == null) ? 0 : psFonts.length;
  994. }
  995. protected boolean textOut(Graphics g, String str, float x, float y,
  996. Font mLastFont, FontRenderContext frc,
  997. float width) {
  998. boolean didText = true;
  999. if (mFontProps == null) {
  1000. return false;
  1001. } else {
  1002. prepDrawing();
  1003. /* On-screen drawString renders most control chars as the missing
  1004. * glyph and have the non-zero advance of that glyph.
  1005. * Exceptions are \t, \n and \r which are considered zero-width.
  1006. * Postscript handles control chars mostly as a missing glyph.
  1007. * But we use 'ashow' specifying a width for the string which
  1008. * assumes zero-width for those three exceptions, and Postscript
  1009. * tries to squeeze the extra char in, with the result that the
  1010. * glyphs look compressed or even overlap.
  1011. * So exclude those control chars from the string sent to PS.
  1012. */
  1013. str = removeControlChars(str);
  1014. if (str.length() == 0) {
  1015. return true;
  1016. }
  1017. CharsetString[] acs =
  1018. ((PlatformFont)
  1019. (mLastFont.getPeer())).makeMultiCharsetString(str, false);
  1020. if (acs == null) {
  1021. /* AWT can't convert all chars so use 2D path */
  1022. return false;
  1023. }
  1024. /* Get an array of indices into our PostScript name
  1025. * table. If all of the runs can not be converted
  1026. * to PostScript fonts then null is returned and
  1027. * we'll want to fall back to printing the text
  1028. * as shapes.
  1029. */
  1030. int[] psFonts = getPSFontIndexArray(mLastFont, acs);
  1031. if (psFonts != null) {
  1032. for (int i = 0; i < acs.length; i++){
  1033. CharsetString cs = acs[i];
  1034. CharsetEncoder fontCS = cs.fontDescriptor.encoder;
  1035. StringBuffer nativeStr = new StringBuffer();
  1036. byte[] strSeg = new byte[cs.length * 2];
  1037. int len = 0;
  1038. try {
  1039. ByteBuffer bb = ByteBuffer.wrap(strSeg);
  1040. fontCS.encode(CharBuffer.wrap(cs.charsetChars,
  1041. cs.offset,
  1042. cs.length),
  1043. bb, true);
  1044. bb.flip();
  1045. len = bb.limit();
  1046. } catch(IllegalStateException xx){
  1047. continue;
  1048. } catch(CoderMalfunctionError xx){
  1049. continue;
  1050. }
  1051. /* The width to fit to may either be specified,
  1052. * or calculated. Specifying by the caller is only
  1053. * valid if the text does not need to be decomposed
  1054. * into multiple calls.
  1055. */
  1056. float desiredWidth;
  1057. if (acs.length == 1 && width != 0f) {
  1058. desiredWidth = width;
  1059. } else {
  1060. Rectangle2D r2d =
  1061. mLastFont.getStringBounds(cs.charsetChars,
  1062. cs.offset,
  1063. cs.offset+cs.length,
  1064. frc);
  1065. desiredWidth = (float)r2d.getWidth();
  1066. }
  1067. /* unprintable chars had width of 0, causing a PS error
  1068. */
  1069. if (desiredWidth == 0) {
  1070. return didText;
  1071. }
  1072. nativeStr.append('<');
  1073. for (int j = 0; j < len; j++){
  1074. byte b = strSeg[j];
  1075. // to avoid encoding conversion with println()
  1076. String hexS = Integer.toHexString(b);
  1077. int length = hexS.length();
  1078. if (length > 2) {
  1079. hexS = hexS.substring(length - 2, length);
  1080. } else if (length == 1) {
  1081. hexS = "0" + hexS;
  1082. } else if (length == 0) {
  1083. hexS = "00";
  1084. }
  1085. nativeStr.append(hexS);
  1086. }
  1087. nativeStr.append('>');
  1088. /* This comment costs too much in output file size */
  1089. // mPSStream.println("% Font[" + mLastFont.getName() + ", " +
  1090. // FontConfiguration.getStyleString(mLastFont.getStyle()) + ", "
  1091. // + mLastFont.getSize2D() + "]");
  1092. getGState().emitPSFont(psFonts[i], mLastFont.getSize2D());
  1093. // out String
  1094. mPSStream.println(nativeStr.toString() + " " +
  1095. desiredWidth + " " + x + " " + y + " " +
  1096. DrawStringName);
  1097. x += desiredWidth;
  1098. }
  1099. } else {
  1100. didText = false;
  1101. }
  1102. }
  1103. return didText;
  1104. }
  1105. /**
  1106. * Set the current path rule to be either
  1107. * <code>FILL_EVEN_ODD</code> (using the
  1108. * even-odd file rule) or <code>FILL_WINDING</code>
  1109. * (using the non-zero winding rule.)
  1110. */
  1111. protected void setFillMode(int fillRule) {
  1112. switch (fillRule) {
  1113. case FILL_EVEN_ODD:
  1114. mFillOpStr = EVEN_ODD_FILL_STR;
  1115. mClipOpStr = EVEN_ODD_CLIP_STR;
  1116. break;
  1117. case FILL_WINDING:
  1118. mFillOpStr = WINDING_FILL_STR;
  1119. mClipOpStr = WINDING_CLIP_STR;
  1120. break;
  1121. default:
  1122. throw new IllegalArgumentException();
  1123. }
  1124. }
  1125. /**
  1126. * Set the printer's current color to be that
  1127. * defined by <code>color</code>
  1128. */
  1129. protected void setColor(Color color) {
  1130. mLastColor = color;
  1131. }
  1132. /**
  1133. * Fill the current path using the current fill mode
  1134. * and color.
  1135. */
  1136. protected void fillPath() {
  1137. mPSStream.println(mFillOpStr);
  1138. }
  1139. /**
  1140. * Called to mark the start of a new path.
  1141. */
  1142. protected void beginPath() {
  1143. prepDrawing();
  1144. mPSStream.println(NEWPATH_STR);
  1145. mPenX = 0;
  1146. mPenY = 0;
  1147. }
  1148. /**
  1149. * Close the current subpath by appending a straight
  1150. * line from the current point to the subpath's
  1151. * starting point.
  1152. */
  1153. protected void closeSubpath() {
  1154. mPSStream.println(CLOSEPATH_STR);
  1155. mPenX = mStartPathX;
  1156. mPenY = mStartPathY;
  1157. }
  1158. /**
  1159. * Generate PostScript to move the current pen
  1160. * position to <code>(x, y)</code>.
  1161. */
  1162. protected void moveTo(float x, float y) {
  1163. mPSStream.println(trunc(x) + " " + trunc(y) + MOVETO_STR);
  1164. /* moveto marks the start of a new subpath
  1165. * and we need to remember that starting
  1166. * position so that we know where the
  1167. * pen returns to with a close path.
  1168. */
  1169. mStartPathX = x;
  1170. mStartPathY = y;
  1171. mPenX = x;
  1172. mPenY = y;
  1173. }
  1174. /**
  1175. * Generate PostScript to draw a line from the
  1176. * current pen position to <code>(x, y)</code>.
  1177. */
  1178. protected void lineTo(float x, float y) {
  1179. mPSStream.println(trunc(x) + " " + trunc(y) + LINETO_STR);
  1180. mPenX = x;
  1181. mPenY = y;
  1182. }
  1183. /**
  1184. * Add to the current path a bezier curve formed
  1185. * by the current pen position and the method parameters
  1186. * which are two control points and an ending
  1187. * point.
  1188. */
  1189. protected void bezierTo(float control1x, float control1y,
  1190. float control2x, float control2y,
  1191. float endX, float endY) {
  1192. // mPSStream.println(control1x + " " + control1y
  1193. // + " " + control2x + " " + control2y
  1194. // + " " + endX + " " + endY
  1195. // + CURVETO_STR);
  1196. mPSStream.println(trunc(control1x) + " " + trunc(control1y)
  1197. + " " + trunc(control2x) + " " + trunc(control2y)
  1198. + " " + trunc(endX) + " " + trunc(endY)
  1199. + CURVETO_STR);
  1200. mPenX = endX;
  1201. mPenY = endY;
  1202. }
  1203. String trunc(float f) {
  1204. float af = Math.abs(f);
  1205. if (af >= 1f && af <=1000f) {
  1206. f = Math.round(f*1000)/1000f;
  1207. }
  1208. return Float.toString(f);
  1209. }
  1210. /**
  1211. * Return the x coordinate of the pen in the
  1212. * current path.
  1213. */
  1214. protected float getPenX() {
  1215. return mPenX;
  1216. }
  1217. /**
  1218. * Return the y coordinate of the pen in the
  1219. * current path.
  1220. */
  1221. protected float getPenY() {
  1222. return mPenY;
  1223. }
  1224. /**
  1225. * Return the x resolution of the coordinates
  1226. * to be rendered.
  1227. */
  1228. protected double getXRes() {
  1229. return PS_XRES;
  1230. }
  1231. /**
  1232. * Return the y resolution of the coordinates
  1233. * to be rendered.
  1234. */
  1235. protected double getYRes() {
  1236. return PS_YRES;
  1237. }
  1238. /**
  1239. * For PostScript the origin is in the upper-left of the
  1240. * paper not at the imageable area corner.
  1241. */
  1242. protected double getPhysicalPrintableX(Paper p) {
  1243. return 0;
  1244. }
  1245. /**
  1246. * For PostScript the origin is in the upper-left of the
  1247. * paper not at the imageable area corner.
  1248. */
  1249. protected double getPhysicalPrintableY(Paper p) {
  1250. return 0;
  1251. }
  1252. protected double getPhysicalPrintableWidth(Paper p) {
  1253. return p.getImageableWidth();
  1254. }
  1255. protected double getPhysicalPrintableHeight(Paper p) {
  1256. return p.getImageableHeight();
  1257. }
  1258. protected double getPhysicalPageWidth(Paper p) {
  1259. return p.getWidth();
  1260. }
  1261. protected double getPhysicalPageHeight(Paper p) {
  1262. return p.getHeight();
  1263. }
  1264. /**
  1265. * Returns how many times each page in the book
  1266. * should be consecutively printed by PrintJob.
  1267. * If the printer makes copies itself then this
  1268. * method should return 1.
  1269. */
  1270. protected int getNoncollatedCopies() {
  1271. return 1;
  1272. }
  1273. protected int getCollatedCopies() {
  1274. return 1;
  1275. }
  1276. private String[] printExecCmd(String printer, String options,
  1277. boolean noJobSheet,
  1278. String banner, int copies, String spoolFile) {
  1279. int PRINTER = 0x1;
  1280. int OPTIONS = 0x2;
  1281. int BANNER = 0x4;
  1282. int COPIES = 0x8;
  1283. int NOSHEET = 0x10;
  1284. int pFlags = 0;
  1285. String execCmd[];
  1286. int ncomps = 2; // minimum number of print args
  1287. int n = 0;
  1288. if (printer != null && !printer.equals("") && !printer.equals("lp")) {
  1289. pFlags |= PRINTER;
  1290. ncomps+=1;
  1291. }
  1292. if (options != null && !options.equals("")) {
  1293. pFlags |= OPTIONS;
  1294. ncomps+=1;
  1295. }
  1296. if (banner != null && !banner.equals("")) {
  1297. pFlags |= BANNER;
  1298. ncomps+=1;
  1299. }
  1300. if (copies > 1) {
  1301. pFlags |= COPIES;
  1302. ncomps+=1;
  1303. }
  1304. if (noJobSheet) {
  1305. pFlags |= NOSHEET;
  1306. ncomps+=1;
  1307. }
  1308. if (System.getProperty("os.name").equals("Linux")) {
  1309. execCmd = new String[ncomps];
  1310. execCmd[n++] = "/usr/bin/lpr";
  1311. if ((pFlags & PRINTER) != 0) {
  1312. execCmd[n++] = new String("-P" + printer);
  1313. }
  1314. if ((pFlags & BANNER) != 0) {
  1315. execCmd[n++] = new String("-J" + banner);
  1316. }
  1317. if ((pFlags & COPIES) != 0) {
  1318. execCmd[n++] = new String("-#" + new Integer(copies).toString());
  1319. }
  1320. if ((pFlags & NOSHEET) != 0) {
  1321. execCmd[n++] = new String("-h");
  1322. }
  1323. if ((pFlags & OPTIONS) != 0) {
  1324. execCmd[n++] = new String(options);
  1325. }
  1326. } else {
  1327. ncomps+=1; //add 1 arg for lp
  1328. execCmd = new String[ncomps];
  1329. execCmd[n++] = "/usr/bin/lp";
  1330. execCmd[n++] = "-c"; // make a copy of the spool file
  1331. if ((pFlags & PRINTER) != 0) {
  1332. execCmd[n++] = new String("-d" + printer);
  1333. }
  1334. if ((pFlags & BANNER) != 0) {
  1335. execCmd[n++] = new String("-t" + banner);
  1336. }
  1337. if ((pFlags & COPIES) != 0) {
  1338. execCmd[n++] = new String("-n" + new Integer(copies).toString());
  1339. }
  1340. if ((pFlags & NOSHEET) != 0) {
  1341. execCmd[n++] = new String("-o nobanner");
  1342. }
  1343. if ((pFlags & OPTIONS) != 0) {
  1344. execCmd[n++] = new String("-o" + options);
  1345. }
  1346. }
  1347. execCmd[n++] = spoolFile;
  1348. return execCmd;
  1349. }
  1350. private static int swapBGRtoRGB(byte[] image, int index, byte[] dest) {
  1351. int destIndex = 0;
  1352. while(index < image.length-2 && destIndex < dest.length-2) {
  1353. dest[destIndex++] = image[index+2];
  1354. dest[destIndex++] = image[index+1];
  1355. dest[destIndex++] = image[index+0];
  1356. index+=3;
  1357. }
  1358. return index;
  1359. }
  1360. /*
  1361. * Currently CharToByteConverter.getCharacterEncoding() return values are
  1362. * not fixed yet. These are used as the part of the key of
  1363. * psfont.propeties. When those name are fixed this routine can
  1364. * be erased.
  1365. */
  1366. private String makeCharsetName(String name, char[] chs) {
  1367. if (name.equals("Cp1252") || name.equals("ISO8859_1")) {
  1368. return "latin1";
  1369. } else if (name.equals("UTF8")) {
  1370. // same as latin 1 if all chars < 256
  1371. for (int i=0; i < chs.length; i++) {
  1372. if (chs[i] > 255) {
  1373. return name.toLowerCase();
  1374. }
  1375. }
  1376. return "latin1";
  1377. } else if (name.startsWith("ISO8859")) {
  1378. // same as latin 1 if all chars < 128
  1379. for (int i=0; i < chs.length; i++) {
  1380. if (chs[i] > 127) {
  1381. return name.toLowerCase();
  1382. }
  1383. }
  1384. return "latin1";
  1385. } else {
  1386. return name.toLowerCase();
  1387. }
  1388. }
  1389. private void prepDrawing() {
  1390. /* Pop gstates until we can set the needed clip
  1391. * and transform or until we are at the outer most
  1392. * gstate.
  1393. */
  1394. while (isOuterGState() == false
  1395. && (getGState().canSetClip(mLastClip) == false
  1396. || getGState().mTransform.equals(mLastTransform) == false)) {
  1397. grestore();
  1398. }
  1399. /* Set the color. This can push the color to the
  1400. * outer most gsave which is often a good thing.
  1401. */
  1402. getGState().emitPSColor(mLastColor);
  1403. /* We do not want to change the outermost
  1404. * transform or clip so if we are at the
  1405. * outer clip the generate a gsave.
  1406. */
  1407. if (isOuterGState()) {
  1408. gsave();
  1409. getGState().emitTransform(mLastTransform);
  1410. getGState().emitPSClip(mLastClip);
  1411. }
  1412. /* Set the font if we have been asked to. It is
  1413. * important that the font is set after the
  1414. * transform in order to get the font size
  1415. * correct.
  1416. */
  1417. // if (g != null) {
  1418. // getGState().emitPSFont(g, mLastFont);
  1419. // }
  1420. }
  1421. /**
  1422. * Return the GState that is currently on top
  1423. * of the GState stack. There should always be
  1424. * a GState on top of the stack. If there isn't
  1425. * then this method will throw an IndexOutOfBounds
  1426. * exception.
  1427. */
  1428. private GState getGState() {
  1429. int count = mGStateStack.size();
  1430. return (GState) mGStateStack.get(count - 1);
  1431. }
  1432. /**
  1433. * Emit a PostScript gsave command and add a
  1434. * new GState on to our stack which represents
  1435. * the printer's gstate stack.
  1436. */
  1437. private void gsave() {
  1438. GState oldGState = getGState();
  1439. mGStateStack.add(new GState(oldGState));
  1440. mPSStream.println(GSAVE_STR);
  1441. }
  1442. /**
  1443. * Emit a PostScript grestore command and remove
  1444. * a GState from our stack which represents the
  1445. * printer's gstate stack.
  1446. */
  1447. private void grestore() {
  1448. int count = mGStateStack.size();
  1449. mGStateStack.remove(count - 1);
  1450. mPSStream.println(GRESTORE_STR);
  1451. }
  1452. /**
  1453. * Return true if the current GState is the
  1454. * outermost GState and therefore should not
  1455. * be restored.
  1456. */
  1457. private boolean isOuterGState() {
  1458. return mGStateStack.size() == 1;
  1459. }
  1460. /**
  1461. * A stack of GStates is maintained to model the printer's
  1462. * gstate stack. Each GState holds information about
  1463. * the current graphics attributes.
  1464. */
  1465. private class GState{
  1466. Color mColor;
  1467. Shape mClip;
  1468. Font mFont;
  1469. AffineTransform mTransform;
  1470. GState() {
  1471. mColor = Color.black;
  1472. mClip = null;
  1473. mFont = null;
  1474. mTransform = new AffineTransform();
  1475. }
  1476. GState(GState copyGState) {
  1477. mColor = copyGState.mColor;
  1478. mClip = copyGState.mClip;
  1479. mFont = copyGState.mFont;
  1480. mTransform = copyGState.mTransform;
  1481. }
  1482. boolean canSetClip(Shape clip) {
  1483. return mClip == null || mClip.equals(clip);
  1484. }
  1485. void emitPSClip(Shape clip) {
  1486. if (clip != null
  1487. && (mClip == null || mClip.equals(clip) == false)) {
  1488. String saveFillOp = mFillOpStr;
  1489. String saveClipOp = mClipOpStr;
  1490. convertToPSPath(clip.getPathIterator(new AffineTransform()));
  1491. selectClipPath();
  1492. mClip = clip;
  1493. /* The clip is a shape and has reset the winding rule state */
  1494. mClipOpStr = saveFillOp;
  1495. mFillOpStr = saveFillOp;
  1496. }
  1497. }
  1498. void emitTransform(AffineTransform transform) {
  1499. if (transform != null && transform.equals(mTransform) == false) {
  1500. double[] matrix = new double[6];
  1501. transform.getMatrix(matrix);
  1502. mPSStream.println("[" + (float)matrix[0]
  1503. + " " + (float)matrix[1]
  1504. + " " + (float)matrix[2]
  1505. + " " + (float)matrix[3]
  1506. + " " + (float)matrix[4]
  1507. + " " + (float)matrix[5]
  1508. + "] concat");
  1509. mTransform = transform;
  1510. }
  1511. }
  1512. void emitPSColor(Color color) {
  1513. if (color != null && color.equals(mColor) == false) {
  1514. float[] rgb = color.getRGBColorComponents(null);
  1515. /* If the color is a gray value then use
  1516. * setgray.
  1517. */
  1518. if (rgb[0] == rgb[1] && rgb[1] == rgb[2]) {
  1519. mPSStream.println(rgb[0] + SETGRAY_STR);
  1520. /* It's not gray so use setrgbcolor.
  1521. */
  1522. } else {
  1523. mPSStream.println(rgb[0] + " "
  1524. + rgb[1] + " "
  1525. + rgb[2] + " "
  1526. + SETRGBCOLOR_STR);
  1527. }
  1528. mColor = color;
  1529. }
  1530. }
  1531. void emitPSFont(int psFontIndex, float fontSize) {
  1532. mPSStream.println(fontSize + " " +
  1533. psFontIndex + " " + SetFontName);
  1534. }
  1535. }
  1536. /**
  1537. * Given a Java2D <code>PathIterator</code> instance,
  1538. * this method translates that into a PostScript path..
  1539. */
  1540. void convertToPSPath(PathIterator pathIter) {
  1541. float[] segment = new float[6];
  1542. int segmentType;
  1543. /* Map the PathIterator's fill rule into the PostScript
  1544. * fill rule.
  1545. */
  1546. int fillRule;
  1547. if (pathIter.getWindingRule() == PathIterator.WIND_EVEN_ODD) {
  1548. fillRule = FILL_EVEN_ODD;
  1549. } else {
  1550. fillRule = FILL_WINDING;
  1551. }
  1552. beginPath();
  1553. setFillMode(fillRule);
  1554. while (pathIter.isDone() == false) {
  1555. segmentType = pathIter.currentSegment(segment);
  1556. switch (segmentType) {
  1557. case PathIterator.SEG_MOVETO:
  1558. moveTo(segment[0], segment[1]);
  1559. break;
  1560. case PathIterator.SEG_LINETO:
  1561. lineTo(segment[0], segment[1]);
  1562. break;
  1563. /* Convert the quad path to a bezier.
  1564. */
  1565. case PathIterator.SEG_QUADTO:
  1566. float lastX = getPenX();
  1567. float lastY = getPenY();
  1568. float c1x = lastX + (segment[0] - lastX) * 2 / 3;
  1569. float c1y = lastY + (segment[1] - lastY) * 2 / 3;
  1570. float c2x = segment[2] - (segment[2] - segment[0]) * 2/ 3;
  1571. float c2y = segment[3] - (segment[3] - segment[1]) * 2/ 3;
  1572. bezierTo(c1x, c1y,
  1573. c2x, c2y,
  1574. segment[2], segment[3]);
  1575. break;
  1576. case PathIterator.SEG_CUBICTO:
  1577. bezierTo(segment[0], segment[1],
  1578. segment[2], segment[3],
  1579. segment[4], segment[5]);
  1580. break;
  1581. case PathIterator.SEG_CLOSE:
  1582. closeSubpath();
  1583. break;
  1584. }
  1585. pathIter.next();
  1586. }
  1587. }
  1588. /*
  1589. * Fill the path defined by <code>pathIter</code>
  1590. * with the specified color.
  1591. * The path is provided in current user space.
  1592. */
  1593. protected void deviceFill(PathIterator pathIter, Color color,
  1594. AffineTransform tx, Shape clip) {
  1595. setTransform(tx);
  1596. setClip(clip);
  1597. setColor(color);
  1598. convertToPSPath(pathIter);
  1599. /* Specify the path to fill as the clip, this ensures that only
  1600. * pixels which are inside the path will be filled, which is
  1601. * what the Java 2D APIs specify
  1602. */
  1603. mPSStream.println(GSAVE_STR);
  1604. selectClipPath();
  1605. fillPath();
  1606. mPSStream.println(GRESTORE_STR + " " + NEWPATH_STR);
  1607. }
  1608. /*
  1609. * Run length encode byte array in a form suitable for decoding
  1610. * by the PS Level 2 filter RunLengthDecode.
  1611. * Array data to encode is inArr. Encoded data is written to outArr
  1612. * outArr must be long enough to hold the encoded data but this
  1613. * can't be known ahead of time.
  1614. * A safe assumption is to use double the length of the input array.
  1615. * This is then copied into a new array of the correct length which
  1616. * is returned.
  1617. * Algorithm:
  1618. * Encoding is a lead byte followed by data bytes.
  1619. * Lead byte of 0->127 indicates leadByte + 1 distinct bytes follow
  1620. * Lead byte of 129->255 indicates 257 - leadByte is the number of times
  1621. * the following byte is repeated in the source.
  1622. * 128 is a special lead byte indicating end of data (EOD) and is
  1623. * written as the final byte of the returned encoded data.
  1624. */
  1625. private byte[] rlEncode(byte[] inArr) {
  1626. int inIndex = 0;
  1627. int outIndex = 0;
  1628. int startIndex = 0;
  1629. int runLen = 0;
  1630. byte[] outArr = new byte[(inArr.length * 2) +2];
  1631. while (inIndex < inArr.length) {
  1632. if (runLen == 0) {
  1633. startIndex = inIndex++;
  1634. runLen=1;
  1635. }
  1636. while (runLen < 128 && inIndex < inArr.length &&
  1637. inArr[inIndex] == inArr[startIndex]) {
  1638. runLen++; // count run of same value
  1639. inIndex++;
  1640. }
  1641. if (runLen > 1) {
  1642. outArr[outIndex++] = (byte)(257 - runLen);
  1643. outArr[outIndex++] = inArr[startIndex];
  1644. runLen = 0;
  1645. continue; // back to top of while loop.
  1646. }
  1647. // if reach here have a run of different values, or at the end.
  1648. while (runLen < 128 && inIndex < inArr.length &&
  1649. inArr[inIndex] != inArr[inIndex-1]) {
  1650. runLen++; // count run of different values
  1651. inIndex++;
  1652. }
  1653. outArr[outIndex++] = (byte)(runLen - 1);
  1654. for (int i = startIndex; i < startIndex+runLen; i++) {
  1655. outArr[outIndex++] = inArr[i];
  1656. }
  1657. runLen = 0;
  1658. }
  1659. outArr[outIndex++] = (byte)128;
  1660. byte[] encodedData = new byte[outIndex];
  1661. System.arraycopy(outArr, 0, encodedData, 0, outIndex);
  1662. return encodedData;
  1663. }
  1664. /* written acc. to Adobe Spec. "Filtered Files: ASCIIEncode Filter",
  1665. * "PS Language Reference Manual, 2nd edition: Section 3.13"
  1666. */
  1667. private byte[] ascii85Encode(byte[] inArr) {
  1668. byte[] outArr = new byte[((inArr.length+4) * 5 / 4) + 2];
  1669. long p1 = 85;
  1670. long p2 = p1*p1;
  1671. long p3 = p1*p2;
  1672. long p4 = p1*p3;
  1673. byte pling = '!';
  1674. int i = 0;
  1675. int olen = 0;
  1676. long val, rem;
  1677. while (i+3 < inArr.length) {
  1678. val = ((long)((inArr[i++]&0xff))<<24) +
  1679. ((long)((inArr[i++]&0xff))<<16) +
  1680. ((long)((inArr[i++]&0xff))<< 8) +
  1681. ((long)(inArr[i++]&0xff));
  1682. if (val == 0) {
  1683. outArr[olen++] = 'z';
  1684. } else {
  1685. rem = val;
  1686. outArr[olen++] = (byte)(rem / p4 + pling); rem = rem % p4;
  1687. outArr[olen++] = (byte)(rem / p3 + pling); rem = rem % p3;
  1688. outArr[olen++] = (byte)(rem / p2 + pling); rem = rem % p2;
  1689. outArr[olen++] = (byte)(rem / p1 + pling); rem = rem % p1;
  1690. outArr[olen++] = (byte)(rem + pling);
  1691. }
  1692. }
  1693. // input not a multiple of 4 bytes, write partial output.
  1694. if (i < inArr.length) {
  1695. int n = inArr.length - i; // n bytes remain to be written
  1696. val = 0;
  1697. while (i < inArr.length) {
  1698. val = (val << 8) + (inArr[i++]&0xff);
  1699. }
  1700. int append = 4 - n;
  1701. while (append-- > 0) {
  1702. val = val << 8;
  1703. }
  1704. byte []c = new byte[5];
  1705. rem = val;
  1706. c[0] = (byte)(rem / p4 + pling); rem = rem % p4;
  1707. c[1] = (byte)(rem / p3 + pling); rem = rem % p3;
  1708. c[2] = (byte)(rem / p2 + pling); rem = rem % p2;
  1709. c[3] = (byte)(rem / p1 + pling); rem = rem % p1;
  1710. c[4] = (byte)(rem + pling);
  1711. for (int b = 0; b < n+1 ; b++) {
  1712. outArr[olen++] = c[b];
  1713. }
  1714. }
  1715. // write EOD marker.
  1716. outArr[olen++]='~'; outArr[olen++]='>';
  1717. /* The original intention was to insert a newline after every 78 bytes.
  1718. * This was mainly intended for legibility but I decided against this
  1719. * partially because of the (small) amount of extra space, and
  1720. * partially because for line breaks either would have to hardwire
  1721. * ascii 10 (newline) or calculate space in bytes to allocate for
  1722. * the platform's newline byte sequence. Also need to be careful
  1723. * about where its inserted:
  1724. * Ascii 85 decoder ignores white space except for one special case:
  1725. * you must ensure you do not split the EOD marker across lines.
  1726. */
  1727. byte[] retArr = new byte[olen];
  1728. System.arraycopy(outArr, 0, retArr, 0, olen);
  1729. return retArr;
  1730. }
  1731. /**
  1732. * PluginPrinter generates EPSF wrapped with a header and trailer
  1733. * comment. This conforms to the new requirements of Mozilla 1.7
  1734. * and FireFox 1.5 and later. Earlier versions of these browsers
  1735. * did not support plugin printing in the general sense (not just Java).
  1736. * A notable limitation of these browsers is that they handle plugins
  1737. * which would span page boundaries by scaling plugin content to fit on a
  1738. * single page. This means white space is left at the bottom of the
  1739. * previous page and its impossible to print these cases as they appear on
  1740. * the web page. This is contrast to how the same browsers behave on
  1741. * Windows where it renders as on-screen.
  1742. * Cases where the content fits on a single page do work fine, and they
  1743. * are the majority of cases.
  1744. * The scaling that the browser specifies to make the plugin content fit
  1745. * when it is larger than a single page can hold is non-uniform. It
  1746. * scales the axis in which the content is too large just enough to
  1747. * ensure it fits. For content which is extremely long this could lead
  1748. * to noticeable distortion. However that is probably rare enough that
  1749. * its not worth compensating for that here, but we can revisit that if
  1750. * needed, and compensate by making the scale for the other axis the
  1751. * same.
  1752. */
  1753. public static class PluginPrinter implements Printable {
  1754. private EPSPrinter epsPrinter;
  1755. private Component applet;
  1756. private PrintStream stream;
  1757. private String epsTitle;
  1758. private int bx, by, bw, bh;
  1759. private int width, height;
  1760. /**
  1761. * This is called from the Java Plug-in to print an Applet's
  1762. * contents as EPS to a postscript stream provided by the browser.
  1763. * @param applet the applet component to print.
  1764. * @param stream the print stream provided by the plug-in
  1765. * @param x the x location of the applet panel in the browser window
  1766. * @param y the y location of the applet panel in the browser window
  1767. * @param w the width of the applet panel in the browser window
  1768. * @param h the width of the applet panel in the browser window
  1769. */
  1770. public PluginPrinter(Component applet,
  1771. PrintStream stream,
  1772. int x, int y, int w, int h) {
  1773. this.applet = applet;
  1774. this.epsTitle = "Java Plugin Applet";
  1775. this.stream = stream;
  1776. bx = x;
  1777. by = y;
  1778. bw = w;
  1779. bh = h;
  1780. width = applet.size().width;
  1781. height = applet.size().height;
  1782. epsPrinter = new EPSPrinter(this, epsTitle, stream,
  1783. 0, 0, width, height);
  1784. }
  1785. public void printPluginPSHeader() {
  1786. stream.println("%%BeginDocument: JavaPluginApplet");
  1787. }
  1788. public void printPluginApplet() {
  1789. try {
  1790. epsPrinter.print();
  1791. } catch (PrinterException e) {
  1792. }
  1793. }
  1794. public void printPluginPSTrailer() {
  1795. stream.println("%%EndDocument: JavaPluginApplet");
  1796. stream.flush();
  1797. }
  1798. public void printAll() {
  1799. printPluginPSHeader();
  1800. printPluginApplet();
  1801. printPluginPSTrailer();
  1802. }
  1803. public int print(Graphics g, PageFormat pf, int pgIndex) {
  1804. if (pgIndex > 0) {
  1805. return Printable.NO_SUCH_PAGE;
  1806. } else {
  1807. // "aware" client code can detect that its been passed a
  1808. // PrinterGraphics and could theoretically print
  1809. // differently. I think this is more likely useful than
  1810. // a problem.
  1811. applet.printAll(g);
  1812. return Printable.PAGE_EXISTS;
  1813. }
  1814. }
  1815. }
  1816. /*
  1817. * This class can take an application-client supplied printable object
  1818. * and send the result to a stream.
  1819. * The application does not need to send any postscript to this stream
  1820. * unless it needs to specify a translation etc.
  1821. * It assumes that its importing application obeys all the conventions
  1822. * for importation of EPS. See Appendix H - Encapsulated Postscript File
  1823. * Format - of the Adobe Postscript Language Reference Manual, 2nd edition.
  1824. * This class could be used as the basis for exposing the ability to
  1825. * generate EPSF from 2D graphics as a StreamPrintService.
  1826. * In that case a MediaPrintableArea attribute could be used to
  1827. * communicate the bounding box.
  1828. */
  1829. public static class EPSPrinter implements Pageable {
  1830. private PageFormat pf;
  1831. private PSPrinterJob job;
  1832. private int llx, lly, urx, ury;
  1833. private Printable printable;
  1834. private PrintStream stream;
  1835. private String epsTitle;
  1836. public EPSPrinter(Printable printable, String title,
  1837. PrintStream stream,
  1838. int x, int y, int wid, int hgt) {
  1839. this.printable = printable;
  1840. this.epsTitle = title;
  1841. this.stream = stream;
  1842. llx = x;
  1843. lly = y;
  1844. urx = llx+wid;
  1845. ury = lly+hgt;
  1846. // construct a PageFormat with zero margins representing the
  1847. // exact bounds of the applet. ie construct a theoretical
  1848. // paper which happens to exactly match applet panel size.
  1849. Paper p = new Paper();
  1850. p.setSize((double)wid, (double)hgt);
  1851. p.setImageableArea(0.0,0.0, (double)wid, (double)hgt);
  1852. pf = new PageFormat();
  1853. pf.setPaper(p);
  1854. }
  1855. public void print() throws PrinterException {
  1856. stream.println("%!PS-Adobe-3.0 EPSF-3.0");
  1857. stream.println("%%BoundingBox: " +
  1858. llx + " " + lly + " " + urx + " " + ury);
  1859. stream.println("%%Title: " + epsTitle);
  1860. stream.println("%%Creator: Java Printing");
  1861. stream.println("%%CreationDate: " + new java.util.Date());
  1862. stream.println("%%EndComments");
  1863. stream.println("/pluginSave save def");
  1864. stream.println("mark"); // for restoring stack state on return
  1865. job = new PSPrinterJob();
  1866. job.epsPrinter = this; // modifies the behaviour of PSPrinterJob
  1867. job.mPSStream = stream;
  1868. job.mDestType = RasterPrinterJob.STREAM; // prevents closure
  1869. job.startDoc();
  1870. try {
  1871. job.printPage(this, 0);
  1872. } catch (Throwable t) {
  1873. if (t instanceof PrinterException) {
  1874. throw (PrinterException)t;
  1875. } else {
  1876. throw new PrinterException(t.toString());
  1877. }
  1878. } finally {
  1879. stream.println("cleartomark"); // restore stack state
  1880. stream.println("pluginSave restore");
  1881. job.endDoc();
  1882. }
  1883. stream.flush();
  1884. }
  1885. public int getNumberOfPages() {
  1886. return 1;
  1887. }
  1888. public PageFormat getPageFormat(int pgIndex) {
  1889. if (pgIndex > 0) {
  1890. throw new IndexOutOfBoundsException("pgIndex");
  1891. } else {
  1892. return pf;
  1893. }
  1894. }
  1895. public Printable getPrintable(int pgIndex) {
  1896. if (pgIndex > 0) {
  1897. throw new IndexOutOfBoundsException("pgIndex");
  1898. } else {
  1899. return printable;
  1900. }
  1901. }
  1902. }
  1903. }