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:org.geomajas.plugin.print.component.PdfContext.java

License:Open Source License

/**
 * Draw text in the center of the specified box.
 *
 * @param text text/*w w w. ja v  a 2s.c om*/
 * @param font font
 * @param box box to put text int
 * @param fontColor colour
 */
public void drawText(String text, Font font, Rectangle box, Color fontColor) {
    template.saveState();
    // get the font
    DefaultFontMapper mapper = new DefaultFontMapper();
    BaseFont bf = mapper.awtToPdf(font);
    template.setFontAndSize(bf, font.getSize());

    // calculate descent
    float descent = 0;
    if (text != null) {
        descent = bf.getDescentPoint(text, font.getSize());
    }

    // calculate the fitting size
    Rectangle fit = getTextSize(text, font);

    // draw text if necessary
    template.setColorFill(fontColor);
    template.beginText();
    template.showTextAligned(PdfContentByte.ALIGN_LEFT, text,
            origX + box.getLeft() + 0.5f * (box.getWidth() - fit.getWidth()),
            origY + box.getBottom() + 0.5f * (box.getHeight() - fit.getHeight()) - descent, 0);
    template.endText();
    template.restoreState();
}

From source file:org.geoserver.wms.map.PDFMapResponse.java

License:Open Source License

/**
 * Writes the PDF.//from   www.  ja  v a  2  s. c  o  m
 * <p>
 * NOTE: the document seems to actually be created in memory, and being written down to
 * {@code output} once we call {@link Document#close()}. If there's no other way to do so, it'd
 * be better to actually split out the process into produceMap/write?
 * </p>
 * 
 * @see org.geoserver.ows.Response#write(java.lang.Object, java.io.OutputStream,
 *      org.geoserver.platform.Operation)
 */
@Override
public void write(Object value, OutputStream output, Operation operation) throws IOException, ServiceException {

    Assert.isInstanceOf(PDFMap.class, value);
    WMSMapContent mapContent = ((PDFMap) value).getContext();

    final int width = mapContent.getMapWidth();
    final int height = mapContent.getMapHeight();

    if (LOGGER.isLoggable(Level.FINE)) {
        LOGGER.fine("setting up " + width + "x" + height + " image");
    }

    try {
        // step 1: creation of a document-object
        // width of document-object is width*72 inches
        // height of document-object is height*72 inches
        com.lowagie.text.Rectangle pageSize = new com.lowagie.text.Rectangle(width, height);

        Document document = new Document(pageSize);
        document.setMargins(0, 0, 0, 0);

        // step 2: creation of the writer
        PdfWriter writer = PdfWriter.getInstance(document, output);

        // step 3: we open the document
        document.open();

        // step 4: we grab the ContentByte and do some stuff with it

        // we create a fontMapper and read all the fonts in the font
        // directory
        DefaultFontMapper mapper = new DefaultFontMapper();
        FontFactory.registerDirectories();

        // we create a template and a Graphics2D object that corresponds
        // with it
        PdfContentByte cb = writer.getDirectContent();
        PdfTemplate tp = cb.createTemplate(width, height);
        PdfGraphics2D graphic = (PdfGraphics2D) tp.createGraphics(width, height, mapper);

        // we set graphics options
        if (!mapContent.isTransparent()) {
            graphic.setColor(mapContent.getBgColor());
            graphic.fillRect(0, 0, width, height);
        } else {
            if (LOGGER.isLoggable(Level.FINE)) {
                LOGGER.fine("setting to transparent");
            }

            int type = AlphaComposite.SRC;
            graphic.setComposite(AlphaComposite.getInstance(type));

            Color c = new Color(mapContent.getBgColor().getRed(), mapContent.getBgColor().getGreen(),
                    mapContent.getBgColor().getBlue(), 0);
            graphic.setBackground(mapContent.getBgColor());
            graphic.setColor(c);
            graphic.fillRect(0, 0, width, height);

            type = AlphaComposite.SRC_OVER;
            graphic.setComposite(AlphaComposite.getInstance(type));
        }

        Rectangle paintArea = new Rectangle(width, height);

        StreamingRenderer renderer = new StreamingRenderer();
        renderer.setMapContent(mapContent);
        // TODO: expose the generalization distance as a param
        // ((StreamingRenderer) renderer).setGeneralizationDistance(0);

        RenderingHints hints = new RenderingHints(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
        renderer.setJava2DHints(hints);

        // we already do everything that the optimized data loading does...
        // if we set it to true then it does it all twice...
        java.util.Map rendererParams = new HashMap();
        rendererParams.put("optimizedDataLoadingEnabled", new Boolean(true));
        rendererParams.put("renderingBuffer", new Integer(mapContent.getBuffer()));
        // we need the renderer to draw everything on the batik provided graphics object
        rendererParams.put(StreamingRenderer.OPTIMIZE_FTS_RENDERING_KEY, Boolean.FALSE);
        // render everything in vector form if possible
        rendererParams.put(StreamingRenderer.VECTOR_RENDERING_KEY, Boolean.TRUE);
        if (DefaultWebMapService.isLineWidthOptimizationEnabled()) {
            rendererParams.put(StreamingRenderer.LINE_WIDTH_OPTIMIZATION_KEY, true);
        }
        rendererParams.put(StreamingRenderer.SCALE_COMPUTATION_METHOD_KEY, mapContent.getRendererScaleMethod());

        renderer.setRendererHints(rendererParams);

        Envelope dataArea = mapContent.getRenderingArea();

        // enforce no more than x rendering errors
        int maxErrors = wms.getMaxRenderingErrors();
        MaxErrorEnforcer errorChecker = new MaxErrorEnforcer(renderer, maxErrors);

        // Add a render listener that ignores well known rendering exceptions and reports back
        // non
        // ignorable ones
        final RenderExceptionStrategy nonIgnorableExceptionListener;
        nonIgnorableExceptionListener = new RenderExceptionStrategy(renderer);
        renderer.addRenderListener(nonIgnorableExceptionListener);

        // enforce max memory usage
        int maxMemory = wms.getMaxRequestMemory() * KB;
        PDFMaxSizeEnforcer memoryChecker = new PDFMaxSizeEnforcer(renderer, graphic, maxMemory);

        // render the map
        renderer.paint(graphic, paintArea, mapContent.getRenderingArea(), mapContent.getRenderingTransform());

        // render the watermark
        MapDecorationLayout.Block watermark = RenderedImageMapOutputFormat.getWatermark(wms.getServiceInfo());

        if (watermark != null) {
            MapDecorationLayout layout = new MapDecorationLayout();
            layout.paint(graphic, paintArea, mapContent);
        }

        // check if a non ignorable error occurred
        if (nonIgnorableExceptionListener.exceptionOccurred()) {
            Exception renderError = nonIgnorableExceptionListener.getException();
            throw new ServiceException("Rendering process failed", renderError, "internalError");
        }

        // check if too many errors occurred
        if (errorChecker.exceedsMaxErrors()) {
            throw new ServiceException("More than " + maxErrors + " rendering errors occurred, bailing out",
                    errorChecker.getLastException(), "internalError");
        }

        // check we did not use too much memory
        if (memoryChecker.exceedsMaxSize()) {
            long kbMax = maxMemory / KB;
            throw new ServiceException(
                    "Rendering request used more memory than the maximum allowed:" + kbMax + "KB");
        }

        graphic.dispose();
        cb.addTemplate(tp, 0, 0);

        // step 5: we close the document
        document.close();
        writer.flush();
        writer.close();
    } catch (DocumentException t) {
        throw new ServiceException("Error setting up the PDF", t, "internalError");
    }
}

From source file:org.jivesoftware.openfire.reporting.graph.GraphServlet.java

License:Open Source License

private void writePDFContent(HttpServletRequest request, HttpServletResponse response, JFreeChart charts[],
        Statistic[] stats, long starttime, long endtime, int width, int height) throws IOException {

    try {//from ww w  .j  a  v  a  2 s  . c om
        Document document = new Document(PageSize.A4, 50, 50, 50, 50);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter writer = PdfWriter.getInstance(document, baos);
        writer.setPageEvent(new PDFEventListener(request));
        document.open();

        int index = 0;
        int chapIndex = 0;
        for (Statistic stat : stats) {

            String serverName = XMPPServer.getInstance().getServerInfo().getXMPPDomain();
            String dateName = JiveGlobals.formatDate(new Date(starttime)) + " - "
                    + JiveGlobals.formatDate(new Date(endtime));
            Paragraph paragraph = new Paragraph(serverName,
                    FontFactory.getFont(FontFactory.HELVETICA, 18, Font.BOLD));
            document.add(paragraph);
            paragraph = new Paragraph(dateName, FontFactory.getFont(FontFactory.HELVETICA, 14, Font.PLAIN));
            document.add(paragraph);
            document.add(Chunk.NEWLINE);
            document.add(Chunk.NEWLINE);

            Paragraph chapterTitle = new Paragraph(++chapIndex + ". " + stat.getName(),
                    FontFactory.getFont(FontFactory.HELVETICA, 16, Font.BOLD));

            document.add(chapterTitle);
            // total hack: no idea what tags people are going to use in the description
            // possibly recommend that we only use a <p> tag?
            String[] paragraphs = stat.getDescription().split("<p>");
            for (String s : paragraphs) {
                Paragraph p = new Paragraph(s);
                document.add(p);
            }
            document.add(Chunk.NEWLINE);

            PdfContentByte contentByte = writer.getDirectContent();
            PdfTemplate template = contentByte.createTemplate(width, height);
            Graphics2D graphs2D = template.createGraphics(width, height, new DefaultFontMapper());
            Rectangle2D rectangle2D = new Rectangle2D.Double(0, 0, width, height);
            charts[index++].draw(graphs2D, rectangle2D);
            graphs2D.dispose();
            float x = (document.getPageSize().width() / 2) - (width / 2);
            contentByte.addTemplate(template, x, writer.getVerticalPosition(true) - height);
            document.newPage();
        }

        document.close();

        // setting some response headers
        response.setHeader("Expires", "0");
        response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
        response.setHeader("Pragma", "public");
        // setting the content type
        response.setContentType("application/pdf");
        // the contentlength is needed for MSIE!!!
        response.setContentLength(baos.size());
        // write ByteArrayOutputStream to the ServletOutputStream
        ServletOutputStream out = response.getOutputStream();
        baos.writeTo(out);
        out.flush();
    } catch (DocumentException e) {
        Log.error("error creating PDF document: " + e.getMessage());

    }
}

From source file:org.oss.pdfreporter.pdf.Page.java

License:Open Source License

Page(PdfContentByte content) {
    this.delegate = content;
    this.fontmapper = new DefaultFontMapper();
}

From source file:org.sakaiproject.evaluation.tool.reporting.EvalPDFReportBuilder.java

License:Educational Community License

/**
  * @param question/*  w  w  w. java 2  s  . c om*/
  *            the question text
  * @param choices
  *            the text for the choices
  * @param values
  *            the count of answers for each choice (same order as choices)
  * @param responseCount
  *            the number of responses to the question
  * @param showPercentages
  *            if true then show the percentages
  * @param answersAndMean
  *            the text which will be displayed above the chart (normally the answers count and
  *            mean)
  * @param lastElementIsHeader
  *            If the last element was a header, the extra spacing paragraph is not needed.
  */
public void addLikertResponse(String question, String[] choices, int[] values, int responseCount,
        boolean showPercentages, String answersAndMean, boolean lastElementIsHeader) {
    ArrayList<Element> myElements = new ArrayList<>();

    try {
        if (!lastElementIsHeader) {
            Paragraph emptyPara = new Paragraph(" ");
            this.addElementWithJump(emptyPara, false);
        }

        Paragraph myPara = new Paragraph(question, questionTextFont);
        myPara.setSpacingAfter(SPACING_AFTER_HEADER);
        myElements.add(myPara);

        EvalLikertChartBuilder chartBuilder = new EvalLikertChartBuilder();
        chartBuilder.setValues(values);
        chartBuilder.setResponses(choices);
        chartBuilder.setShowPercentages(showPercentages);
        chartBuilder.setResponseCount(responseCount);
        JFreeChart chart = chartBuilder.makeLikertChart();

        /* The height is going to be based off the number of choices */
        int height = 15 * choices.length;

        PdfContentByte cb = pdfWriter.getDirectContent();
        PdfTemplate tp = cb.createTemplate(200, height);
        Graphics2D g2d = tp.createGraphics(200, height, new DefaultFontMapper());
        Rectangle2D r2d = new Rectangle2D.Double(0, 0, 200, height);
        chart.draw(g2d, r2d);
        g2d.dispose();
        Image image = Image.getInstance(tp);

        // put image in the document
        myElements.add(image);

        if (answersAndMean != null) {
            Paragraph header = new Paragraph(answersAndMean, paragraphFont);
            header.setSpacingAfter(SPACING_BETWEEN_LIST_ITEMS);
            myElements.add(header);
        }

        this.addElementArrayWithJump(myElements);
    } catch (BadElementException e) {
        // TODO Auto-generated catch block
        LOG.warn(e);
    }
}

From source file:org.schreibubi.JCombinations.ui.GridChartPanel.java

License:Open Source License

/**
 * Create PDF// w ww .  j a  v  a 2  s  .c  o m
 * 
 * @param name
 *            Filename
 * @param selection
 *            Selected Nodes
 * @param dm
 *            DataModel
 * @param pl
 *            ProgressListener
 */
@SuppressWarnings("unchecked")
public static void generatePDF(File name, DataModel dm, ArrayList<TreePath> selection, ProgressListener pl) {
    com.lowagie.text.Document document = new Document(PageSize.A4.rotate(), 50, 50, 50, 50);
    try {
        ArrayList<ExtendedJFreeChart> charts = dm.getCharts(selection);
        if (charts.size() > 0) {
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(name));
            writer.setViewerPreferences(PdfWriter.PageModeUseOutlines);
            document.addAuthor("Jrg Werner");
            document.addSubject("Created by JCombinations");
            document.addKeywords("JCombinations");
            document.addCreator("JCombinations using iText");

            // we define a header and a footer
            HeaderFooter header = new HeaderFooter(new Phrase("JCombinations by Jrg Werner"), false);
            HeaderFooter footer = new HeaderFooter(new Phrase("Page "), new Phrase("."));
            footer.setAlignment(Element.ALIGN_CENTER);
            document.setHeader(header);
            document.setFooter(footer);

            document.open();
            DefaultFontMapper mapper = new DefaultFontMapper();
            FontFactory.registerDirectories();
            mapper.insertDirectory("c:\\WINNT\\fonts");

            PdfContentByte cb = writer.getDirectContent();

            pl.progressStarted(new ProgressEvent(GridChartPanel.class, 0, charts.size()));
            for (int i = 0; i < charts.size(); i++) {
                ExtendedJFreeChart chart = charts.get(i);
                PdfTemplate tp = cb.createTemplate(document.right(EXTRA_MARGIN) - document.left(EXTRA_MARGIN),
                        document.top(EXTRA_MARGIN) - document.bottom(EXTRA_MARGIN));
                Graphics2D g2d = tp.createGraphics(document.right(EXTRA_MARGIN) - document.left(EXTRA_MARGIN),
                        document.top(EXTRA_MARGIN) - document.bottom(EXTRA_MARGIN), mapper);
                Rectangle2D r2d = new Rectangle2D.Double(0, 0,
                        document.right(EXTRA_MARGIN) - document.left(EXTRA_MARGIN),
                        document.top(EXTRA_MARGIN) - document.bottom(EXTRA_MARGIN));
                chart.draw(g2d, r2d);
                g2d.dispose();
                cb.addTemplate(tp, document.left(EXTRA_MARGIN), document.bottom(EXTRA_MARGIN));
                PdfDestination destination = new PdfDestination(PdfDestination.FIT);
                TreePath treePath = chart.getTreePath();
                PdfOutline po = cb.getRootOutline();
                for (int j = 0; j < treePath.getPathCount(); j++) {
                    ArrayList<PdfOutline> lpo = po.getKids();
                    PdfOutline cpo = null;
                    for (PdfOutline outline : lpo)
                        if (outline.getTitle().compareTo(treePath.getPathComponent(j).toString()) == 0)
                            cpo = outline;
                    if (cpo == null)
                        cpo = new PdfOutline(po, destination, treePath.getPathComponent(j).toString());
                    po = cpo;
                }
                document.newPage();
                pl.progressIncremented(new ProgressEvent(GridChartPanel.class, i));
            }
            document.close();
            pl.progressEnded(new ProgressEvent(GridChartPanel.class));

        }
    } catch (DocumentException de) {
        System.err.println(de.getMessage());
    } catch (IOException ioe) {
        System.err.println(ioe.getMessage());
    }
}

From source file:org.vfny.geoserver.wms.responses.map.pdf.PDFMapProducer.java

License:Open Source License

/**
 * Writes the image to the client./*  w  w  w .  j  av a2  s . c  om*/
 * 
 * @param out
 *            The output stream to write to.
 */
public void writeTo(OutputStream out) throws ServiceException, java.io.IOException {
    final int width = mapContext.getMapWidth();
    final int height = mapContext.getMapHeight();

    if (LOGGER.isLoggable(Level.FINE)) {
        LOGGER.fine("setting up " + width + "x" + height + " image");
    }

    try {
        // step 1: creation of a document-object
        // width of document-object is width*72 inches
        // height of document-object is height*72 inches
        com.lowagie.text.Rectangle pageSize = new com.lowagie.text.Rectangle(width, height);

        Document document = new Document(pageSize);
        document.setMargins(0, 0, 0, 0);

        // step 2: creation of the writer
        PdfWriter writer = PdfWriter.getInstance(document, out);

        // step 3: we open the document
        document.open();

        // step 4: we grab the ContentByte and do some stuff with it

        // we create a fontMapper and read all the fonts in the font
        // directory
        DefaultFontMapper mapper = new DefaultFontMapper();
        FontFactory.registerDirectories();

        // we create a template and a Graphics2D object that corresponds
        // with it
        PdfContentByte cb = writer.getDirectContent();
        PdfTemplate tp = cb.createTemplate(width, height);
        PdfGraphics2D graphic = (PdfGraphics2D) tp.createGraphics(width, height, mapper);

        // we set graphics options
        if (!mapContext.isTransparent()) {
            graphic.setColor(mapContext.getBgColor());
            graphic.fillRect(0, 0, width, height);
        } else {
            if (LOGGER.isLoggable(Level.FINE)) {
                LOGGER.fine("setting to transparent");
            }

            int type = AlphaComposite.SRC;
            graphic.setComposite(AlphaComposite.getInstance(type));

            Color c = new Color(mapContext.getBgColor().getRed(), mapContext.getBgColor().getGreen(),
                    mapContext.getBgColor().getBlue(), 0);
            graphic.setBackground(mapContext.getBgColor());
            graphic.setColor(c);
            graphic.fillRect(0, 0, width, height);

            type = AlphaComposite.SRC_OVER;
            graphic.setComposite(AlphaComposite.getInstance(type));
        }

        Rectangle paintArea = new Rectangle(width, height);

        renderer = new StreamingRenderer();
        renderer.setContext(mapContext);
        // TODO: expose the generalization distance as a param
        // ((StreamingRenderer) renderer).setGeneralizationDistance(0);

        RenderingHints hints = new RenderingHints(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
        renderer.setJava2DHints(hints);

        // we already do everything that the optimized data loading does...
        // if we set it to true then it does it all twice...
        Map rendererParams = new HashMap();
        rendererParams.put("optimizedDataLoadingEnabled", new Boolean(true));
        rendererParams.put("renderingBuffer", new Integer(mapContext.getBuffer()));
        // we need the renderer to draw everything on the batik provided graphics object
        rendererParams.put(StreamingRenderer.OPTIMIZE_FTS_RENDERING_KEY, Boolean.FALSE);
        if (!DefaultWebMapService.isLineWidthOptimizationEnabled()) {
            rendererParams.put(StreamingRenderer.LINE_WIDTH_OPTIMIZATION_KEY, false);
        }
        renderer.setRendererHints(rendererParams);

        Envelope dataArea = mapContext.getAreaOfInterest();
        AffineTransform at = RendererUtilities.worldToScreenTransform(dataArea, paintArea);

        if (this.abortRequested) {
            graphic.dispose();
            // step 5: we close the document
            document.close();

            return;
        }

        // enforce no more than x rendering errors
        int maxErrors = wms.getMaxRenderingErrors();
        MaxErrorEnforcer errorChecker = new MaxErrorEnforcer(renderer, maxErrors);

        // Add a render listener that ignores well known rendering exceptions and reports back non
        // ignorable ones
        final RenderExceptionStrategy nonIgnorableExceptionListener;
        nonIgnorableExceptionListener = new RenderExceptionStrategy(renderer);
        renderer.addRenderListener(nonIgnorableExceptionListener);

        // enforce max memory usage
        int maxMemory = wms.getMaxRequestMemory() * KB;
        PDFMaxSizeEnforcer memoryChecker = new PDFMaxSizeEnforcer(renderer, graphic, maxMemory);

        // render the map
        renderer.paint(graphic, paintArea, at);

        // render the watermark
        MapDecorationLayout.Block watermark = DefaultRasterMapProducer
                .getWatermark(this.mapContext.getRequest().getWMS().getServiceInfo());

        if (watermark != null) {
            MapDecorationLayout layout = new MapDecorationLayout();
            layout.paint(graphic, paintArea, this.mapContext);
        }

        //check if a non ignorable error occurred
        if (nonIgnorableExceptionListener.exceptionOccurred()) {
            Exception renderError = nonIgnorableExceptionListener.getException();
            throw new WmsException("Rendering process failed", "internalError", renderError);
        }

        // check if too many errors occurred
        if (errorChecker.exceedsMaxErrors()) {
            throw new WmsException("More than " + maxErrors + " rendering errors occurred, bailing out",
                    "internalError", errorChecker.getLastException());
        }

        // check we did not use too much memory
        if (memoryChecker.exceedsMaxSize()) {
            long kbMax = maxMemory / KB;
            throw new WmsException(
                    "Rendering request used more memory than the maximum allowed:" + kbMax + "KB");
        }

        graphic.dispose();
        cb.addTemplate(tp, 0, 0);

        // step 5: we close the document
        document.close();
        writer.flush();
        writer.close();
    } catch (DocumentException t) {
        throw new WmsException("Error setting up the PDF", "internalError", t);
    }
}

From source file:peakml.graphics.JFreeChartTools.java

License:Open Source License

/**
 * This method writes the given graph to the output stream in the PDF format. As a vector
 * based file format it allows some freedom to be changed (e.g. colors, line thickness, etc.),
 * which can be convenient for presentation purposes.
 * /*from  w ww .j a  va2s.  c o  m*/
 * @param out         The output stream to write to.
 * @param chart         The chart to be written.
 * @param width         The width of the image.
 * @param height      The height of the image.
 * @throws IOException   Thrown when an error occurs with the IO.
 */
public static void writeAsPDF(OutputStream out, JFreeChart chart, int width, int height) throws IOException {
    Document document = new Document(new Rectangle(width, height), 50, 50, 50, 50);
    document.addAuthor("");
    document.addSubject("");

    try {
        PdfWriter writer = PdfWriter.getInstance(document, out);
        document.open();
        PdfContentByte cb = writer.getDirectContent();
        PdfTemplate tp = cb.createTemplate(width, height);

        java.awt.Graphics2D g2 = tp.createGraphics(width, height, new DefaultFontMapper());
        chart.draw(g2, new java.awt.geom.Rectangle2D.Double(0, 0, width, height));

        g2.dispose();
        cb.addTemplate(tp, 0, 0);
    } catch (DocumentException de) {
        throw new IOException(de.getMessage());
    }

    document.close();
}

From source file:processing.pdf.PGraphicsPDF.java

License:Open Source License

static protected DefaultFontMapper getMapper() {
    if (mapper == null) {
        //      long t = System.currentTimeMillis();
        mapper = new DefaultFontMapper();

        if (PApplet.platform == PConstants.MACOSX) {
            try {
                String homeLibraryFonts = System.getProperty("user.home") + "/Library/Fonts";
                mapper.insertDirectory(homeLibraryFonts);
            } catch (Exception e) {
                // might be a security issue with getProperty() and user.home
                // if this sketch is running from the web
            }//from w w w .java  2s . c o  m
            // add the system font paths
            mapper.insertDirectory("/System/Library/Fonts");
            mapper.insertDirectory("/Library/Fonts");

        } else if (PApplet.platform == PConstants.WINDOWS) {
            // how to get the windows fonts directory?
            // could be c:\winnt\fonts or c:\windows\fonts or not even c:
            // maybe do a Runtime.exec() on echo %WINDIR% ?
            // Runtime.exec solution might be a mess on systems where the
            // the backslash/colon characters not really used (i.e. JP)

            // find the windows fonts folder
            File roots[] = File.listRoots();
            for (int i = 0; i < roots.length; i++) {
                if (roots[i].toString().startsWith("A:")) {
                    // Seems to be a problem with some machines that the A:
                    // drive is returned as an actual root, even if not available.
                    // This won't fix the issue if the same thing happens with
                    // other removable drive devices, but should fix the
                    // initial/problem as cited by the bug report:
                    // http://dev.processing.org/bugs/show_bug.cgi?id=478
                    // If not, will need to use the other fileExists() code below.
                    continue;
                }

                File folder = new File(roots[i], "WINDOWS/Fonts");
                if (folder.exists()) {
                    mapper.insertDirectory(folder.getAbsolutePath());
                    break;
                }
                folder = new File(roots[i], "WINNT/Fonts");
                if (folder.exists()) {
                    mapper.insertDirectory(folder.getAbsolutePath());
                    break;
                }
            }

        } else if (PApplet.platform == PConstants.LINUX) {
            checkDir("/usr/share/fonts/", mapper);
            checkDir("/usr/local/share/fonts/", mapper);
            checkDir(System.getProperty("user.home") + "/.fonts", mapper);
        }
        //      System.out.println("mapping " + (System.currentTimeMillis() - t));
    }
    return mapper;
}

From source file:sim.util.media.chart.ChartGenerator.java

License:Academic Free License

void generatePDF(JFreeChart chart, int width, int height, String fileName) {
    try {/*from  w  ww.j  av a 2  s. c  om*/
        Document document = new Document(new com.lowagie.text.Rectangle(width, height));
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(fileName));
        document.addAuthor("MASON");
        document.open();
        PdfContentByte cb = writer.getDirectContent();
        PdfTemplate tp = cb.createTemplate(width, height);
        Graphics2D g2 = tp.createGraphics(width, height, new DefaultFontMapper());
        Rectangle2D rectangle2D = new Rectangle2D.Double(0, 0, width, height);
        chart.draw(g2, rectangle2D);
        g2.dispose();
        cb.addTemplate(tp, 0, 0);
        document.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}