f1ff9896cd11daf72cbe9110c2d41c7d238ebe55
[scilab.git] / scilab / modules / graphic_export / src / java / org / scilab / modules / graphic_export / Export.java
1 /*
2  * Scilab ( http://www.scilab.org/ ) - This file is part of Scilab
3  * Copyright (C) 2012 - Scilab Enterprises - Calixte Denizet
4  *
5  * This file must be used under the terms of the CeCILL.
6  * This source file is licensed as described in the file COPYING, which
7  * you should have received as part of this distribution.  The terms
8  * are also available at
9  * http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt
10  *
11  */
12
13 package org.scilab.modules.graphic_export;
14
15 import java.awt.Dimension;
16 import java.awt.Font;
17 import java.awt.Graphics2D;
18 import java.awt.Shape;
19 import java.awt.geom.AffineTransform;
20 import java.awt.geom.Ellipse2D;
21 import java.awt.geom.PathIterator;
22 import java.awt.image.BufferedImage;
23 import java.io.BufferedOutputStream;
24 import java.io.ByteArrayOutputStream;
25 import java.io.File;
26 import java.io.FileOutputStream;
27 import java.io.IOException;
28 import java.io.OutputStream;
29 import java.io.OutputStreamWriter;
30 import java.io.Writer;
31 import java.nio.charset.Charset;
32 import java.nio.charset.CharsetEncoder;
33 import java.text.AttributedCharacterIterator;
34 import java.util.HashMap;
35 import java.util.Map;
36 import java.util.WeakHashMap;
37
38 import org.apache.batik.dom.GenericDOMImplementation;
39 import org.apache.batik.svggen.SVGGeneratorContext;
40 import org.apache.batik.svggen.SVGGraphics2D;
41 import org.apache.fop.Version;
42 import org.apache.fop.svg.PDFDocumentGraphics2D;
43 import org.apache.xmlgraphics.java2d.GraphicContext;
44 import org.apache.xmlgraphics.java2d.ps.AbstractPSDocumentGraphics2D;
45 import org.apache.xmlgraphics.java2d.ps.EPSDocumentGraphics2D;
46 import org.apache.xmlgraphics.java2d.ps.PSDocumentGraphics2D;
47 import org.apache.xmlgraphics.ps.DSCConstants;
48 import org.apache.xmlgraphics.ps.PSGenerator;
49 import org.scilab.forge.scirenderer.Canvas;
50 import org.scilab.forge.scirenderer.implementation.g2d.G2DCanvas;
51 import org.scilab.forge.scirenderer.implementation.g2d.G2DCanvasFactory;
52 import org.scilab.forge.scirenderer.implementation.jogl.JoGLCanvas;
53 import org.scilab.forge.scirenderer.implementation.jogl.JoGLCanvasFactory;
54 import org.scilab.modules.commons.ScilabCommonsUtils;
55 import org.scilab.modules.graphic_export.convertToPPM.PPMEncoder;
56 import org.scilab.modules.graphic_objects.figure.Figure;
57 import org.scilab.modules.graphic_objects.graphicController.GraphicController;
58 import org.scilab.modules.graphic_objects.graphicObject.GraphicObjectProperties;
59 import org.scilab.modules.renderer.JoGLView.DrawerVisitor;
60 import org.w3c.dom.DOMImplementation;
61 import org.w3c.dom.Document;
62
63 /**
64  * Main class to export
65  * Dependancies are put in inner classes to avoid the deps loading.
66  *
67  * @author Calixte DENIZET
68  */
69 public class Export {
70
71     public static final int SUCCESS = 0;
72     public static final int IOEXCEPTION_ERROR = 1;
73     public static final int INVALID_FILE = 2;
74     public static final int MEMORY_ERROR = 3;
75     public static final int UNKNOWN_ERROR = 4;
76
77     private static final float DEFAULT_JPEG_COMPRESSION = 0.95f;
78
79     private static final String CLASSPATH_PDF_PS_EPS_EXPORT_NAME = "pdf_ps_eps_graphic_export";
80     private static final String CLASSPATH_SVG_EXPORT_NAME = "svg_graphic_export";
81
82     private static final Map<DrawerVisitor, Exporter> visitorsToExp = new WeakHashMap<DrawerVisitor, Exporter>();
83
84     private static final Map<String, Integer> extToType = new HashMap<String, Integer>();
85     static {
86         extToType.put("bmp", 1);
87         extToType.put("gif", 2);
88         extToType.put("jpeg", 3);
89         extToType.put("jpg", 3);
90         extToType.put("png", 4);
91         extToType.put("ppm", 5);
92         extToType.put("eps", 6);
93         extToType.put("pdf", 7);
94         extToType.put("svg", 8);
95         extToType.put("ps", 9);
96         extToType.put("pos", 9);
97     }
98
99     private static boolean svgLoaded;
100     private static boolean pdfLoaded;
101
102     public enum TYPE { PNG, JPEG, GIF, BMP, PPM, SVG, PS, EPS, PDF }
103     private static final TYPE[] types = new TYPE[] {TYPE.PNG, TYPE.BMP, TYPE.GIF, TYPE.JPEG, TYPE.PNG, TYPE.PPM, TYPE.EPS, TYPE.PDF, TYPE.SVG, TYPE.PS};
104
105     /**
106      * @param type the image type
107      * @return true if bitmap image format
108      */
109     public static boolean isBitmapFormat(TYPE type) {
110         return type == TYPE.PNG || type == TYPE.JPEG || type == TYPE.GIF || type == TYPE.BMP || type == TYPE.PPM;
111     }
112
113     public static int getType(String ext) {
114         Integer type = extToType.get(ext.toLowerCase());
115         if (type == null) {
116             return -1;
117         }
118
119         return type;
120     }
121
122     /**
123      * Export in drawing in a Graphics2D
124      * @param uid the figure uid
125      * @param type the export type
126      * @param fileName the file name
127      * @param params the export paramaters
128      * @return the export status
129      */
130     public static int export(String uid, int type, String fileName, ExportParams params, boolean headless) {
131         // Check that the fileName contains an extension
132         int dotPosition = fileName.lastIndexOf('.'); // position of the dot
133         boolean extensionFound = false;
134         if (dotPosition > 0 && dotPosition <= fileName.length() - 2) {
135             extensionFound = true;
136         }
137
138         String extendedFilename = fileName;
139         if (!extensionFound) { // Add default extension if no one found
140             String[] extensions = {"png", "bmp", "gif", "jpeg", "png", "ppm", "eps", "pdf", "svg", "ps"};
141             extendedFilename = fileName + "." + extensions[type];
142         }
143
144         DrawerVisitor visitor = DrawerVisitor.getVisitor(uid);
145         if (visitor != null) {
146             Canvas canvas = visitor.getCanvas();
147             if (canvas instanceof JoGLCanvas && isBitmapFormat(types[type])) {
148                 try {
149                     return exportBitmap(uid, type, extendedFilename, true, params);
150                 } catch (OutOfMemoryError e) {
151                     return MEMORY_ERROR;
152                 } catch (Throwable e) {
153                     return UNKNOWN_ERROR;
154                 }
155             }
156         }
157
158         return exportVectorial(uid, type, extendedFilename, params, headless);
159     }
160
161
162     /**
163      * Export in drawing in a Graphics2D
164      * @param uid the figure uid
165      * @param type the export type
166      * @param fileName the file name
167      * @param params the export paramaters
168      * @return the export status
169      */
170     public static int exportVectorial(String uid, int type, String fileName, ExportParams params, boolean headless) {
171         if (fileName == null) {
172             return INVALID_FILE;
173         }
174
175         File f = new File(fileName);
176         int ret = Utils.checkWritePermission(f);
177         if (ret != SUCCESS) {
178             return ret;
179         }
180
181         try {
182             return exportVectorial(uid, types[type], f, params, headless);
183         } catch (IOException e) {
184             return IOEXCEPTION_ERROR;
185         }
186     }
187
188     /**
189      * Export in drawing in a Graphics2D
190      * @param uid the figure uid
191      * @param type the export type
192      * @param file the file where to export
193      * @param params the export paramaters
194      */
195     public static int exportVectorial(String uid, TYPE type, File file, ExportParams params, boolean headless) throws IOException {
196         Figure figure = (Figure) GraphicController.getController().getObjectFromId(uid);
197
198         if (!headless) {
199             Exporter exporter = getExporter(type);
200             Integer[] dims = figure.getAxesSize();
201             int width = dims[0];
202             int height = dims[1];
203
204             Graphics2D g2d = exporter.getGraphics2D(width, height, file, params);
205             params.setParamsOnGraphics(g2d);
206
207             Canvas canvas = G2DCanvasFactory.createCanvas(g2d, width, height);
208             DrawerVisitor oldVisitor = DrawerVisitor.getVisitor(uid);
209             DrawerVisitor visitor = new DrawerVisitor(null, canvas, figure) {
210                     @Override
211                     public void updateObject(String id, int property) {
212                         // Don't update during the export
213                     }
214                 };
215
216             try {
217                 canvas.setMainDrawer(visitor);
218                 canvas.redraw();
219                 exporter.write();
220             } catch (OutOfMemoryError e) {
221                 return MEMORY_ERROR;
222             } catch (Throwable e) {
223                 return UNKNOWN_ERROR;
224             } finally {
225                 GraphicController.getController().unregister(visitor);
226                 DrawerVisitor.changeVisitor(figure, oldVisitor);
227                 exporter.dispose();
228                 exporter = null;
229                 visitorsToExp.remove(visitor);
230             }
231         } else {
232             DrawerVisitor visitor = DrawerVisitor.getVisitor(uid);
233             G2DCanvas canvas = (G2DCanvas) visitor.getCanvas();
234             canvas.enableDraw();
235             Exporter exporter = null;
236             try {
237                 canvas.redraw();
238                 exporter = visitorsToExp.get(visitor);
239                 if (exporter != null) {
240                     exporter.file = file;
241                     exporter.write();
242                 }
243             } catch (OutOfMemoryError e) {
244                 return MEMORY_ERROR;
245             } catch (Throwable e) {
246                 return UNKNOWN_ERROR;
247             } finally {
248                 if (exporter != null) {
249                     exporter.dispose();
250                     exporter = null;
251                     visitorsToExp.remove(visitor);
252                 }
253                 DrawerVisitor.changeVisitor(figure, null);
254                 GraphicController.getController().unregister(visitor);
255             }
256         }
257
258         return SUCCESS;
259     }
260
261     /**
262      * Export in getting a buffered image from JoGL
263      * @param uid the figure uid
264      * @param type the export type
265      * @param fileName the file name
266      * @param fromScreen if true, then use the screen view
267      * @param params the export paramaters
268      * @return the export status
269      */
270     public static int exportBitmap(String uid, int type, String fileName, boolean fromScreen, ExportParams params) {
271         if (fileName == null) {
272             return INVALID_FILE;
273         }
274
275         File f = new File(fileName);
276         int ret = Utils.checkWritePermission(f);
277         if (ret != SUCCESS) {
278             return ret;
279         }
280
281         try {
282             exportBitmap(uid, types[type], f, fromScreen, params);
283         } catch (IOException e) {
284             return IOEXCEPTION_ERROR;
285         }
286
287         return SUCCESS;
288     }
289
290     /**
291      * Export in getting a buffered image from JoGL
292      * @param uid the figure uid
293      * @param type the export type
294      * @param file the file where to export
295      * @param fromScreen if true, then use the screen view
296      * @param params the export paramaters
297      */
298     public static void exportBitmap(String uid, TYPE type, File file, boolean fromScreen, ExportParams params) throws IOException {
299         if (isBitmapFormat(type)) {
300             JoGLCanvas joglCanvas = null;
301             if (fromScreen) {
302                 DrawerVisitor visitor = DrawerVisitor.getVisitor(uid);
303                 Canvas canvas = visitor.getCanvas();
304                 if (canvas instanceof JoGLCanvas) {
305                     joglCanvas = (JoGLCanvas) canvas;
306                 }
307             } else {
308                 Figure figure = (Figure) GraphicController.getController().getObjectFromId(uid);
309                 Integer[] dims = figure.getAxesSize();
310                 DrawerVisitor oldVisitor = DrawerVisitor.getVisitor(uid);
311                 joglCanvas = (JoGLCanvas) JoGLCanvasFactory.createCanvas(dims[0], dims[1]);
312                 DrawerVisitor visitor = new DrawerVisitor(null, joglCanvas, figure) {
313                         @Override
314                         public void updateObject(String id, int property) {
315                             // Don't update during the export
316                         }
317
318                         @Override
319                         public void deleteObject(String id) {
320                             // Don't delete during the export
321                         }
322                     };
323                 joglCanvas.setMainDrawer(visitor);
324                 joglCanvas.redraw();
325                 GraphicController.getController().unregister(visitor);
326                 DrawerVisitor.changeVisitor(figure, oldVisitor);
327             }
328
329             if (joglCanvas != null) {
330                 BufferedImage image = joglCanvas.getImage();
331                 //joglCanvas.destroy();
332                 PNGExporter exporter = (PNGExporter) getExporter(type);
333                 exporter.setImage(file, image, params);
334                 exporter.write();
335                 exporter.dispose();
336             }
337         }
338     }
339
340     /**
341      * Export in drawing in a Graphics2D
342      * @param uid the figure uid
343      * @param type the export type
344      * @param file the file where to export
345      * @param params the export paramaters
346      */
347     public static void setVisitor(String uid, int type, final ExportParams params) {
348         final Exporter exporter = getExporter(types[type]);
349         Figure figure = (Figure) GraphicController.getController().getObjectFromId(uid);
350         Integer[] dims = figure.getAxesSize();
351         int width = dims[0];
352         int height = dims[1];
353
354         Graphics2D g2d = exporter.getGraphics2D(width, height, null, params);
355         params.setParamsOnGraphics(g2d);
356
357         G2DCanvas canvas = G2DCanvasFactory.createCanvas(g2d, width, height);
358         canvas.disableDraw();
359         DrawerVisitor visitor = new DrawerVisitor(null, canvas, figure) {
360             @Override
361             public void deleteObject(String id) {
362                 // Don't delete during the export
363             }
364
365             @Override
366             public void updateObject(String id, int property) {
367                 if (property == GraphicObjectProperties.__GO_AXES_SIZE__) {
368                     Integer[] size = getFigure().getAxesSize();
369                     Graphics2D g2d = exporter.getGraphics2D(size[0], size[1], null, params);
370                     params.setParamsOnGraphics(g2d);
371
372                     G2DCanvas canvas = G2DCanvasFactory.createCanvas(g2d, size[0], size[1]);
373                     canvas.disableDraw();
374                     setCanvas(canvas);
375
376                     setDrawingTools(canvas.getDrawingTools());
377                     canvas.setMainDrawer(this);
378                 }
379             }
380         };
381         visitor.setDrawingTools(canvas.getDrawingTools());
382         canvas.setMainDrawer(visitor);
383         visitorsToExp.put(visitor, exporter);
384     }
385
386     /**
387      * Get an exporter from a type
388      * @param type the exporter type.
389      * @return the corresponding exporter/
390      */
391     private static Exporter getExporter(TYPE type) {
392         switch (type) {
393         case PNG :
394             return new PNGExporter();
395         case GIF :
396             return new GIFExporter();
397         case JPEG :
398             return new JPEGExporter();
399         case BMP :
400             return new BMPExporter();
401         case PPM :
402             return new PPMExporter();
403         case SVG :
404             if (!svgLoaded) {
405                 ScilabCommonsUtils.loadOnUse(CLASSPATH_SVG_EXPORT_NAME);
406                 svgLoaded = true;
407             }
408             return new SVGExporter();
409         case PDF :
410             loadPDF();
411             return new PDFExporter();
412         case PS :
413             loadPDF();
414             return new PSExporter();
415         case EPS :
416             loadPDF();
417             return new EPSExporter();
418         default :
419             break;
420         }
421
422         return null;
423     }
424
425     /**
426      * Load the PDF/PS/EPS dependencies
427      */
428     private static final void loadPDF() {
429         if (!pdfLoaded) {
430             ScilabCommonsUtils.loadOnUse(CLASSPATH_PDF_PS_EPS_EXPORT_NAME);
431             pdfLoaded = true;
432         }
433     }
434
435     /**
436      * Interface to export
437      */
438     private static abstract class Exporter {
439
440         protected File file;
441
442         /**
443          * @param width graphics width
444          * @param height graphisc height
445          * @param file the file
446          * @param params the export parameters
447          */
448         abstract Graphics2D getGraphics2D(int width, int height, File file, ExportParams params);
449
450         /**
451          * Write the file
452          */
453         abstract void write() throws IOException;
454
455         abstract void dispose();
456     }
457
458     /**
459      * PNG Exporter
460      */
461     private static class PNGExporter extends Exporter {
462
463         protected BufferedImage image;
464         protected Graphics2D g2d;
465         protected ExportParams params;
466
467         public PNGExporter() { }
468
469         public void setImage(File file, BufferedImage image, ExportParams params) {
470             this.file = file;
471             this.image = image;
472             this.params = params;
473         }
474
475         @Override
476         public Graphics2D getGraphics2D(int width, int height, File file, ExportParams params) {
477             this.file = file;
478             this.params = params;
479             image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
480             g2d = image.createGraphics();
481
482             return g2d;
483         }
484
485         @Override
486         public void write() throws IOException {
487             ExportBitmap.writeFile(image, "png", file);
488         }
489
490         @Override
491         public void dispose() {
492             if (g2d != null) {
493                 g2d.dispose();
494             }
495         }
496     }
497
498     /**
499      * GIF Exporter
500      */
501     private static class GIFExporter extends PNGExporter {
502
503         public GIFExporter() { }
504
505         @Override
506         public void write() throws IOException {
507             ExportBitmap.writeFile(image, "gif", file);
508         }
509     }
510
511     /**
512      * BMP Exporter
513      */
514     private static class BMPExporter extends PNGExporter {
515
516         public BMPExporter() { }
517
518         @Override
519         public Graphics2D getGraphics2D(int width, int height, File file, ExportParams params) {
520             this.file = file;
521             this.params = params;
522             image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
523             g2d = image.createGraphics();
524
525             return g2d;
526         }
527
528         @Override
529         public void write() throws IOException {
530             ExportBitmap.writeFile(image, "bmp", file);
531         }
532     }
533
534     /**
535      * JPEG Exporter
536      */
537     private static class JPEGExporter extends BMPExporter {
538
539         public JPEGExporter() { }
540
541         @Override
542         public void write() throws IOException {
543             if (params.compressionQuality == -1) {
544                 ExportBitmap.writeJPEG(image, DEFAULT_JPEG_COMPRESSION, file);
545             } else {
546                 ExportBitmap.writeJPEG(image, params.compressionQuality, file);
547             }
548         }
549     }
550
551     /**
552      * PPM Exporter
553      */
554     private static class PPMExporter extends BMPExporter {
555
556         public PPMExporter() { }
557
558         @Override
559         public void write() throws IOException {
560             OutputStream out = new BufferedOutputStream(new FileOutputStream(file));
561             PPMEncoder encoder = new PPMEncoder(image, out);
562             int[] pixels = image.getRGB(0, 0, image.getWidth(), image.getHeight(), null, 0, image.getWidth());
563             encoder.encodeStart(image.getWidth(), image.getHeight());
564             encoder.encodePixels(0, 0, image.getWidth(), image.getHeight(), pixels, 0, image.getWidth());
565             out.flush();
566             out.close();
567         }
568     }
569
570     /**
571      * SVG Exporter
572      */
573     private static class SVGExporter extends Exporter {
574
575         private SVGGraphics2D g2d;
576         private ExportParams params;
577
578         public SVGExporter() { }
579
580         @Override
581         public Graphics2D getGraphics2D(int width, int height, File file, ExportParams params) {
582             this.file = file;
583             this.params = params;
584             DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation();
585             Document document = domImpl.createDocument("http://www.w3.org/2000/svg", "svg", null);
586             final SVGGeneratorContext ctx = SVGGeneratorContext.createDefault(document);
587             ctx.setComment("Generated by Scilab with Batik SVG Generator");
588             // TODO: better handle of LaTeX fonts (should remove the 'true' below and include the font in the SVG)
589             // same thing for PDF & co...
590             ctx.setEmbeddedFontsOn(true);
591             g2d = new SVGGraphics2D(ctx, false) {
592
593                     @Override
594                     public void drawString(String s, float x, float y) {
595                         textAsShapes = getFont().getFontName().startsWith("jlm");
596                         super.drawString(s, x, y);
597                     }
598
599                     @Override
600                     public void drawString(AttributedCharacterIterator ati, float x, float y) {
601                         textAsShapes = getFont().getFontName().startsWith("jlm");
602                         super.drawString(ati, x, y);
603                     }
604                 };
605             if (params.orientation == ExportParams.LANDSCAPE) {
606                 g2d.setSVGCanvasSize(new Dimension(height, width));
607                 AffineTransform transf = AffineTransform.getRotateInstance(Math.PI / 2);
608                 transf.preConcatenate(AffineTransform.getTranslateInstance(height, 0));
609                 g2d.setTransform(transf);
610             } else {
611                 g2d.setSVGCanvasSize(new Dimension(width, height));
612             }
613             return g2d;
614         }
615
616         @Override
617         public void write() throws IOException {
618             boolean useCSS = true;
619             OutputStream svgs = new BufferedOutputStream(new FileOutputStream(file));
620             Writer out = new OutputStreamWriter(svgs, "UTF-8");
621             g2d.stream(out, useCSS);
622             svgs.flush();
623             svgs.close();
624         }
625
626         @Override
627         public void dispose() {
628             if (g2d != null) {
629                 g2d.dispose();
630             }
631         }
632     }
633
634     /**
635      * PDF Exporter
636      */
637     private static class PDFExporter extends Exporter {
638
639         private OutputStream out;
640         private PDFDocumentGraphics2D g2d;
641         private ExportParams params;
642         private ByteArrayOutputStream buffer;
643
644         public PDFExporter() { }
645
646         @Override
647         public Graphics2D getGraphics2D(int width, int height, File file, ExportParams params) {
648             this.file = file;
649             this.params = params;
650             try {
651                 if (file == null) {
652                     buffer = new ByteArrayOutputStream();
653                     out = new BufferedOutputStream(buffer);
654                 } else {
655                     out = new BufferedOutputStream(new FileOutputStream(file));
656                 }
657                 g2d = new PDFDocumentGraphics2D(true);
658                 g2d.setupDefaultFontInfo();
659                 g2d.getPDFDocument().getInfo().setProducer("Generated by Scilab with Apache FOP Version " + Version.getVersion());
660                 g2d.setGraphicContext(new GraphicContext());
661                 if (params.orientation == ExportParams.LANDSCAPE) {
662                     g2d.setupDocument(out, height, width);
663                     g2d.setSVGDimension(height, width);
664                     double s = PDFDocumentGraphics2D.NORMAL_PDF_RESOLUTION / g2d.getDeviceDPI();
665                     AffineTransform transf = AffineTransform.getRotateInstance(Math.PI / 2);
666                     transf.preConcatenate(AffineTransform.getTranslateInstance(height / s, 0));
667                     g2d.setTransform(transf);
668                 } else {
669                     g2d.setupDocument(out, width, height);
670                     g2d.setSVGDimension(width, height);
671                 }
672             } catch (IOException e) { }
673
674             return g2d;
675         }
676
677         @Override
678         public void write() throws IOException {
679             if (g2d != null) {
680                 g2d.finish();
681             }
682             if (buffer != null && file != null) {
683                 FileOutputStream fos = new FileOutputStream(file);
684                 buffer.writeTo(fos);
685                 buffer.close();
686                 fos.flush();
687                 fos.close();
688             }
689             if (out != null) {
690                 out.close();
691             }
692         }
693
694         @Override
695         public void dispose() {
696             g2d.dispose();
697         }
698     }
699
700     /**
701      * PS Exporter
702      */
703     private static class PSExporter extends Exporter {
704
705         protected OutputStream out;
706         protected AbstractPSDocumentGraphics2D g2d;
707         protected ExportParams params;
708         protected ByteArrayOutputStream buffer;
709
710         public PSExporter() { }
711
712         @Override
713         public Graphics2D getGraphics2D(int width, int height, File file, final ExportParams params) {
714             this.file = file;
715             this.params = params;
716             try {
717                 if (file == null) {
718                     buffer = new ByteArrayOutputStream();
719                     out = new BufferedOutputStream(buffer);
720                 } else {
721                     out = new BufferedOutputStream(new FileOutputStream(file));
722                 }
723                 g2d = new PSDocumentGraphics2D(true, out, width, height) {
724                         @Override
725                         protected void writePageHeader() throws IOException {
726                             super.writePageHeader();
727                             if (params.orientation == ExportParams.LANDSCAPE) {
728                                 gen.writeDSCComment(DSCConstants.PAGE_ORIENTATION, "Landscape");
729                             } else {
730                                 gen.writeDSCComment(DSCConstants.PAGE_ORIENTATION, "Portrait");
731                             }
732                             gen.writeln("/ReEncode { /MyEncoding exch def exch findfont dup length dict begin {def} forall /Encoding MyEncoding def currentdict end definefont } def");
733                             gen.writeln("/Helvetica /HelveticaLatin1 ISOLatin1Encoding ReEncode");
734                             gen.writeln("/Times /TimesLatin1 ISOLatin1Encoding ReEncode");
735                         }
736
737                         @Override
738                         public void drawString(String s, float x, float y) {
739                             if (s != null && !s.isEmpty()) {
740                                 CharsetEncoder encoder = Charset.forName("ISO-8859-1").newEncoder();
741                                 if (encoder.canEncode(s)) {
742                                     Font font = getFont();
743                                     boolean sserif = font.getName().equals("SansSerif");
744                                     boolean serif = font.getName().equals("Serif");
745                                     if (sserif || serif) {
746                                         try {
747                                             preparePainting();
748                                             establishColor(getColor());
749                                             gen.writeln((sserif ? "/HelveticaLatin1" : "/TimesLatin1") + " " + gen.formatDouble(getFont().getSize()) + " F");
750
751                                             gen.saveGraphicsState();
752                                             Shape imclip = getClip();
753                                             writeClip(imclip);
754
755                                             AffineTransform trans = getTransform();
756                                             boolean newTransform = gen.getCurrentState().checkTransform(trans) && !trans.isIdentity();
757
758                                             if (newTransform) {
759                                                 gen.concatMatrix(trans);
760                                             }
761
762                                             gen.writeln(gen.formatDouble(x)
763                                                         + " " + gen.formatDouble(y)
764                                                         + " M 1 -1 scale");
765
766                                             StringBuffer buf = new StringBuffer("(");
767                                             for (int i = 0; i < s.length(); i++) {
768                                                 PSGenerator.escapeChar(s.charAt(i), buf);
769                                             }
770                                             buf.append(") t");
771
772                                             gen.writeln(buf.toString());
773
774                                             gen.restoreGraphicsState();
775                                         } catch (IOException e) {
776                                             System.err.println(e);
777                                         }
778
779                                         return;
780                                     }
781                                 }
782
783                                 super.drawString(s, x, y);
784                             }
785                         }
786
787                         @Override
788                         public int processShape(Shape s) throws IOException {
789                             if (s instanceof Ellipse2D.Double) {
790                                 Ellipse2D.Double ell = (Ellipse2D.Double) s;
791                                 if (ell.height == ell.width) {
792                                     gen.writeln(gen.formatDouble(ell.x + ell.width / 2)
793                                                 + " " + gen.formatDouble(ell.y + ell.height / 2)
794                                                 + " " + gen.formatDouble(ell.width / 2)
795                                                 + " " + gen.formatDouble(0d)
796                                                 + " " + gen.formatDouble(360d)
797                                                 + " arc cp");
798
799                                     return PathIterator.WIND_NON_ZERO;
800                                 }
801                             }
802
803                             return super.processShape(s);
804                         }
805                     };
806                 g2d.setGraphicContext(new GraphicContext());
807             } catch (IOException e) { }
808
809             return g2d;
810         }
811
812         @Override
813         public void write() throws IOException {
814             if (g2d != null) {
815                 g2d.finish();
816             }
817             if (buffer != null && file != null) {
818                 FileOutputStream fos = new FileOutputStream(file);
819                 buffer.writeTo(fos);
820                 buffer.close();
821                 fos.flush();
822                 fos.close();
823             }
824             if (out != null) {
825                 out.close();
826             }
827         }
828
829         @Override
830         public void dispose() {
831             if (g2d != null) {
832                 g2d.dispose();
833             }
834         }
835     }
836
837     /**
838      * EPS Exporter
839      */
840     private static class EPSExporter extends PSExporter {
841
842         public EPSExporter() { }
843
844         @Override
845         public Graphics2D getGraphics2D(int width, int height, File file, final ExportParams params) {
846             this.file = file;
847             this.params = params;
848             try {
849                 if (file == null) {
850                     buffer = new ByteArrayOutputStream();
851                     out = new BufferedOutputStream(buffer);
852                 } else {
853                     out = new BufferedOutputStream(new FileOutputStream(file));
854                 }
855                 g2d = new EPSDocumentGraphics2D(true) {
856                         @Override
857                         protected void writePageHeader() throws IOException {
858                             super.writePageHeader();
859                             if (params.orientation == ExportParams.LANDSCAPE) {
860                                 gen.writeDSCComment(DSCConstants.PAGE_ORIENTATION, "Landscape");
861                             } else {
862                                 gen.writeDSCComment(DSCConstants.PAGE_ORIENTATION, "Portrait");
863                             }
864                             gen.writeln("/ReEncode { /MyEncoding exch def exch findfont dup length dict begin {def} forall /Encoding MyEncoding def currentdict end definefont } def");
865                             gen.writeln("/Helvetica /HelveticaLatin1 ISOLatin1Encoding ReEncode");
866                             gen.writeln("/Times /TimesLatin1 ISOLatin1Encoding ReEncode");
867                         }
868
869                         @Override
870                         public void drawString(String s, float x, float y) {
871                             if (s != null && !s.isEmpty()) {
872                                 CharsetEncoder encoder = Charset.forName("ISO-8859-1").newEncoder();
873                                 if (encoder.canEncode(s)) {
874                                     Font font = getFont();
875                                     boolean sserif = font.getName().equals("SansSerif");
876                                     boolean serif = font.getName().equals("Serif");
877                                     if (sserif || serif) {
878                                         try {
879                                             preparePainting();
880                                             establishColor(getColor());
881                                             gen.writeln((sserif ? "/HelveticaLatin1" : "/TimesLatin1") + " " + gen.formatDouble(getFont().getSize()) + " F");
882
883                                             gen.saveGraphicsState();
884                                             Shape imclip = getClip();
885                                             writeClip(imclip);
886
887                                             AffineTransform trans = getTransform();
888                                             boolean newTransform = gen.getCurrentState().checkTransform(trans) && !trans.isIdentity();
889
890                                             if (newTransform) {
891                                                 gen.concatMatrix(trans);
892                                             }
893
894                                             gen.writeln(gen.formatDouble(x)
895                                                         + " " + gen.formatDouble(y)
896                                                         + " M 1 -1 scale");
897
898                                             StringBuffer buf = new StringBuffer("(");
899                                             for (int i = 0; i < s.length(); i++) {
900                                                 PSGenerator.escapeChar(s.charAt(i), buf);
901                                             }
902                                             buf.append(") t");
903
904                                             gen.writeln(buf.toString());
905
906                                             gen.restoreGraphicsState();
907                                         } catch (IOException e) {
908                                             System.err.println(e);
909                                         }
910
911                                         return;
912                                     }
913                                 }
914
915                                 super.drawString(s, x, y);
916                             }
917                         }
918
919                         @Override
920                         public int processShape(Shape s) throws IOException {
921                             if (s instanceof Ellipse2D.Double) {
922                                 Ellipse2D.Double ell = (Ellipse2D.Double) s;
923                                 if (ell.height == ell.width) {
924                                     gen.writeln(gen.formatDouble(ell.x + ell.width / 2)
925                                                 + " " + gen.formatDouble(ell.y + ell.height / 2)
926                                                 + " " + gen.formatDouble(ell.width / 2)
927                                                 + " " + gen.formatDouble(0d)
928                                                 + " " + gen.formatDouble(360d)
929                                                 + " arc cp");
930
931                                     return PathIterator.WIND_NON_ZERO;
932                                 }
933                             }
934
935                             return super.processShape(s);
936                         }
937
938                     };
939                 g2d.setupDocument(out, width, height);
940                 g2d.setGraphicContext(new GraphicContext());
941             } catch (IOException e) { }
942
943             return g2d;
944         }
945     }
946 }