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