PageRenderTime 62ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 0ms

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

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