PageRenderTime 31ms CodeModel.GetById 33ms RepoModel.GetById 0ms app.codeStats 0ms

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

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