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