PageRenderTime 31ms CodeModel.GetById 25ms RepoModel.GetById 1ms app.codeStats 0ms

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

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