001/* ===========================================================
002 * JFreeChart : a free chart library for the Java(tm) platform
003 * ===========================================================
004 *
005 * (C) Copyright 2000-2020, by Object Refinery Limited and Contributors.
006 *
007 * Project Info:  http://www.jfree.org/jfreechart/index.html
008 *
009 * This library is free software; you can redistribute it and/or modify it
010 * under the terms of the GNU Lesser General Public License as published by
011 * the Free Software Foundation; either version 2.1 of the License, or
012 * (at your option) any later version.
013 *
014 * This library is distributed in the hope that it will be useful, but
015 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
016 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
017 * License for more details.
018 *
019 * You should have received a copy of the GNU Lesser General Public
020 * License along with this library; if not, write to the Free Software
021 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
022 * USA.
023 *
024 * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. 
025 * Other names may be trademarks of their respective owners.]
026 *
027 * ----------------
028 * ExportUtils.java
029 * ----------------
030 * (C) Copyright 2014-2020 by Object Refinery Limited and Contributors.
031 *
032 * Original Author:  David Gilbert (for Object Refinery Limited);
033 * Contributor(s):   -;
034 *
035 */
036
037package org.jfree.chart.util;
038
039import java.awt.Graphics2D;
040import java.awt.Rectangle;
041import java.awt.geom.Rectangle2D;
042import java.awt.image.BufferedImage;
043import java.io.BufferedOutputStream;
044import java.io.File;
045import java.io.FileNotFoundException;
046import java.io.FileOutputStream;
047import java.io.IOException;
048import java.io.OutputStream;
049import java.lang.reflect.Constructor;
050import java.lang.reflect.InvocationTargetException;
051import java.lang.reflect.Method;
052import javax.imageio.ImageIO;
053import org.jfree.chart.ui.Drawable;
054
055/**
056 * Utility functions for exporting charts to SVG and PDF format.
057 * 
058 * @since 1.0.18
059 */
060public class ExportUtils {
061
062    /**
063     * Returns {@code true} if JFreeSVG is on the classpath, and 
064     * {@code false} otherwise.  The JFreeSVG library can be found at
065     * http://www.jfree.org/jfreesvg/
066     * 
067     * @return A boolean.
068     */
069    public static boolean isJFreeSVGAvailable() {
070        Class<?> svgClass = null;
071        try {
072            svgClass = Class.forName("org.jfree.graphics2d.svg.SVGGraphics2D");
073        } catch (ClassNotFoundException e) {
074            // svgClass will be null so the function will return false
075        }
076        return (svgClass != null);
077    }
078
079    /**
080     * Returns {@code true} if OrsonPDF is on the classpath, and 
081     * {@code false} otherwise.  The OrsonPDF library can be found at
082     * http://www.object-refinery.com/orsonpdf/
083     * 
084     * @return A boolean.
085     */
086    public static boolean isOrsonPDFAvailable() {
087        Class<?> pdfDocumentClass = null;
088        try {
089            pdfDocumentClass = Class.forName("com.orsonpdf.PDFDocument");
090        } catch (ClassNotFoundException e) {
091            // pdfDocumentClass will be null so the function will return false
092        }
093        return (pdfDocumentClass != null);
094    }
095
096    /**
097     * Writes the current content to the specified file in SVG format.  This 
098     * will only work when the JFreeSVG library is found on the classpath.
099     * Reflection is used to ensure there is no compile-time dependency on
100     * JFreeSVG.
101     * 
102     * @param drawable  the drawable ({@code null} not permitted).
103     * @param w  the chart width.
104     * @param h  the chart height.
105     * @param file  the output file ({@code null} not permitted).
106     */
107    public static void writeAsSVG(Drawable drawable, int w, int h, 
108            File file) {
109        if (!ExportUtils.isJFreeSVGAvailable()) {
110            throw new IllegalStateException(
111                    "JFreeSVG is not present on the classpath.");
112        }
113        Args.nullNotPermitted(drawable, "drawable");
114        Args.nullNotPermitted(file, "file");
115        try {
116            Class<?> svg2Class = Class.forName(
117                    "org.jfree.graphics2d.svg.SVGGraphics2D");
118            Constructor<?> c1 = svg2Class.getConstructor(int.class, int.class);
119            Graphics2D svg2 = (Graphics2D) c1.newInstance(w, h);
120            Rectangle2D drawArea = new Rectangle2D.Double(0, 0, w, h);
121            drawable.draw(svg2, drawArea);
122            Class<?> svgUtilsClass = Class.forName(
123                    "org.jfree.graphics2d.svg.SVGUtils");
124            Method m1 = svg2Class.getMethod("getSVGElement", (Class[]) null);
125            String element = (String) m1.invoke(svg2, (Object[]) null);
126            Method m2 = svgUtilsClass.getMethod("writeToSVG", File.class, 
127                    String.class);
128            m2.invoke(svgUtilsClass, file, element);
129        } catch (ClassNotFoundException ex) {
130            throw new RuntimeException(ex);
131        } catch (InstantiationException ex) {
132            throw new RuntimeException(ex);
133        } catch (IllegalAccessException ex) {
134            throw new RuntimeException(ex);
135        } catch (NoSuchMethodException ex) {
136            throw new RuntimeException(ex);
137        } catch (SecurityException ex) {
138            throw new RuntimeException(ex);
139        } catch (IllegalArgumentException ex) {
140            throw new RuntimeException(ex);
141        } catch (InvocationTargetException ex) {
142            throw new RuntimeException(ex);
143        }
144    }
145
146    /**
147     * Writes a {@link Drawable} to the specified file in PDF format.  This 
148     * will only work when the OrsonPDF library is found on the classpath.
149     * Reflection is used to ensure there is no compile-time dependency on
150     * OrsonPDF.
151     * 
152     * @param drawable  the drawable ({@code null} not permitted).
153     * @param w  the chart width.
154     * @param h  the chart height.
155     * @param file  the output file ({@code null} not permitted).
156     */
157    public static final void writeAsPDF(Drawable drawable, 
158            int w, int h, File file) {
159        if (!ExportUtils.isOrsonPDFAvailable()) {
160            throw new IllegalStateException(
161                    "OrsonPDF is not present on the classpath.");
162        }
163        Args.nullNotPermitted(drawable, "drawable");
164        Args.nullNotPermitted(file, "file");
165        try {
166            Class<?> pdfDocClass = Class.forName("com.orsonpdf.PDFDocument");
167            Object pdfDoc = pdfDocClass.newInstance();
168            Method m = pdfDocClass.getMethod("createPage", Rectangle2D.class);
169            Rectangle2D rect = new Rectangle(w, h);
170            Object page = m.invoke(pdfDoc, rect);
171            Method m2 = page.getClass().getMethod("getGraphics2D");
172            Graphics2D g2 = (Graphics2D) m2.invoke(page);
173            Rectangle2D drawArea = new Rectangle2D.Double(0, 0, w, h);
174            drawable.draw(g2, drawArea);
175            Method m3 = pdfDocClass.getMethod("writeToFile", File.class);
176            m3.invoke(pdfDoc, file);
177        } catch (ClassNotFoundException ex) {
178            throw new RuntimeException(ex);
179        } catch (InstantiationException ex) {
180            throw new RuntimeException(ex);
181        } catch (IllegalAccessException ex) {
182            throw new RuntimeException(ex);
183        } catch (NoSuchMethodException ex) {
184            throw new RuntimeException(ex);
185        } catch (SecurityException ex) {
186            throw new RuntimeException(ex);
187        } catch (IllegalArgumentException ex) {
188            throw new RuntimeException(ex);
189        } catch (InvocationTargetException ex) {
190            throw new RuntimeException(ex);
191        }
192    }
193    
194    /**
195     * Writes the current content to the specified file in PNG format.
196     * 
197     * @param drawable  the drawable ({@code null} not permitted).
198     * @param w  the chart width.
199     * @param h  the chart height.
200     * @param file  the output file ({@code null} not permitted).
201     * 
202     * @throws FileNotFoundException if the file is not found.
203     * @throws IOException if there is an I/O problem.
204     */
205    public static void writeAsPNG(Drawable drawable, int w, int h, 
206            File file) throws FileNotFoundException, IOException {
207        BufferedImage image = new BufferedImage(w, h, 
208                BufferedImage.TYPE_INT_ARGB);
209        Graphics2D g2 = image.createGraphics();
210        drawable.draw(g2, new Rectangle(w, h));
211        OutputStream out = new BufferedOutputStream(new FileOutputStream(file));
212        try {
213            ImageIO.write(image, "png", out);
214        }
215        finally {
216            out.close();
217        }
218    }
219
220    /**
221     * Writes the current content to the specified file in JPEG format.
222     * 
223     * @param drawable  the drawable ({@code null} not permitted).
224     * @param w  the chart width.
225     * @param h  the chart height.
226     * @param file  the output file ({@code null} not permitted).
227     * 
228     * @throws FileNotFoundException if the file is not found.
229     * @throws IOException if there is an I/O problem.
230     */
231    public static void writeAsJPEG(Drawable drawable, int w, int h, 
232            File file) throws FileNotFoundException, IOException {
233        BufferedImage image = new BufferedImage(w, h, 
234                BufferedImage.TYPE_INT_RGB);
235        Graphics2D g2 = image.createGraphics();
236        drawable.draw(g2, new Rectangle(w, h));
237        OutputStream out = new BufferedOutputStream(new FileOutputStream(file));
238        try {
239            ImageIO.write(image, "jpg", out);
240        }
241        finally {
242            out.close();
243        }
244    }
245 
246}