Java tutorial
/******************************************************************************* * Copyright (c) 2010-2012 by Min Cai (min.cai.china@gmail.com). * * This file is part of the Archimulator multicore architectural simulator. * * Archimulator is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Archimulator is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Archimulator. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package net.pickapack.chart; import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Rectangle; import com.itextpdf.awt.DefaultFontMapper; import com.itextpdf.text.pdf.PdfContentByte; import com.itextpdf.text.pdf.PdfTemplate; import com.itextpdf.text.pdf.PdfWriter; import org.jfree.chart.JFreeChart; import java.awt.*; import java.awt.geom.Rectangle2D; import java.io.FileNotFoundException; import java.io.FileOutputStream; /** * Chart to PDF exporter. * * @author Min Cai */ public class ChartPdfExporter { /** * Export the specified chart to the specified PDF file. * * @param chart the chart * @param width the width of the PDF file * @param height the height of the PDF file * @param fileName the PDF file name */ public static void exportPdf(JFreeChart chart, int width, int height, String fileName) { try { Document document = new Document(new Rectangle(width, height)); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(fileName)); document.open(); PdfContentByte cb = writer.getDirectContent(); PdfTemplate tp = cb.createTemplate(width, height); Graphics2D g2d = tp.createGraphics(width, height, new DefaultFontMapper()); Rectangle2D r2d = new Rectangle2D.Double(0, 0, width, height); chart.draw(g2d, r2d); g2d.dispose(); cb.addTemplate(tp, 0, 0); document.close(); } catch (DocumentException e) { throw new RuntimeException(e); } catch (FileNotFoundException e) { throw new RuntimeException(e); } } }