Example usage for com.lowagie.text.pdf DefaultFontMapper DefaultFontMapper

List of usage examples for com.lowagie.text.pdf DefaultFontMapper DefaultFontMapper

Introduction

In this page you can find the example usage for com.lowagie.text.pdf DefaultFontMapper DefaultFontMapper.

Prototype

DefaultFontMapper

Source Link

Usage

From source file:at.granul.mason.collector.ChartFileScalarDataWriter.java

License:Open Source License

public static void exportGraph(XYChartGenerator chart, String prefix, int width, int height) {
    try {/*from  ww  w  .j  a  v a  2s .c om*/
        Document document = new Document(new com.lowagie.text.Rectangle(width, height));

        PdfWriter writer = PdfWriter.getInstance(document,
                new FileOutputStream(new File(prefix + "_" + DataWriter.DF.format(new Date()) + ".pdf")));

        document.addAuthor("MASON");
        document.open();
        PdfContentByte cb = writer.getDirectContent();
        //PdfTemplate tp = cb.createTemplate(width, height);

        //Write the chart with all datasets
        chart.addLegend();
        /*LegendTitle title = new LegendTitle(chart.getChart().getPlot());
        title.setLegendItemGraphicPadding(new org.jfree.ui.RectangleInsets(0,8,0,4));
        chart.addLegend(title);*/
        LegendTitle legendTitle = chart.getChart().getLegend();
        legendTitle.setPosition(RectangleEdge.BOTTOM);

        Graphics2D g2 = cb.createGraphics(width, height, new DefaultFontMapper());
        Rectangle2D rectangle2D = new Rectangle2D.Double(0, 0, width, height);
        chart.getChart().draw(g2, rectangle2D);
        g2.dispose();

        //PNG Output
        ChartUtilities.saveChartAsJPEG(new File(prefix + "_" + DataWriter.DF.format(new Date()) + ".png"),
                chart.getChart(), width, height);

        chart.getChart().removeLegend();
        //tp = cb.createTemplate(width, height);

        //All invisible
        final XYItemRenderer renderer = chart.getChartPanel().getChart().getXYPlot().getRenderer();
        for (int a = 0; a < chart.getSeriesCount(); a++) {
            renderer.setSeriesVisible(a, false);
        }

        final Dataset seriesDataset = chart.getSeriesDataset();
        XYSeriesCollection series = ((XYSeriesCollection) seriesDataset);
        for (int a = 0; a < chart.getSeriesCount(); a++) {
            renderer.setSeriesVisible(a, true);
            final String seriesName = series.getSeries(a).getKey() + "";
            chart.setYAxisLabel(seriesName);
            document.newPage();
            g2 = cb.createGraphics(width, height * (a + 2), new DefaultFontMapper());
            g2.translate(0, height * (a + 1));
            chart.getChart().draw(g2, rectangle2D);
            g2.dispose();

            //PNG Output
            ChartUtilities.saveChartAsJPEG(
                    new File(prefix + "_" + seriesName + DataWriter.DF.format(new Date()) + ".png"),
                    chart.getChart(), width, height);

            renderer.setSeriesVisible(a, false);
        }
        //cb.addTemplate(tp, 0, 0);

        document.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:clusterMaker.treeview.dendroview.GraphicsExportPanel.java

License:Open Source License

private void pdfSave(String format) {
    com.lowagie.text.Rectangle pageSize = PageSize.LETTER;
    Document document = new Document(pageSize);
    try {//from   w ww . j  av  a  2 s.  c om
        OutputStream output = new BufferedOutputStream(new FileOutputStream(getFile()));
        PdfWriter writer = PdfWriter.getInstance(document, output);
        document.open();
        PdfContentByte cb = writer.getDirectContent();
        Graphics2D g = cb.createGraphics(pageSize.getWidth(), pageSize.getHeight(), new DefaultFontMapper());

        double imageScale = Math.min(pageSize.getWidth() / ((double) estimateWidth() + getBorderPixels()),
                pageSize.getHeight() / ((double) estimateHeight() + getBorderPixels()));
        g.scale(imageScale, imageScale);
        drawAll(g, 1.0);
        g.dispose();
    } catch (Exception e) {
        JOptionPane.showMessageDialog(this, new JTextArea("Dendrogram export had problem " + e));
        logger.error("Exception " + e);
        // e.printStackTrace();
    }

    document.close();
}

From source file:com.bayareasoftware.chartengine.chart.jfree.JFreeChartDriver.java

License:Apache License

/**
 * main entry point for creating charts,  given a ChartInfo, create a chart and return it.  Does not cache the chart
 * //from w  w  w .java2 s .co m
 * @param ci        ChartInfo that describes the UI properties for the chart
 * @param logo      logo for this chart (if null, use default logo)
 * @param sMap      the map of descriptor sid's to DataStream that supply all the data for the chart series and markers
 * @param template  Template of default properties,  can be null
 * @param ret       an optional ChartResult can be passed in to guide the creation of the object.
 *                  the dimensions (width/height) in the ChartResult override the dimensions in the ChartInfo  
 *                  If the ChartResult has filePaths set, then those files will be use to materialize
 *                  the image, thumbnail, and image maps on disk
 *                  if not the, the data will be kept inline in the ChartResult
 *                  if res is null, then a new ChartResult is created and data will be kept in that object
 * @return          the ChartResult
 * @throws          rethrows any exception raised during chart creation.  but if the ChartResult passed in has  isShowErrorImage() set then
 *                  the exception is converted into a chart image and returned instead of being re-thrown
 */
public ChartResult create(ChartInfo ci, LogoInfo logo, Map<Integer, DataStream> sMap, SimpleProps template,
        ChartResult ret) throws Exception {

    try {
        if (ret == null)
            ret = new ChartResult();

        long start, now;

        // how long does it take to do various stages
        long queryTime, createTime, persistTime, logoTime, imageTime, vectorTime, thumbnailTime;

        int WIDTH = ret.getWidth() > 0 ? ret.getWidth() : ci.getWidth();
        WIDTH = Math.min(WIDTH, MAX_WIDTH);
        int HEIGHT = ret.getHeight() > 0 ? ret.getHeight() : ci.getHeight();
        HEIGHT = Math.min(HEIGHT, MAX_HEIGHT);
        ret.setSize(WIDTH, HEIGHT);
        ret.setPlotType(ci.getPlotType());
        start = System.currentTimeMillis();
        long createStart = start;

        // ====== Step 1: create the necessary data sets
        ChartContext ctxt = new ChartContext(ci, sMap);

        //getData(ctxt);

        now = System.currentTimeMillis();
        queryTime = now - start;
        start = now;

        ret.colorMap = new HashMap<Integer, String>();
        // ====== Step 2: create the actual JFreeChart
        // using the ChartBundle and the dsMap
        //JFreeChart chart = createChart(ci, template, dsMap, markerValues);
        JFreeChart chart = createChart(ci, template, ctxt, ret.colorMap);

        //            if (ret.colorMap != null) {
        //                log.warn("*############################ colorMap ########################");
        //                for (Integer k : ret.colorMap.keySet()) {
        //                    log.warn("colorMap(" + k + ") = " + ret.colorMap.get(k));
        //                }
        //            }

        now = System.currentTimeMillis();
        createTime = now - start;
        start = now;

        // ====== Step 3: add ChartMechanic logo to the chart
        //  TODO: add other fixtures like ads, etc.

        ChartLogo chartLogo = defaultLogo;
        if (logo != null) {
            chartLogo = logoCache.get(logo);
            //System.err.println("*******************logoCache.get(" + logo + ") returned = " + chartLogo);
            if (chartLogo == null) {
                chartLogo = logoinfo2chartlogo(logo);
                //System.err.println("*******************logoinfo2chartlogo(" + logo + ") returned = " + chartLogo);
                logoCache.put(logo, chartLogo);
            }
        }

        addLogo(ci, chart, WIDTH, HEIGHT, chartLogo);

        now = System.currentTimeMillis();
        logoTime = now - start;
        start = now;

        ChartRenderingInfo cri = new ChartRenderingInfo();
        ChartDiskResult diskResult = ret.getDiskResult();
        // ====== Step 4: generate the full image 
        // either as raw PNGdata or to a file as specified in the ChartResult 
        BufferedImage bi = chart.createBufferedImage(WIDTH, HEIGHT, cri);
        // record geometry of various regions of the chart into the
        // chart result...
        EntityCollection ecoll = cri.getEntityCollection();
        if (ecoll != null && ecoll.getEntityCount() > 0) {
            int ecount = ecoll.getEntityCount();
            TextTitle title = chart.getTitle();
            // the first entity is the entire chart itself
            int r = 1;
            if (title != null) {
                String s = title.getText();
                if (s != null && !s.trim().equals("") && r < ecount) {
                    // the 2nd entity is the title as long as it's not
                    // null
                    ChartEntity ce = ecoll.getEntity(r);
                    if (isTitleEntity(ce)) {
                        Rectangle re = makeRect(ce);
                        ret.setTitleRect(re);
                    }
                    r++;
                }
            }

            if (chart.getSubtitleCount() > 0) {
                // the next entity is the subtitle (either the first or
                // second entry depending on whether there is a title
                String desc = ci.getDescription();
                if (desc != null && !desc.trim().equals("") && r < ecount) {
                    ChartEntity ce = ecoll.getEntity(r);
                    if (isTitleEntity(ce)) {
                        Rectangle re = makeRect(ce);
                        ret.setSubtitleRect(re);
                    }
                }
            }
            /*
             * for (int i = 0; i < ecoll.getEntityCount(); i++) {
             * ChartEntity ce = ecoll.getEntity(i); System.out.println(
             * "[JFreeDriver] entity #" + i + " =" + ce.getClass().getName()
             * + " coords=" + ce.getShapeCoords()); }
             */
        }

        now = System.currentTimeMillis();
        imageTime = now - start;
        start = now;

        if (diskResult.hasImagePath()) {
            writeImageAsPNG(bi, diskResult.getImagePath());
        }
        // step 4.1: record plot geometry
        {
            PlotRenderingInfo pri = cri.getPlotInfo();
            ret.setPlotRect(makeRect(pri.getPlotArea()));
            ret.setPlotDataRect(makeRect(pri.getDataArea()));
        }

        now = System.currentTimeMillis();
        persistTime = now - start;
        start = now;

        // ====== Step 4a: generate a vector file (e.g. pdf) if necessary
        // 
        if (diskResult.isGeneratePDF()) {
            if (diskResult.hasPdfPath()) {
                OutputStream out = null;
                try {
                    out = new FileOutputStream(new File(diskResult.getPdfPath()));
                    writeChartAsPDF(out, chart, WIDTH, HEIGHT, new DefaultFontMapper());
                } finally {
                    if (out != null)
                        out.close();
                }
            }
        } else if (diskResult.isGeneratePS()) {
            if (diskResult.hasPSPath()) {
                OutputStream out = null;
                try {
                    out = new FileOutputStream(new File(diskResult.getPSPath()));
                    writeChartAsPS(out, chart, WIDTH, HEIGHT);
                } finally {
                    if (out != null)
                        out.close();
                }
            }
        } else if (diskResult.isGenerateEMF()) {
            if (diskResult.hasEMFPath()) {
                OutputStream out = null;
                try {
                    out = new FileOutputStream(new File(diskResult.getEMFPath()));
                    writeChartAsEMF(out, chart, WIDTH, HEIGHT);
                } finally {
                    if (out != null)
                        out.close();
                }
            }
        }
        now = System.currentTimeMillis();
        vectorTime = now - start;
        start = now;

        // ====== Step 5: generate the thumbnail (if necessary)
        // either as raw PNGdata or to a file as specified in the ChartResult
        if (diskResult.isGenerateThumbnail()) {
            BufferedImage thumbnail = createThumbnail(chart, cri);
            if (diskResult.hasThumbPath()) {
                writeImageAsPNG(thumbnail, diskResult.getThumbPath());
            }
        }

        now = System.currentTimeMillis();
        thumbnailTime = now - start;
        start = now;

        // ====== Step 6: generate the imageMap (if necessary)
        if (diskResult.isGenerateImageMap()) {
            URLTagFragmentGenerator utag = new StandardURLTagFragmentGenerator();
            ToolTipTagFragmentGenerator ttgen = new StandardToolTipTagFragmentGenerator();
            String imapId = diskResult.getImageMapId();
            String imap = ImageMapUtilities.getImageMap(imapId, cri, ttgen, utag);
            if (diskResult.hasImageMapPath()) {
                FileUtil.writeString(new File(diskResult.getImageMapPath()), imap);
            }
            //                else {
            //                    diskResult.setImageMap(imap);
            //                }
        }

        // === Step 7: record axis ranges
        {
            Range range;
            Plot plot = chart.getPlot();
            if (plot instanceof XYPlot) {
                XYPlot xyp = (XYPlot) plot;
                ValueAxis domain = xyp.getDomainAxis();
                range = domain.getRange();
                ret.setAxisRange(0, range.getLowerBound(), range.getUpperBound());
                for (int i = 0; i < xyp.getRangeAxisCount(); i++) {
                    ValueAxis va = xyp.getRangeAxis(i);
                    if (va == null) {
                        // range axis may not exist
                        continue;
                    }
                    range = va.getRange();
                    double lower = range.getLowerBound();
                    double upper = range.getUpperBound();
                    //p("rangeAxis[" + i + "] lower=" + lower + " upper=" + upper);
                    ret.setAxisRange(i + 1, lower, upper);
                }
            } else if (plot instanceof CategoryPlot) {
                CategoryPlot cplot = (CategoryPlot) plot;
                for (int i = 0; i < cplot.getRangeAxisCount(); i++) {
                    ValueAxis va = cplot.getRangeAxis(i);
                    if (va == null) {
                        // range axis may not exist
                        continue;
                    }
                    range = va.getRange();
                    ret.setAxisRange(i + 1, range.getLowerBound(), range.getUpperBound());
                }
            }
        }

        if (log.isDebugEnabled()) {
            log.debug("created chart: id=" + ci.getId() + "/' in " + (System.currentTimeMillis() - createStart)
                    + " ms." + " create time= " + createTime + " query time=" + queryTime + " image time = "
                    + imageTime + " logo time = " + imageTime + " persist time =" + persistTime
                    + " vector time = " + vectorTime + " thumbnail time = " + thumbnailTime);
        }
        ret.setQueryTime(queryTime);
        ret.setCreateTime(createTime);
        ret.setPersistTime(persistTime);
        return ret;
    } catch (Exception e) {
        e.printStackTrace();
        if (ret.getDiskResult().isShowErrorImage()) {
            throwable2chart(ret, e);
            return ret;
        }
        throw e;
    }

}

From source file:com.centurylink.mdw.designer.pages.ExportHelper.java

License:Apache License

public void printImagePdf(String filename, DesignerCanvas canvas, Dimension graphsize) {
    try {/*  w w w.j  a v  a2  s .com*/
        DefaultFontMapper mapper = new DefaultFontMapper();
        FontFactory.registerDirectories();
        mapper.insertDirectory("c:\\winnt\\fonts");
        // mapper.insertDirectory("c:\\windows\\fonts");
        // we create a template and a Graphics2D object that corresponds
        // with it
        int margin = 72; // 1 inch
        float scale = 0.5f;
        boolean multiple_page = true;
        Rectangle page_size;
        if (multiple_page) {
            page_size = PageSize.LETTER.rotate();
        } else {
            page_size = new Rectangle((int) (graphsize.getWidth() * scale) + margin,
                    (int) (graphsize.getHeight() * scale) + margin);
        }
        Document document = new Document(page_size);
        DocWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
        document.open();
        document.setPageSize(page_size);
        int image_w = (int) page_size.getWidth() - margin;
        int image_h = (int) page_size.getHeight() - margin;
        boolean edsave = canvas.editable;
        canvas.editable = false;
        Color bgsave = canvas.getBackground();
        canvas.setBackground(Color.white);
        if (multiple_page) {
            int horizontal_pages = (int) (graphsize.width * scale) / image_w + 1;
            int vertical_pages = (int) (graphsize.height * scale) / image_h + 1;
            for (int i = 0; i < horizontal_pages; i++) {
                for (int j = 0; j < vertical_pages; j++) {
                    Image img;
                    PdfContentByte cb = ((PdfWriter) writer).getDirectContent();
                    PdfTemplate tp = cb.createTemplate(image_w, image_h);
                    Graphics2D g2 = tp.createGraphics(image_w, image_h, mapper);
                    tp.setWidth(image_w);
                    tp.setHeight(image_h);
                    g2.scale(scale, scale);
                    g2.translate(-i * image_w / scale, -j * image_h / scale);
                    canvas.paintComponent(g2);
                    g2.dispose();
                    img = new ImgTemplate(tp);
                    document.add(img);
                }
            }
        } else {
            Image img;
            PdfContentByte cb = ((PdfWriter) writer).getDirectContent();
            PdfTemplate tp = cb.createTemplate(image_w, image_h);
            Graphics2D g2 = tp.createGraphics(image_w, image_h, mapper);
            tp.setWidth(image_w);
            tp.setHeight(image_h);
            g2.scale(scale, scale);
            canvas.paintComponent(g2);
            g2.dispose();
            img = new ImgTemplate(tp);
            document.add(img);
        }
        canvas.setBackground(bgsave);
        canvas.editable = edsave;
        document.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.centurylink.mdw.designer.pages.ExportHelper.java

License:Apache License

private void printGraphPdf(DocWriter writer, CanvasCommon canvas, Graph process, Rectangle page_size,
        String type, String filename, Chapter chapter, int chapter_number) throws Exception {
    Dimension graphsize = process.getGraphSize();
    // we create a fontMapper and read all the fonts in the font directory
    DefaultFontMapper mapper = new DefaultFontMapper();
    FontFactory.registerDirectories();/*from ww  w.j  a  v  a2s.  c  om*/
    mapper.insertDirectory("c:\\winnt\\fonts");
    // mapper.insertDirectory("c:\\windows\\fonts");
    // we create a template and a Graphics2D object that corresponds with it
    int w, h;
    float scale;
    if ((float) graphsize.width < page_size.getWidth() * 0.8
            && (float) graphsize.height < page_size.getHeight() * 0.8 || type.equals(HTML)) {
        w = graphsize.width + 36;
        h = graphsize.height + 36;
        scale = -1f;
    } else {
        scale = page_size.getWidth() * 0.8f / (float) graphsize.width;
        if (scale > page_size.getHeight() * 0.8f / (float) graphsize.height)
            scale = page_size.getHeight() * 0.8f / (float) graphsize.height;
        w = (int) (graphsize.width * scale) + 36;
        h = (int) (graphsize.height * scale) + 36;
    }
    Image img;
    int zoomSave = process.zoom;
    process.zoom = 100;
    Color bgsave = canvas.getBackground();
    boolean edsave = canvas.editable;
    canvas.editable = false;
    canvas.setBackground(Color.white);

    if (type.equals(PDF)) {
        PdfContentByte cb = ((PdfWriter) writer).getDirectContent();
        PdfTemplate tp = cb.createTemplate(w, h);
        Graphics2D g2 = tp.createGraphics(w, h, mapper);
        if (scale > 0)
            g2.scale(scale, scale);
        tp.setWidth(w);
        tp.setHeight(h);
        canvas.paintComponent(g2);
        g2.dispose();
        // cb.addTemplate(tp, 50, 400);
        img = new ImgTemplate(tp);
    } else {
        String imgfilename = filename + "." + process.getName() + "_ch" + chapter_number + ".jpg";
        printImage(imgfilename, -1f, canvas, graphsize);
        img = Image.getInstance(imgfilename);
        if (scale > 0)
            img.scalePercent(scale * 100);
    }
    process.zoom = zoomSave;
    canvas.setBackground(bgsave);
    canvas.editable = edsave;
    if (img != null)
        chapter.add(img);
}

From source file:com.exam.server.ConvertPDF.java

public static void addPieChart(JFreeChart chart, int width, int height, PdfWriter writer) {
    //          PdfWriter writer = null;

    //          Document document = new Document();

    try {//from ww w .  j ava 2  s .co  m
        //             writer = PdfWriter.getInstance(document, new FileOutputStream(
        //                   fileName));
        System.out.println("writing pie chart document ");
        //             document.open();
        PdfContentByte contentByte = writer.getDirectContent();
        PdfTemplate template = contentByte.createTemplate(width, height);
        Graphics2D graphics2d = template.createGraphics(width, height, new DefaultFontMapper());
        Rectangle2D rectangle2d = new Rectangle2D.Double(0, 0, width, height);

        chart.draw(graphics2d, rectangle2d);

        graphics2d.dispose();
        contentByte.addTemplate(template, 0, 0);

    } catch (Exception e) {
        e.printStackTrace();
    }
    System.out.println("writing done:: ");
}

From source file:com.rapidminer.gui.actions.export.ImageExporter.java

License:Open Source License

private void exportVectorGraphics(String formatName, File outputFile) throws ImageExportException {
    Component component = printableComponent.getExportComponent();
    int width = component.getWidth();
    int height = component.getHeight();
    try (FileOutputStream fs = new FileOutputStream(outputFile)) {
        switch (formatName) {
        case PDF:
            // create pdf document with slightly increased width and height
            // (otherwise the image gets cut off)
            Document document = new Document(new Rectangle(width + 5, height + 5));
            PdfWriter writer = PdfWriter.getInstance(document, fs);
            document.open();/*from   w w  w .  ja v a  2s. c o m*/
            PdfContentByte cb = writer.getDirectContent();
            PdfTemplate tp = cb.createTemplate(width, height);
            Graphics2D g2 = tp.createGraphics(width, height, new DefaultFontMapper());
            component.print(g2);
            g2.dispose();
            cb.addTemplate(tp, 0, 0);
            document.close();
            break;
        case SVG:
            exportFreeHep(component, fs, new SVGGraphics2D(fs, new Dimension(width, height)));
            break;
        case EPS:
            exportFreeHep(component, fs, new PSGraphics2D(fs, new Dimension(width, height)));
            break;
        default:
            // cannot happen
            break;
        }
    } catch (Exception e) {
        throw new ImageExportException(
                I18N.getMessage(I18N.getUserErrorMessagesBundle(), "error.image_export.export_failed"), e);
    }
}

From source file:com.servoy.extensions.plugins.pdf_output.PDFPrinterJob.java

License:Open Source License

PDFPrinterJob(OutputStream os, boolean isMetaPrintJob) {
    this.os = os;
    this.isMetaPrintJob = isMetaPrintJob;
    this.mapper = new DefaultFontMapper();
    this.totalPagesPrinted = 0;
    this.pagesPrinted = 0;
}

From source file:com.trollworks.gcs.character.CharacterSheet.java

License:Open Source License

/**
 * @param file The file to save to.//from   w  w  w .j  a v a 2 s . com
 * @return <code>true</code> on success.
 */
public boolean saveAsPDF(File file) {
    HashSet<Row> changed = expandAllContainers();
    try {
        PrintManager settings = mCharacter.getPageSettings();
        PageFormat format = settings != null ? settings.createPageFormat() : createDefaultPageFormat();
        Paper paper = format.getPaper();
        float width = (float) paper.getWidth();
        float height = (float) paper.getHeight();

        adjustToPageSetupChanges(true);
        setPrinting(true);

        com.lowagie.text.Document pdfDoc = new com.lowagie.text.Document(
                new com.lowagie.text.Rectangle(width, height));
        try (FileOutputStream out = new FileOutputStream(file)) {
            PdfWriter writer = PdfWriter.getInstance(pdfDoc, out);
            int pageNum = 0;
            PdfContentByte cb;

            pdfDoc.open();
            cb = writer.getDirectContent();
            while (true) {
                PdfTemplate template = cb.createTemplate(width, height);
                Graphics2D g2d = template.createGraphics(width, height, new DefaultFontMapper());

                if (print(g2d, format, pageNum) == NO_SUCH_PAGE) {
                    g2d.dispose();
                    break;
                }
                if (pageNum != 0) {
                    pdfDoc.newPage();
                }
                g2d.setClip(0, 0, (int) width, (int) height);
                print(g2d, format, pageNum++);
                g2d.dispose();
                cb.addTemplate(template, 0, 0);
            }
            pdfDoc.close();
        }
        return true;
    } catch (Exception exception) {
        return false;
    } finally {
        setPrinting(false);
        closeContainers(changed);
    }
}

From source file:com.unicornlabs.kabouter.reporting.PowerReport.java

License:Apache License

public static void GeneratePowerReport(Date startDate, Date endDate) {
    try {//from  w  w w  .ja  va2  s  . c  om
        Historian theHistorian = (Historian) BusinessObjectManager.getBusinessObject(Historian.class.getName());
        ArrayList<String> powerLogDeviceIds = theHistorian.getPowerLogDeviceIds();

        Document document = new Document(PageSize.A4, 50, 50, 50, 50);

        File outputFile = new File("PowerReport.pdf");
        outputFile.createNewFile();

        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(outputFile));
        document.open();

        document.add(new Paragraph("Power Report for " + startDate.toString() + " to " + endDate.toString()));

        document.newPage();

        DecimalFormat df = new DecimalFormat("#.###");

        for (String deviceId : powerLogDeviceIds) {
            ArrayList<Powerlog> powerlogs = theHistorian.getPowerlogs(deviceId, startDate, endDate);
            double total = 0;
            double max = 0;
            Date maxTime = startDate;
            double average = 0;
            XYSeries series = new XYSeries(deviceId);
            XYDataset dataset = new XYSeriesCollection(series);

            for (Powerlog log : powerlogs) {
                total += log.getPower();
                if (log.getPower() > max) {
                    max = log.getPower();
                    maxTime = log.getId().getLogtime();
                }
                series.add(log.getId().getLogtime().getTime(), log.getPower());
            }

            average = total / powerlogs.size();

            document.add(new Paragraph("\nDevice: " + deviceId));
            document.add(new Paragraph("Average Power Usage: " + df.format(average)));
            document.add(new Paragraph("Maximum Power Usage: " + df.format(max) + " at " + maxTime.toString()));
            document.add(new Paragraph("Total Power Usage: " + df.format(total)));
            //Create a custom date axis to display dates on the X axis
            DateAxis dateAxis = new DateAxis("Date");
            //Make the labels vertical
            dateAxis.setVerticalTickLabels(true);

            //Create the power axis
            NumberAxis powerAxis = new NumberAxis("Power");

            //Set both axes to auto range for their values
            powerAxis.setAutoRange(true);
            dateAxis.setAutoRange(true);

            //Create the tooltip generator
            StandardXYToolTipGenerator ttg = new StandardXYToolTipGenerator("{0}: {2}",
                    new SimpleDateFormat("yyyy/MM/dd HH:mm"), NumberFormat.getInstance());

            //Set the renderer
            StandardXYItemRenderer renderer = new StandardXYItemRenderer(StandardXYItemRenderer.LINES, ttg,
                    null);

            //Create the plot
            XYPlot plot = new XYPlot(dataset, dateAxis, powerAxis, renderer);

            //Create the chart
            JFreeChart myChart = new JFreeChart(deviceId, JFreeChart.DEFAULT_TITLE_FONT, plot, true);

            PdfContentByte pcb = writer.getDirectContent();
            PdfTemplate tp = pcb.createTemplate(480, 360);
            Graphics2D g2d = tp.createGraphics(480, 360, new DefaultFontMapper());
            Rectangle2D r2d = new Rectangle2D.Double(0, 0, 480, 360);
            myChart.draw(g2d, r2d);
            g2d.dispose();
            pcb.addTemplate(tp, 0, 0);

            document.newPage();
        }

        document.close();

        JOptionPane.showMessageDialog(null, "Report Generated.");

        Desktop.getDesktop().open(outputFile);
    } catch (FileNotFoundException fnfe) {
        JOptionPane.showMessageDialog(null,
                "Unable To Open File For Writing, Make Sure It Is Not Currently Open");
    } catch (IOException ex) {
        Logger.getLogger(PowerReport.class.getName()).log(Level.SEVERE, null, ex);
    } catch (DocumentException ex) {
        Logger.getLogger(PowerReport.class.getName()).log(Level.SEVERE, null, ex);
    }
}