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