Debian Codegraph @

freehep-graphicsio-ps/src/main/java/org/freehep/graphicsio/ps/AbstractPSGraphics2D.java

raw
1 // Copyright 2007 FreeHEP
2 package org.freehep.graphicsio.ps;
3
4 import java.awt.BasicStroke;
5 import java.awt.Color;
6 import java.awt.Component;
7 import java.awt.Dimension;
8 import java.awt.Font;
9 import java.awt.GradientPaint;
10 import java.awt.Graphics;
11 import java.awt.GraphicsConfiguration;
12 import java.awt.Insets;
13 import java.awt.Paint;
14 import java.awt.Rectangle;
15 import java.awt.Shape;
16 import java.awt.TexturePaint;
17 import java.awt.geom.AffineTransform;
18 import java.awt.geom.Point2D;
19 import java.awt.geom.Rectangle2D;
20 import java.awt.image.BufferedImage;
21 import java.awt.image.RenderedImage;
22 import java.io.BufferedOutputStream;
23 import java.io.IOException;
24 import java.io.OutputStream;
25 import java.io.PrintStream;
26 import java.text.DateFormat;
27 import java.text.AttributedCharacterIterator.Attribute;
28 import java.util.Date;
29 import java.util.Map;
30 import java.util.Properties;
31
32 import org.freehep.graphics2d.TagString;
33 import org.freehep.graphics2d.font.FontUtilities;
34 import org.freehep.graphicsbase.util.ScientificFormat;
35 import org.freehep.graphicsbase.util.UserProperties;
36 import org.freehep.graphicsbase.util.images.ImageUtilities;
37 import org.freehep.graphicsio.AbstractVectorGraphicsIO;
38 import org.freehep.graphicsio.FontConstants;
39 import org.freehep.graphicsio.ImageConstants;
40 import org.freehep.graphicsio.ImageGraphics2D;
41 import org.freehep.graphicsio.InfoConstants;
42 import org.freehep.graphicsio.PageConstants;
43
44 /**
45 *
46 * @author duns
47 * @version $Id: freehep-graphicsio-ps/src/main/java/org/freehep/graphicsio/ps/AbstractPSGraphics2D.java bed5e3a39f35 2007/09/10 18:13:00 duns $
48 */
49 public abstract class AbstractPSGraphics2D extends AbstractVectorGraphicsIO implements FontUtilities.ShowString {
50 private static final String rootKey = PSGraphics2D.class.getName();
51
52 public static final String BACKGROUND = rootKey + "."
53 + PageConstants.BACKGROUND;
54
55 public static final String BACKGROUND_COLOR = rootKey + "."
56 + PageConstants.BACKGROUND_COLOR;
57
58 /**
59 * Property name for setting the size of the pages output by this {@code AbstractPSGraphics2D}.
60 * <p>
61 * To set a pre-defined page size, set this property to one of the page size constants defined
62 * in {@link PageConstants} - for instance, {@linkplain PageConstants#A4},
63 * {@linkplain PageConstants#LETTER}.
64 * <p>
65 * To set a custom page size, set this property to the value {@link CUSTOM_PAGE_SIZE}. Then,
66 * set the {@link CUSTOM_PAGE_SIZE} property to a {@link Dimension} object.
67 * @see UserProperties
68 */
69 public static final String PAGE_SIZE = rootKey + "."
70 + PageConstants.PAGE_SIZE;
71
72 /**
73 * Property name (and value!) for setting a custom page size.
74 * <p>
75 * If the {@link PAGE_SIZE} property is set to THIS VALUE, then the properties are consulted
76 * for the value of THIS KEY. The value of this key should be a {@link Dimension} object,
77 * in the "user coordinates" of Java2D.
78 *
79 */
80 public static final String CUSTOM_PAGE_SIZE = rootKey + "."
81 + PageConstants.CUSTOM_PAGE_SIZE;
82
83 /**
84 * Set this to an {@link Insets} object to set the page margins.
85 */
86 public static final String PAGE_MARGINS = rootKey + "."
87 + PageConstants.PAGE_MARGINS;
88
89 public static final String ORIENTATION = rootKey + "."
90 + PageConstants.ORIENTATION;
91
92 public static final String FIT_TO_PAGE = rootKey + "."
93 + PageConstants.FIT_TO_PAGE;
94
95 public static final String EMBED_FONTS = rootKey + "."
96 + FontConstants.EMBED_FONTS;
97
98 public static final String EMBED_FONTS_AS = rootKey + "."
99 + FontConstants.EMBED_FONTS_AS;
100
101 public static final String FOR = rootKey + "." + InfoConstants.FOR;
102
103 public static final String TITLE = rootKey + "." + InfoConstants.TITLE;
104
105 public static final String PREVIEW = rootKey + ".Preview";
106
107 public static final String PREVIEW_BITS = rootKey + ".PreviewBits";
108
109 public static final String WRITE_IMAGES_AS = rootKey + "."
110 + ImageConstants.WRITE_IMAGES_AS;
111
112 private static final UserProperties defaultProperties = new UserProperties();
113 static {
114 defaultProperties.setProperty(BACKGROUND, false);
115 defaultProperties.setProperty(BACKGROUND_COLOR, Color.GRAY);
116
117 defaultProperties.setProperty(PAGE_SIZE, PageConstants.INTERNATIONAL);
118 defaultProperties.setProperty(PAGE_MARGINS, PageConstants
119 .getMargins(PageConstants.SMALL));
120 defaultProperties.setProperty(ORIENTATION, PageConstants.PORTRAIT);
121 defaultProperties.setProperty(FIT_TO_PAGE, true);
122 defaultProperties.setProperty(EMBED_FONTS, false);
123 defaultProperties.setProperty(TEXT_AS_SHAPES, false);
124 defaultProperties.setProperty(EMBED_FONTS_AS,
125 FontConstants.EMBED_FONTS_TYPE3);
126
127 defaultProperties.setProperty(FOR, "");
128 defaultProperties.setProperty(TITLE, "");
129
130 defaultProperties.setProperty(PREVIEW, false);
131 defaultProperties.setProperty(PREVIEW_BITS, 8);
132
133 defaultProperties.setProperty(WRITE_IMAGES_AS, ImageConstants.SMALLEST);
134
135 defaultProperties.setProperty(CLIP, true);
136 defaultProperties.setProperty(TEXT_AS_SHAPES, true);
137 }
138
139 public static Properties getDefaultProperties() {
140 return defaultProperties;
141 }
142
143 public static final String version = "$Revision: 12753 $";
144
145 public static final int LEVEL_2 = 2;
146
147 public static final int LEVEL_3 = 3;
148
149 // remember which fonts are used
150 private PSFontTable fontTable;
151
152 // The private writer used for this file.
153 protected OutputStream ros;
154
155 protected PrintStream os;
156
157 private int postscriptLevel = LEVEL_3;
158
159 public AbstractPSGraphics2D(Dimension size, boolean doRestoreOnDispose) {
160 super(size, doRestoreOnDispose);
161 }
162
163 public AbstractPSGraphics2D(Component component, boolean doRestoreOnDispose) {
164 super(component, doRestoreOnDispose);
165 }
166
167 /**
168 * This protected method is used by the create() methods to create a clone
169 * of the given graphics object.
170 *
171 * @param graphics Parent graphics to take attributes from
172 * @param doRestoreOnDispose if true writeGraphicsRestore() is called on dispose()
173 */
174 protected AbstractPSGraphics2D(AbstractPSGraphics2D graphics, boolean doRestoreOnDispose) {
175
176 super(graphics, doRestoreOnDispose);
177
178 // Now initialize the new object.
179 ros = graphics.ros;
180 os = graphics.os;
181 fontTable = graphics.fontTable;
182 }
183
184 protected void init(OutputStream os) {
185 ros = new BufferedOutputStream(os);
186 initProperties(defaultProperties);
187 fontTable = new PSFontTable(ros, getFontRenderContext());
188 }
189
190 /**
191 * Set the clipping enabled flag. This will affect all output operations
192 * after this call completes.
193 *
194 * @param enabled true enables clipping
195 */
196 public static void setClipEnabled(boolean enabled) {
197 defaultProperties.setProperty(CLIP, enabled);
198 }
199
200 /**
201 * Write out the header of this EPS file.
202 */
203 public void writeHeader() throws IOException {
204 String producer = getClass().getName();
205 if (!isDeviceIndependent()) {
206 producer += " " + version.substring(1, version.length() - 1);
207 }
208 os.println("%%Creator: " + getCreator());
209 os.println("%%Producer: " + producer);
210 os.println("%%For: " + getProperty(FOR));
211 os.println("%%Title: " + getProperty(TITLE));
212 if (!isDeviceIndependent()) {
213 os.println("%%CreationDate: "
214 + DateFormat.getDateTimeInstance(DateFormat.FULL,
215 DateFormat.FULL).format(new Date()));
216 }
217 os.println("%%LanguageLevel: " + postscriptLevel);
218 os.println("%%EndComments");
219
220 // write preview if possible
221 if (isProperty(PREVIEW) && (getComponent() != null)) {
222 Rectangle size = getComponent().getBounds();
223 BufferedImage image = new BufferedImage(size.width, size.height,
224 BufferedImage.TYPE_INT_ARGB);
225 Graphics imageGraphics = image.getGraphics();
226 getComponent().print(imageGraphics);
227
228 EPSIEncoder encoder = new EPSIEncoder(image, ros,
229 getPropertyInt(PREVIEW_BITS), getProperty(ORIENTATION)
230 .equals(PageConstants.PORTRAIT));
231 encoder.encode();
232 }
233
234 // The prolog is kept in a file PSProlog.txt in the same area
235 // as this class definition. It is simply copied into the
236 // output file.
237 os.println("%%BeginProlog");
238 copyResourceTo(this, "PSProlog.txt", os);
239 os.println("%%EndProlog");
240 os.println();
241 }
242
243 public void writeBackground() throws IOException {
244 // since PS is non-transparent, write current background
245 if (isProperty(BACKGROUND)) {
246 setBackground(getPropertyColor(BACKGROUND_COLOR));
247 clearRect(0.0, 0.0, getSize().width, getSize().height);
248 } else {
249 setBackground(getComponent() != null ? getComponent()
250 .getBackground() : Color.WHITE);
251 clearRect(0.0, 0.0, getSize().width, getSize().height);
252 }
253 }
254
255 public void writeTrailer() throws IOException {
256 os.println();
257 os.println("%%Trailer");
258 }
259
260 public void closeStream() throws IOException {
261 ros.close();
262 os.close();
263 }
264
265
266 /**
267 * Reads the PAGE_SIZE Property. If A4 .. A0 is found,
268 * PageConstants will determine the size. If CUSTOM_PAGE_SIZE
269 * is found, CUSTOM_PAGE_SIZE is used as a Property key for
270 * a dimension object.
271 *
272 * @return Size of page
273 */
274 protected Dimension getPageSize() {
275 // A4 ... A0 or PageConstants.CUSTOM_PAGE_SIZE expected
276 // if PageConstants.CUSTOM_PAGE_SIZE is found,
277 // PageConstants.CUSTOM_PAGE_SIZE is used as Key too
278 String pageSizeProperty = getProperty(PAGE_SIZE);
279
280 // determine page size
281 Dimension result = CUSTOM_PAGE_SIZE.equals(pageSizeProperty) ?
282 getPropertyDimension(CUSTOM_PAGE_SIZE) :
283 PageConstants.getSize(getProperty(PAGE_SIZE));
284
285 // set a default value
286 if (result == null) {
287 result = PageConstants.getSize(PageConstants.A4);
288 }
289
290 return result;
291 }
292
293 protected void openPage(Dimension size, String title, Component component) {
294 if (size == null) {
295 size = component.getSize();
296 }
297 resetClip(new Rectangle(0, 0, size.width, size.height));
298
299 // Our PS Header has internal page orientation mode, all sizes given in
300 // portrait
301 Dimension pageSize = getPageSize();
302 Insets margins = getPropertyInsets(PAGE_MARGINS);
303
304 os.println("save");
305 os.println("procDict begin");
306 os.println("printColorMap begin");
307 os.println(pageSize.width + " " + pageSize.height + " setpagesize");
308 os.println(margins.left + " " + margins.bottom + " " + margins.top
309 + " " + margins.right + " setmargins");
310 os.println("0 0 setorigin");
311 os.println(size.width + " " + size.height + " setsize");
312 os.println(isProperty(FIT_TO_PAGE) ? "fittopage" : "naturalsize");
313 os.println(getProperty(ORIENTATION).equals(PageConstants.PORTRAIT) ? "portrait" : "landscape");
314 os.println("imagescale");
315 os.println("cliptobounds");
316 os.println("setbasematrix");
317 os.println("/Helvetica 10 sf");
318 os.println("defaultGraphicsState");
319 }
320
321 public void setHeader(Font font, TagString left, TagString center,
322 TagString right, int underlineThickness) {
323 }
324
325 public void setFooter(Font font, TagString left, TagString center,
326 TagString right, int underlineThickness) {
327 }
328
329 /**
330 * Embed a gsave in the PostScript file.
331 */
332 protected void writeGraphicsSave() throws IOException {
333 os.println("q");
334 }
335
336 /**
337 * Embed a grestore in the PostScript file.
338 */
339 protected void writeGraphicsRestore() throws IOException {
340 os.println("Q");
341 }
342
343 public void draw(Shape shape) {
344 try {
345 if (getStroke() instanceof BasicStroke) {
346 writePath(shape);
347 os.println("S");
348 } else {
349 boolean eofill = writePath(getStroke().createStrokedShape(shape));
350 os.println(((eofill) ? "f*" : "f"));
351 }
352 } catch (IOException e) {
353 handleException(e);
354 }
355 }
356
357 public void fill(Shape shape) {
358 try {
359 if (getPaint() instanceof Color || (getPaint() instanceof GradientPaint && postscriptLevel >= LEVEL_3)) {
360 boolean eofill = writePath(shape);
361 os.println(((eofill) ? "f*" : "f"));
362 } else {
363 // setting the color seems to be needed by PS
364 writePaint(Color.black);
365 fill(shape, getPaint());
366 }
367 } catch (IOException e) {
368 handleException(e);
369 }
370 }
371
372 public void fillAndDraw(Shape shape, Color fillColor) {
373 try {
374 if (getPaint() instanceof Color || (getPaint() instanceof GradientPaint && postscriptLevel >= LEVEL_3)) {
375 setPSColor(fillColor, true);
376 boolean eofill = writePath(shape);
377 os.println(((eofill) ? "B*" : "B"));
378 } else {
379 // setting the color seems to be needed by PS
380 writePaint(Color.black);
381 fill(shape, getPaint());
382 }
383 } catch (IOException e) {
384 handleException(e);
385 }
386 }
387
388 public void copyArea(int x, int y, int width, int height, int dx, int dy) {
389 writeWarning(getClass()
390 + ": copyArea(int, int, int, int, int, int) not implemented.");
391 }
392
393 protected void writeImage(RenderedImage image, AffineTransform xform,
394 Color bkg) throws IOException {
395
396 // save complete gstate, not only color space
397 writeGraphicsSave();
398
399 // FIXME FVG-31
400
401 if (bkg == null) {
402 bkg = getBackground();
403 }
404 image = ImageUtilities.createRenderedImage(image, bkg);
405
406 // Write out the PostScript code to start an image
407 // definition.
408 int imageWidth = image.getWidth();
409 int imageHeight = image.getHeight();
410
411 AffineTransform imageTransform = new AffineTransform(
412 imageWidth, 0.0, 0.0, imageHeight, 0.0, 0.0);
413 xform.concatenate(imageTransform);
414
415 writeTransform(xform);
416 os.println("<<");
417 os.println("/ImageType 1");
418 os.println("/Width " + imageWidth + " /Height " + imageHeight);
419 os.println("/BitsPerComponent 8");
420 os.println("/Decode [0 1 0 1 0 1]");
421 os.println("/ImageMatrix [" + imageWidth + " 0 0 " + imageHeight
422 + " 0 0]");
423
424 // read image format
425 String writeAs = getProperty(WRITE_IMAGES_AS);
426
427 // used for creating
428 // /DataSource currentfile /ASCII85Decode filter /"encode"Decode filter
429 // >> image "imageBytes"
430 String encode;
431 byte[] imageBytes;
432
433 // write as RAW with ZIP compression
434 if (ImageConstants.ZLIB.equalsIgnoreCase(writeAs)) {
435 encode = ImageConstants.ENCODING_FLATE;
436 imageBytes = ImageGraphics2D.toByteArray(
437 image,
438 ImageConstants.RAW,
439 ImageConstants.ENCODING_FLATE_ASCII85,
440 ImageGraphics2D.getRAWProperties(bkg, ImageConstants.COLOR_MODEL_RGB));
441 }
442
443 // write as JPEG
444 else if (ImageConstants.JPG.equalsIgnoreCase(writeAs)) {
445 encode = ImageConstants.ENCODING_DCT;
446 imageBytes = ImageGraphics2D.toByteArray(
447 image,
448 ImageConstants.JPG,
449 ImageConstants.ENCODING_ASCII85,
450 null);
451 }
452
453 // write SMALLEST (JPEG or RAW)
454 else {
455 // zip-compressed raw image
456 byte[] flateBytes = ImageGraphics2D.toByteArray(
457 image,
458 ImageConstants.RAW,
459 ImageConstants.ENCODING_FLATE_ASCII85,
460 ImageGraphics2D.getRAWProperties(bkg, ImageConstants.COLOR_MODEL_RGB));
461
462 // jpeg image DCT encoded
463 byte[] jpgBytes = ImageGraphics2D.toByteArray(
464 image,
465 ImageConstants.JPG,
466 ImageConstants.ENCODING_ASCII85,
467 null);
468
469 // define encoding and imagebytes
470 if (jpgBytes.length < 0.5 * flateBytes.length) {
471 encode = ImageConstants.ENCODING_DCT;
472 imageBytes = jpgBytes;
473 } else {
474 encode = ImageConstants.ENCODING_FLATE;
475 imageBytes = flateBytes;
476 }
477 }
478
479 os.println("/DataSource currentfile " + "/ASCII85Decode filter " + "/"
480 + encode + "Decode filter ");
481 os.println(">> image");
482
483 os.write(imageBytes);
484
485 os.println("");
486
487 writeGraphicsRestore();
488 }
489
490 protected void writeString(String str, double x, double y)
491 throws IOException {
492 showCharacterCodes(str, x, y);
493 }
494
495 protected void writeTransform(AffineTransform tx) throws IOException {
496 os.println("[ " + fixedPrecision(tx.getScaleX()) + " "
497 + fixedPrecision(tx.getShearY()) + " "
498 + fixedPrecision(tx.getShearX()) + " "
499 + fixedPrecision(tx.getScaleY()) + " "
500 + fixedPrecision(tx.getTranslateX()) + " "
501 + fixedPrecision(tx.getTranslateY()) + " ] concat");
502 }
503
504 protected void writeSetTransform(AffineTransform tx) throws IOException {
505 os.println("[ " + fixedPrecision(tx.getScaleX()) + " "
506 + fixedPrecision(tx.getShearY()) + " "
507 + fixedPrecision(tx.getShearX()) + " "
508 + fixedPrecision(tx.getScaleY()) + " "
509 + fixedPrecision(tx.getTranslateX()) + " "
510 + fixedPrecision(tx.getTranslateY())
511 + " ] defaultmatrix matrix concatmatrix setmatrix");
512 }
513
514 protected void writeClip(Shape s) throws IOException {
515 if (s == null || !isProperty(CLIP)) {
516 return;
517 }
518 if (s instanceof Rectangle) {
519 os.println(
520 ((Rectangle)s).x+" "+
521 ((Rectangle)s).y+" "+
522 ((Rectangle)s).width+" "+
523 ((Rectangle)s).height+" rc");
524 } else if (s instanceof Rectangle2D) {
525 os.println(
526 fixedPrecision(((Rectangle2D)s).getX())+" "+
527 fixedPrecision(((Rectangle2D)s).getY())+" "+
528 fixedPrecision(((Rectangle2D)s).getWidth())+" "+
529 fixedPrecision(((Rectangle2D)s).getHeight())+" rc");
530 } else {
531 boolean eofill = writePath(s);
532 os.println(((eofill) ? "W*" : "W"));
533 }
534 }
535
536 protected void writeSetClip(Shape s) throws IOException {
537 os.println("cliprestore");
538 writeClip(s);
539 }
540
541 /**
542 * Write the path of the current shape to the output file. Return a boolean
543 * indicating whether or not the even-odd rule for filling should be used.
544 *
545 * @return path by PSPathConstructor
546 * @param s Shape to convert
547 * @throws java.io.IOException thrown by created path
548 */
549 private boolean writePath(Shape s) throws IOException {
550 os.println("newpath");
551 PSPathConstructor path = new PSPathConstructor(os, true, false);
552 return path.addPath(s);
553 }
554
555 protected void writeWidth(float width) throws IOException {
556 os.println(fixedPrecision(width) + " w");
557 }
558
559 protected void writeCap(int cap) throws IOException {
560 switch (cap) {
561 default:
562 case BasicStroke.CAP_BUTT:
563 os.println("0 J");
564 break;
565 case BasicStroke.CAP_ROUND:
566 os.println("1 J");
567 break;
568 case BasicStroke.CAP_SQUARE:
569 os.println("2 J");
570 break;
571 }
572 }
573
574 protected void writeJoin(int join) throws IOException {
575 switch (join) {
576 default:
577 case BasicStroke.JOIN_MITER:
578 os.println("0 j");
579 break;
580 case BasicStroke.JOIN_ROUND:
581 os.println("1 j");
582 break;
583 case BasicStroke.JOIN_BEVEL:
584 os.println("2 j");
585 break;
586 }
587 }
588
589 protected void writeMiterLimit(float limit) throws IOException {
590 os.println(fixedPrecision(limit) + " M");
591 }
592
593 protected void writeDash(float[] dash, float phase) throws IOException {
594 os.print("[ ");
595 for (int i = 0; i < dash.length; i++) {
596 os.print(fixedPrecision(dash[i]) + " ");
597 }
598 os.println("] " + fixedPrecision(phase) + " d");
599 }
600
601 public void setPaintMode() {
602 writeWarning(getClass() + ": setPaintMode() not implemented.");
603 }
604
605 public void setXORMode(Color c1) {
606 writeWarning(getClass() + ": setXORMode(Color) not implemented.");
607 }
608
609 protected void writePaint(Color c) throws IOException {
610 setPSColor(c, false);
611 }
612
613 protected void writePaint(GradientPaint paint) throws IOException {
614 if (postscriptLevel >= LEVEL_3) {
615 float[] rgb1 = paint.getColor1().getRGBColorComponents(null);
616 float[] rgb2 = paint.getColor2().getRGBColorComponents(null);
617 Point2D p1 = paint.getPoint1();
618 Point2D p2 = paint.getPoint2();
619 os.println("<< /PatternType 2");
620 os.println(" /Shading");
621 os.println(" << /ShadingType 2");
622 os.println(" /ColorSpace /DeviceRGB");
623 os.println(" /Coords [" + p1.getX() + " " + p1.getY() + " "
624 + p2.getX() + " " + p2.getY() + "]");
625 os.println(" /Function");
626 os.println(" << /FunctionType 2");
627 os.println(" /Domain [0 1]");
628 os.println(" /Range [0 1 0 1 0 1]");
629 os.println(" /C0 [" + rgb1[0] + " " + rgb1[1] + " "
630 + rgb1[2] + "]");
631 os.println(" /C1 [" + rgb2[0] + " " + rgb2[1] + " "
632 + rgb2[2] + "]");
633 os.println(" /N 1");
634 os.println(" >>");
635 os.println(" /Extend [true true]");
636 os.println(" >>");
637 os.println(">>");
638 os.println("matrix makepattern setpattern");
639 }
640 }
641
642 protected void writePaint(TexturePaint paint) throws IOException {
643 // written when filled
644 }
645
646 protected void writePaint(Paint p) throws IOException {
647 // written when filled
648 }
649
650 protected void writeFont(Font font) {
651 // written when needed
652 }
653
654 public GraphicsConfiguration getDeviceConfiguration() {
655 writeWarning(getClass() + ": getDeviceConfiguration() not implemented.");
656 return null;
657 }
658
659 /**
660 * Embed a PostScript comment into the output file.
661 */
662 public void writeComment(String s) throws IOException {
663 os.println("% " + s);
664 }
665
666 public String toString() {
667 return "PSGraphics2D";
668 }
669
670 /**
671 * Write the string <code>str</code> the the stream. Method is used by
672 * {@link FontUtilities#showString(java.awt.Font, String,
673 * org.freehep.graphics2d.font.CharTable,
674 * org.freehep.graphics2d.font.FontUtilities.ShowString)} or
675 * {@link #showCharacterCodes(String, double, double)} depending on the
676 * settings font embedding.
677 *
678 * @param font font to use
679 * @param str string to draw
680 */
681 public void showString(Font font, String str) {
682 StringBuffer result = new StringBuffer();
683 Map /*<TextAttribute,?>*/<Attribute, Object> attributes = FontUtilities.getAttributes(font);
684 PSFontTable.normalize(attributes);
685 // write font name
686 String fontName = fontTable.fontReference(
687 font,
688 isProperty(EMBED_FONTS),
689 getProperty(EMBED_FONTS_AS));
690 result.append("/");
691 result.append(fontName);
692 result.append(" findfont ");
693 result.append(font.getSize());
694 result.append(" scalefont setfont");
695
696 // use embeded fonts or draw string directly
697 if (isProperty(EMBED_FONTS)) {
698 // write string directly
699 result.append("\n");
700 result.append(PSStringStyler.getEscaped(str));
701 result.append(" show");
702 } else {
703 // write string as styled unicode char sequence
704 result.append(" ");
705 result.append(PSStringStyler.getStyledString(attributes, str));
706 result.append(" recshow");
707 }
708
709 // write the result
710 os.println(result.toString());
711 }
712
713 /**
714 * Draws <code>str</code> to the stream. Uses the font transformation and depending on
715 * {@link PSGraphics2D#EMBED_FONTS} the method {@link #showString(java.awt.Font, String)}
716 * or {@link FontUtilities#showString(java.awt.Font, String, org.freehep.graphics2d.font.CharTable,
717 * org.freehep.graphics2d.font.FontUtilities.ShowString)} ;
718 *
719 * @param str string to draw
720 * @param x coordinate for drawing
721 * @param y coordinate for drawing
722 * @throws java.io.IOException thrown by write operations
723 */
724 private void showCharacterCodes(String str, double x, double y) throws IOException {
725 // push a copy of the current graphics state on the graphics state stack
726 writeGraphicsSave();
727 // move to string position. This is done by transformation because
728 // after a "moveto" command all translations by a transformation
729 // are ignored and font transformation should be used after the
730 // general one.
731 AffineTransform at = new AffineTransform(1, 0, 0, 1, x, y);
732 // aplly font transformation, e.g. vertical offset and scaling
733 // for TextAttribut.SUPERSUBSCRIPT
734 at.concatenate(getFont().getTransform());
735 // flip vertically
736 at.scale(1, -1);
737 // write transformation
738 writeTransform(at);
739 // move to drawing position, nedded to open a drawing path
740 os.println(fixedPrecision(0) + " " + fixedPrecision(0) + " moveto");
741 // embed font or draw string directly
742 if (isProperty(EMBED_FONTS)) {
743 // use embedded font encodings for unicode to PS
744 FontUtilities.showString(
745 getFont(),
746 str,
747 fontTable.getEncodingTable(),
748 this);
749 } else {
750 // use PS header for unicode to composite font encoding
751 showString(getFont(), str);
752 }
753
754 // reset the current graphics state from the one on the top
755 // of the graphics state stack and pop the graphics state stack
756 writeGraphicsRestore();
757 }
758
759 /**
760 * A utility function which actually sets the color in the PS. We use the
761 * stroke color as the PS current color and a special saved variable for the
762 * fill color.
763 *
764 * @param c Color
765 * @param fillColor true writes a color for fillings
766 */
767 private void setPSColor(Color c, boolean fillColor) {
768 if (c != null) {
769 if (c instanceof MappedColor) {
770 MappedColor mc = (MappedColor) c;
771 if (!fillColor) {
772 if (mc.getBrightness() == 0) {
773 os.println(mc.getColorTag() + " vg&C");
774 } else {
775 os.println(mc.getColorTag() + " " + mc.getBrightness()
776 + " darken vg&C");
777 }
778 } else {
779 if (mc.getBrightness() == 0) {
780 os.println(mc.getColorTag() + " vg&DFC");
781 } else {
782 os.println(mc.getColorTag() + " " + mc.getBrightness()
783 + " darken vg&DFC");
784 }
785 }
786 } else {
787 Color pc = getPrintColor(c);
788 double red = ((double) pc.getRed()) / 255.;
789 double green = ((double) pc.getGreen()) / 255.;
790 double blue = ((double) pc.getBlue()) / 255.;
791 os.print(fixedPrecision(red) + " " + fixedPrecision(green)
792 + " " + fixedPrecision(blue) + " ");
793 os.println(((fillColor) ? "rg" : "RG"));
794 }
795 }
796 }
797
798 private ScientificFormat scientific = new ScientificFormat(6, 9, false);
799
800 public String fixedPrecision(double d) {
801 return scientific.format(d);
802 }
803
804 }