Export: avoir memleak
[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         final Integer[] dims = figure.getAxesSize();
351         int width = dims[0];
352         int height = dims[1];
353
354         final Graphics2D g2d = exporter.getGraphics2D(width, height, null, params);
355         params.setParamsOnGraphics(g2d);
356
357         final 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                     if (size[0] != dims[0] || size[1] != dims[1]) {
370                         Graphics2D newg2d = exporter.getGraphics2D(size[0], size[1], null, params);
371                         params.setParamsOnGraphics(newg2d);
372                         canvas.setGraphics(newg2d, size[0], size[1]);
373                         dims[0] = size[0];
374                         dims[1] = size[1];
375
376                         g2d.dispose();
377                     }
378                 } else if (property == GraphicObjectProperties.__GO_ANTIALIASING__) {
379                     canvas.setAntiAliasingLevel(getFigure().getAntialiasing());
380                 }
381             }
382         };
383         visitor.setDrawingTools(canvas.getDrawingTools());
384         canvas.setMainDrawer(visitor);
385         visitorsToExp.put(visitor, exporter);
386     }
387
388     /**
389      * Get an exporter from a type
390      * @param type the exporter type.
391      * @return the corresponding exporter/
392      */
393     private static Exporter getExporter(TYPE type) {
394         switch (type) {
395             case PNG :
396                 return new PNGExporter();
397             case GIF :
398                 return new GIFExporter();
399             case JPEG :
400                 return new JPEGExporter();
401             case BMP :
402                 return new BMPExporter();
403             case PPM :
404                 return new PPMExporter();
405             case SVG :
406                 if (!svgLoaded) {
407                     ScilabCommonsUtils.loadOnUse(CLASSPATH_SVG_EXPORT_NAME);
408                     svgLoaded = true;
409                 }
410                 return new SVGExporter();
411             case PDF :
412                 loadPDF();
413                 return new PDFExporter();
414             case PS :
415                 loadPDF();
416                 return new PSExporter();
417             case EPS :
418                 loadPDF();
419                 return new EPSExporter();
420             default :
421                 break;
422         }
423
424         return null;
425     }
426
427     /**
428      * Load the PDF/PS/EPS dependencies
429      */
430     private static final void loadPDF() {
431         if (!pdfLoaded) {
432             ScilabCommonsUtils.loadOnUse(CLASSPATH_PDF_PS_EPS_EXPORT_NAME);
433             pdfLoaded = true;
434         }
435     }
436
437     /**
438      * Interface to export
439      */
440     private static abstract class Exporter {
441
442         protected File file;
443
444         /**
445          * @param width graphics width
446          * @param height graphisc height
447          * @param file the file
448          * @param params the export parameters
449          */
450         abstract Graphics2D getGraphics2D(int width, int height, File file, ExportParams params);
451
452         /**
453          * Write the file
454          */
455         abstract void write() throws IOException;
456
457         abstract void dispose();
458     }
459
460     /**
461      * PNG Exporter
462      */
463     private static class PNGExporter extends Exporter {
464
465         protected BufferedImage image;
466         protected Graphics2D g2d;
467         protected ExportParams params;
468
469         public PNGExporter() { }
470
471         public void setImage(File file, BufferedImage image, ExportParams params) {
472             this.file = file;
473             this.image = image;
474             this.params = params;
475         }
476
477         @Override
478         public Graphics2D getGraphics2D(int width, int height, File file, ExportParams params) {
479             this.file = file;
480             this.params = params;
481             image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
482             g2d = image.createGraphics();
483
484             return g2d;
485         }
486
487         @Override
488         public void write() throws IOException {
489             ExportBitmap.writeFile(image, "png", file);
490         }
491
492         @Override
493         public void dispose() {
494             if (g2d != null) {
495                 g2d.dispose();
496             }
497         }
498     }
499
500     /**
501      * GIF Exporter
502      */
503     private static class GIFExporter extends PNGExporter {
504
505         public GIFExporter() { }
506
507         @Override
508         public void write() throws IOException {
509             ExportBitmap.writeFile(image, "gif", file);
510         }
511     }
512
513     /**
514      * BMP Exporter
515      */
516     private static class BMPExporter extends PNGExporter {
517
518         public BMPExporter() { }
519
520         @Override
521         public Graphics2D getGraphics2D(int width, int height, File file, ExportParams params) {
522             this.file = file;
523             this.params = params;
524             image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
525             g2d = image.createGraphics();
526
527             return g2d;
528         }
529
530         @Override
531         public void write() throws IOException {
532             ExportBitmap.writeFile(image, "bmp", file);
533         }
534     }
535
536     /**
537      * JPEG Exporter
538      */
539     private static class JPEGExporter extends BMPExporter {
540
541         public JPEGExporter() { }
542
543         @Override
544         public void write() throws IOException {
545             if (params.compressionQuality == -1) {
546                 ExportBitmap.writeJPEG(image, DEFAULT_JPEG_COMPRESSION, file);
547             } else {
548                 ExportBitmap.writeJPEG(image, params.compressionQuality, file);
549             }
550         }
551     }
552
553     /**
554      * PPM Exporter
555      */
556     private static class PPMExporter extends BMPExporter {
557
558         public PPMExporter() { }
559
560         @Override
561         public void write() throws IOException {
562             OutputStream out = new BufferedOutputStream(new FileOutputStream(file));
563             PPMEncoder encoder = new PPMEncoder(image, out);
564             int[] pixels = image.getRGB(0, 0, image.getWidth(), image.getHeight(), null, 0, image.getWidth());
565             encoder.encodeStart(image.getWidth(), image.getHeight());
566             encoder.encodePixels(0, 0, image.getWidth(), image.getHeight(), pixels, 0, image.getWidth());
567             out.flush();
568             out.close();
569         }
570     }
571
572     /**
573      * SVG Exporter
574      */
575     private static class SVGExporter extends Exporter {
576
577         private SVGGraphics2D g2d;
578         private ExportParams params;
579
580         public SVGExporter() { }
581
582         @Override
583         public Graphics2D getGraphics2D(int width, int height, File file, ExportParams params) {
584             this.file = file;
585             this.params = params;
586             DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation();
587             Document document = domImpl.createDocument("http://www.w3.org/2000/svg", "svg", null);
588             final SVGGeneratorContext ctx = SVGGeneratorContext.createDefault(document);
589             ctx.setComment("Generated by Scilab with Batik SVG Generator");
590             // TODO: better handle of LaTeX fonts (should remove the 'true' below and include the font in the SVG)
591             // same thing for PDF & co...
592             ctx.setEmbeddedFontsOn(true);
593             g2d = new SVGGraphics2D(ctx, false) {
594
595                 @Override
596                 public void drawString(String s, float x, float y) {
597                     textAsShapes = getFont().getFontName().startsWith("jlm");
598                     super.drawString(s, x, y);
599                 }
600
601                 @Override
602                 public void drawString(AttributedCharacterIterator ati, float x, float y) {
603                     textAsShapes = getFont().getFontName().startsWith("jlm");
604                     super.drawString(ati, x, y);
605                 }
606             };
607             if (params.orientation == ExportParams.LANDSCAPE) {
608                 g2d.setSVGCanvasSize(new Dimension(height, width));
609                 AffineTransform transf = AffineTransform.getRotateInstance(Math.PI / 2);
610                 transf.preConcatenate(AffineTransform.getTranslateInstance(height, 0));
611                 g2d.setTransform(transf);
612             } else {
613                 g2d.setSVGCanvasSize(new Dimension(width, height));
614             }
615             return g2d;
616         }
617
618         @Override
619         public void write() throws IOException {
620             boolean useCSS = true;
621             OutputStream svgs = new BufferedOutputStream(new FileOutputStream(file));
622             Writer out = new OutputStreamWriter(svgs, "UTF-8");
623             g2d.stream(out, useCSS);
624             svgs.flush();
625             svgs.close();
626         }
627
628         @Override
629         public void dispose() {
630             if (g2d != null) {
631                 g2d.dispose();
632             }
633         }
634     }
635
636     /**
637      * PDF Exporter
638      */
639     private static class PDFExporter extends Exporter {
640
641         private OutputStream out;
642         private PDFDocumentGraphics2D g2d;
643         private ExportParams params;
644         private ByteArrayOutputStream buffer;
645
646         public PDFExporter() { }
647
648         @Override
649         public Graphics2D getGraphics2D(int width, int height, File file, ExportParams params) {
650             this.file = file;
651             this.params = params;
652             try {
653                 if (file == null) {
654                     buffer = new ByteArrayOutputStream();
655                     out = new BufferedOutputStream(buffer);
656                 } else {
657                     out = new BufferedOutputStream(new FileOutputStream(file));
658                 }
659                 g2d = new PDFDocumentGraphics2D(true);
660                 g2d.setupDefaultFontInfo();
661                 g2d.getPDFDocument().getInfo().setProducer("Generated by Scilab with Apache FOP Version " + Version.getVersion());
662                 g2d.setGraphicContext(new GraphicContext());
663                 if (params.orientation == ExportParams.LANDSCAPE) {
664                     g2d.setupDocument(out, height, width);
665                     g2d.setSVGDimension(height, width);
666                     double s = PDFDocumentGraphics2D.NORMAL_PDF_RESOLUTION / g2d.getDeviceDPI();
667                     AffineTransform transf = AffineTransform.getRotateInstance(Math.PI / 2);
668                     transf.preConcatenate(AffineTransform.getTranslateInstance(height / s, 0));
669                     g2d.setTransform(transf);
670                 } else {
671                     g2d.setupDocument(out, width, height);
672                     g2d.setSVGDimension(width, height);
673                 }
674             } catch (IOException e) { }
675
676             return g2d;
677         }
678
679         @Override
680         public void write() throws IOException {
681             if (g2d != null) {
682                 g2d.finish();
683             }
684             if (buffer != null && file != null) {
685                 FileOutputStream fos = new FileOutputStream(file);
686                 buffer.writeTo(fos);
687                 buffer.close();
688                 fos.flush();
689                 fos.close();
690             }
691             if (out != null) {
692                 out.close();
693             }
694         }
695
696         @Override
697         public void dispose() {
698             g2d.dispose();
699         }
700     }
701
702     /**
703      * PS Exporter
704      */
705     private static class PSExporter extends Exporter {
706
707         protected OutputStream out;
708         protected AbstractPSDocumentGraphics2D g2d;
709         protected ExportParams params;
710         protected ByteArrayOutputStream buffer;
711
712         public PSExporter() { }
713
714         @Override
715         public Graphics2D getGraphics2D(int width, int height, File file, final ExportParams params) {
716             this.file = file;
717             this.params = params;
718             try {
719                 if (file == null) {
720                     buffer = new ByteArrayOutputStream();
721                     out = new BufferedOutputStream(buffer);
722                 } else {
723                     out = new BufferedOutputStream(new FileOutputStream(file));
724                 }
725                 g2d = new PSDocumentGraphics2D(true, out, width, height) {
726                     @Override
727                     protected void writePageHeader() throws IOException {
728                         super.writePageHeader();
729                         if (params.orientation == ExportParams.LANDSCAPE) {
730                             gen.writeDSCComment(DSCConstants.PAGE_ORIENTATION, "Landscape");
731                         } else {
732                             gen.writeDSCComment(DSCConstants.PAGE_ORIENTATION, "Portrait");
733                         }
734                         gen.writeln("/ReEncode { /MyEncoding exch def exch findfont dup length dict begin {def} forall /Encoding MyEncoding def currentdict end definefont } def");
735                         gen.writeln("/Helvetica /HelveticaLatin1 ISOLatin1Encoding ReEncode");
736                         gen.writeln("/Times /TimesLatin1 ISOLatin1Encoding ReEncode");
737                     }
738
739                     @Override
740                     public void drawString(String s, float x, float y) {
741                         if (s != null && !s.isEmpty()) {
742                             CharsetEncoder encoder = Charset.forName("ISO-8859-1").newEncoder();
743                             if (encoder.canEncode(s)) {
744                                 Font font = getFont();
745                                 boolean sserif = font.getName().equals("SansSerif");
746                                 boolean serif = font.getName().equals("Serif");
747                                 if (sserif || serif) {
748                                     try {
749                                         preparePainting();
750                                         establishColor(getColor());
751                                         gen.writeln((sserif ? "/HelveticaLatin1" : "/TimesLatin1") + " " + gen.formatDouble(getFont().getSize()) + " F");
752
753                                         gen.saveGraphicsState();
754                                         Shape imclip = getClip();
755                                         writeClip(imclip);
756
757                                         AffineTransform trans = getTransform();
758                                         boolean newTransform = gen.getCurrentState().checkTransform(trans) && !trans.isIdentity();
759
760                                         if (newTransform) {
761                                             gen.concatMatrix(trans);
762                                         }
763
764                                         gen.writeln(gen.formatDouble(x)
765                                                     + " " + gen.formatDouble(y)
766                                                     + " M 1 -1 scale");
767
768                                         StringBuffer buf = new StringBuffer("(");
769                                         for (int i = 0; i < s.length(); i++) {
770                                             PSGenerator.escapeChar(s.charAt(i), buf);
771                                         }
772                                         buf.append(") t");
773
774                                         gen.writeln(buf.toString());
775
776                                         gen.restoreGraphicsState();
777                                     } catch (IOException e) {
778                                         System.err.println(e);
779                                     }
780
781                                     return;
782                                 }
783                             }
784
785                             super.drawString(s, x, y);
786                         }
787                     }
788
789                     @Override
790                     public int processShape(Shape s) throws IOException {
791                         if (s instanceof Ellipse2D.Double) {
792                             Ellipse2D.Double ell = (Ellipse2D.Double) s;
793                             if (ell.height == ell.width) {
794                                 gen.writeln(gen.formatDouble(ell.x + ell.width / 2)
795                                             + " " + gen.formatDouble(ell.y + ell.height / 2)
796                                             + " " + gen.formatDouble(ell.width / 2)
797                                             + " " + gen.formatDouble(0d)
798                                             + " " + gen.formatDouble(360d)
799                                             + " arc cp");
800
801                                 return PathIterator.WIND_NON_ZERO;
802                             }
803                         }
804
805                         return super.processShape(s);
806                     }
807                 };
808                 g2d.setGraphicContext(new GraphicContext());
809             } catch (IOException e) { }
810
811             return g2d;
812         }
813
814         @Override
815         public void write() throws IOException {
816             if (g2d != null) {
817                 g2d.finish();
818             }
819             if (buffer != null && file != null) {
820                 FileOutputStream fos = new FileOutputStream(file);
821                 buffer.writeTo(fos);
822                 buffer.close();
823                 fos.flush();
824                 fos.close();
825             }
826             if (out != null) {
827                 out.close();
828             }
829         }
830
831         @Override
832         public void dispose() {
833             if (g2d != null) {
834                 g2d.dispose();
835             }
836         }
837     }
838
839     /**
840      * EPS Exporter
841      */
842     private static class EPSExporter extends PSExporter {
843
844         public EPSExporter() { }
845
846         @Override
847         public Graphics2D getGraphics2D(int width, int height, File file, final ExportParams params) {
848             this.file = file;
849             this.params = params;
850             try {
851                 if (file == null) {
852                     buffer = new ByteArrayOutputStream();
853                     out = new BufferedOutputStream(buffer);
854                 } else {
855                     out = new BufferedOutputStream(new FileOutputStream(file));
856                 }
857                 g2d = new EPSDocumentGraphics2D(true) {
858                     @Override
859                     protected void writePageHeader() throws IOException {
860                         super.writePageHeader();
861                         if (params.orientation == ExportParams.LANDSCAPE) {
862                             gen.writeDSCComment(DSCConstants.PAGE_ORIENTATION, "Landscape");
863                         } else {
864                             gen.writeDSCComment(DSCConstants.PAGE_ORIENTATION, "Portrait");
865                         }
866                         gen.writeln("/ReEncode { /MyEncoding exch def exch findfont dup length dict begin {def} forall /Encoding MyEncoding def currentdict end definefont } def");
867                         gen.writeln("/Helvetica /HelveticaLatin1 ISOLatin1Encoding ReEncode");
868                         gen.writeln("/Times /TimesLatin1 ISOLatin1Encoding ReEncode");
869                     }
870
871                     @Override
872                     public void drawString(String s, float x, float y) {
873                         if (s != null && !s.isEmpty()) {
874                             CharsetEncoder encoder = Charset.forName("ISO-8859-1").newEncoder();
875                             if (encoder.canEncode(s)) {
876                                 Font font = getFont();
877                                 boolean sserif = font.getName().equals("SansSerif");
878                                 boolean serif = font.getName().equals("Serif");
879                                 if (sserif || serif) {
880                                     try {
881                                         preparePainting();
882                                         establishColor(getColor());
883                                         gen.writeln((sserif ? "/HelveticaLatin1" : "/TimesLatin1") + " " + gen.formatDouble(getFont().getSize()) + " F");
884
885                                         gen.saveGraphicsState();
886                                         Shape imclip = getClip();
887                                         writeClip(imclip);
888
889                                         AffineTransform trans = getTransform();
890                                         boolean newTransform = gen.getCurrentState().checkTransform(trans) && !trans.isIdentity();
891
892                                         if (newTransform) {
893                                             gen.concatMatrix(trans);
894                                         }
895
896                                         gen.writeln(gen.formatDouble(x)
897                                                     + " " + gen.formatDouble(y)
898                                                     + " M 1 -1 scale");
899
900                                         StringBuffer buf = new StringBuffer("(");
901                                         for (int i = 0; i < s.length(); i++) {
902                                             PSGenerator.escapeChar(s.charAt(i), buf);
903                                         }
904                                         buf.append(") t");
905
906                                         gen.writeln(buf.toString());
907
908                                         gen.restoreGraphicsState();
909                                     } catch (IOException e) {
910                                         System.err.println(e);
911                                     }
912
913                                     return;
914                                 }
915                             }
916
917                             super.drawString(s, x, y);
918                         }
919                     }
920
921                     @Override
922                     public int processShape(Shape s) throws IOException {
923                         if (s instanceof Ellipse2D.Double) {
924                             Ellipse2D.Double ell = (Ellipse2D.Double) s;
925                             if (ell.height == ell.width) {
926                                 gen.writeln(gen.formatDouble(ell.x + ell.width / 2)
927                                             + " " + gen.formatDouble(ell.y + ell.height / 2)
928                                             + " " + gen.formatDouble(ell.width / 2)
929                                             + " " + gen.formatDouble(0d)
930                                             + " " + gen.formatDouble(360d)
931                                             + " arc cp");
932
933                                 return PathIterator.WIND_NON_ZERO;
934                             }
935                         }
936
937                         return super.processShape(s);
938                     }
939
940                 };
941                 g2d.setupDocument(out, width, height);
942                 g2d.setGraphicContext(new GraphicContext());
943             } catch (IOException e) { }
944
945             return g2d;
946         }
947     }
948 }