Example usage for com.itextpdf.awt DefaultFontMapper DefaultFontMapper

List of usage examples for com.itextpdf.awt DefaultFontMapper DefaultFontMapper

Introduction

In this page you can find the example usage for com.itextpdf.awt DefaultFontMapper DefaultFontMapper.

Prototype

DefaultFontMapper

Source Link

Usage

From source file:edu.umn.genomics.component.SavePDF.java

License:Open Source License

/**
 *  Saves the Component to a Portable Document File, PDF, with the 
 * file location selected using the JFileChooser.
 * @param c the Component to save as a PDF
 *//*from w w w .  j  a v  a  2  s .  com*/
public static boolean savePDF(Component c) throws IOException {
    System.out.println("");
    final int w = c.getWidth() > 0 ? c.getWidth() : 1;
    final int h = c.getHeight() > 0 ? c.getHeight() : 1;
    final Dimension dim = c.getPreferredSize();

    JFileChooser chooser = new JFileChooser();
    JPanel ap = new JPanel();
    ap.setLayout(new BoxLayout(ap, BoxLayout.Y_AXIS));
    JPanel sp = new JPanel(new GridLayout(0, 1));
    sp.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "Image Size"));
    final JTextField iwtf = new JTextField("" + w, 4);
    iwtf.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "width"));
    final JTextField ihtf = new JTextField("" + h, 4);
    ihtf.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEmptyBorder(), "height"));
    JButton curSzBtn = new JButton("As Viewed: " + w + "x" + h);
    curSzBtn.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            iwtf.setText("" + w);
            ihtf.setText("" + h);
        }
    });
    sp.add(curSzBtn);
    if (dim != null && dim.getWidth() > 0 && dim.getHeight() > 0) {
        JButton prefSzBtn = new JButton("As Preferred: " + dim.width + "x" + dim.height);
        prefSzBtn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                iwtf.setText("" + dim.width);
                ihtf.setText("" + dim.height);
            }
        });
        sp.add(prefSzBtn);
    }
    sp.add(iwtf);
    sp.add(ihtf);

    ap.add(sp);

    chooser.setAccessory(ap);
    // ImageFilter filter = new ImageFilter(fmt);
    // chooser.setFileFilter(filter);
    int returnVal = chooser.showSaveDialog(c);
    boolean status = false;
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        File file = chooser.getSelectedFile();
        //Added the below code to add th .pdf extension if it is not provided by the user
        String name = file.getAbsolutePath();
        if (!(name.substring(name.length() - 4, name.length()).equalsIgnoreCase(".pdf"))) {
            name = name.concat(".pdf");
            file = new File(name);
        }
        int iw = w;
        int ih = h;
        try {
            iw = Integer.parseInt(iwtf.getText());
            ih = Integer.parseInt(ihtf.getText());
        } catch (Exception ex) {
            ExceptionHandler.popupException("" + ex);
        }
        iw = iw > 0 ? iw : w;
        ih = ih > 0 ? ih : h;
        if (iw != w || ih != h) {
            c.setSize(iw, ih);
        }

        // step 1: creation of a document-object
        Document document = new Document();

        try {
            // step 2:
            // we create a writer that listens to the document
            // and directs a PDF-stream to a file
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));

            // 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();

            // mapper.insertDirectory("c:\\winnt\\fonts");

            com.itextpdf.text.Rectangle pgSize = document.getPageSize();
            // we create a template and a Graphics2D object that corresponds with it
            PdfContentByte cb = writer.getDirectContent();
            PdfTemplate tp = cb.createTemplate(iw, ih);
            tp.setWidth(iw);
            tp.setHeight(ih);
            Graphics2D g2 = tp.createGraphics(iw, ih, mapper);
            g2.setStroke(new BasicStroke(.1f));
            //cb.setLineWidth(.1f);
            //cb.stroke();

            c.paintAll(g2);

            g2.dispose();

            //cb.addTemplate(tp, 0, 0);
            float sfx = (float) (pgSize.getWidth() / iw);
            float sfy = (float) (pgSize.getHeight() / ih);
            // preserve the aspect ratio
            float sf = (float) Math.min(sfx, sfy);
            cb.addTemplate(tp, sf, 0f, 0f, sf, 0f, 0f);

        } catch (DocumentException de) {
            ExceptionHandler.popupException("" + de);
        } catch (IOException ioe) {
            ExceptionHandler.popupException("" + ioe);
        } catch (Exception ex) {
            ExceptionHandler.popupException("" + ex);
        }

        // step 5: we close the document
        document.close();

        if (iw != w || ih != h) {
            c.setSize(w, h);
        }

    }
    return true;
}

From source file:groove.io.external.util.GraphToPDF.java

License:Apache License

@Override
public void renderGraph(JGraph<?> graph, File file) throws PortException {
    // Get graph bounds. If not available, do nothing (probably empty graph)
    Rectangle2D bounds = graph.getGraphBounds();
    if (bounds == null) {
        return;//from  ww w  .  ja va 2 s .c om
    }
    Rectangle bound = new Rectangle((float) bounds.getWidth(), (float) bounds.getHeight());

    try (FileOutputStream fos = new FileOutputStream(file)) {
        Document document = new Document(bound);
        // Open file, create PDF document
        PdfWriter writer = PdfWriter.getInstance(document, fos);
        // Set some metadata
        document.addCreator(Version.getAbout());

        // Open document, get graphics
        document.open();
        PdfContentByte cb = writer.getDirectContent();
        boolean onlyShapes = true;
        //The embedded fonts most likely do not contain all necessary glyphs, so using outlines instead
        // onlyShapes makes PDF considerably bigger, but no alternative at the moment
        PdfGraphics2D pdf2d = new PdfGraphics2D(cb, (float) bounds.getWidth(), (float) bounds.getHeight(),
                new DefaultFontMapper(), onlyShapes, false, (float) 100.0);

        // Render
        toGraphics(graph, pdf2d);

        // Cleanup
        pdf2d.dispose();
        document.close();
    } catch (DocumentException | IOException e) {
        throw new PortException(e);
    }
}

From source file:info.sarihh.unimodeling.gui.DynamicBPEstimateFrame.java

private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed
    int returnValue = fileChooser.showSaveDialog(this);
    if (returnValue == JFileChooser.APPROVE_OPTION) {
        File file = fileChooser.getSelectedFile();
        try {/*from www .j a v a2  s. co  m*/
            saveChartAsPDF(file, chart, 450, 350, new DefaultFontMapper());
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
}

From source file:net.panthema.BispanningGame.GamePanel.java

License:Open Source License

public void writePdf() throws FileNotFoundException, DocumentException {

    // Query user for filename
    JFileChooser chooser = new JFileChooser();
    chooser.setDialogTitle("Specify PDF file to save");
    chooser.setCurrentDirectory(new File("."));
    FileNameExtensionFilter filter = new FileNameExtensionFilter("PDF Documents", "pdf");
    chooser.setFileFilter(filter);//  w  w  w  .j a  v  a  2 s . co  m

    if (chooser.showSaveDialog(this) != JFileChooser.APPROVE_OPTION)
        return;

    File outfile = chooser.getSelectedFile();
    if (!outfile.getAbsolutePath().endsWith(".pdf")) {
        outfile = new File(outfile.getAbsolutePath() + ".pdf");
    }

    // Calculate page size rectangle
    Dimension size = mVV.getSize();
    Rectangle rsize = new Rectangle(size.width, size.height);

    // Open the PDF file for writing - and create a Graphics2D object
    Document document = new Document(rsize);
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(outfile));
    document.open();

    PdfContentByte contentByte = writer.getDirectContent();
    PdfGraphics2D graphics2d = new PdfGraphics2D(contentByte, size.width, size.height, new DefaultFontMapper());

    // Create a container to hold the visualization
    Container container = new Container();
    container.addNotify();
    container.add(mVV);
    container.setVisible(true);
    container.paintComponents(graphics2d);

    // Dispose of the graphics and close the document
    graphics2d.dispose();
    document.close();

    // Put mVV back onto visible plane
    setLayout(new BorderLayout());
    add(mVV, BorderLayout.CENTER);
}

From source file:net.pickapack.chart.ChartPdfExporter.java

License:Open Source License

/**
 * Export the specified chart to the specified PDF file.
 *
 * @param chart the chart//from ww w . j ava2  s  .  co  m
 * @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);
    }
}

From source file:net.sf.mzmine.chartbasics.graphicsexport.ChartExportUtil.java

License:Open Source License

/**
 * This method saves a chart as a PDF with given dimensions
 * /*from www . j  a va2 s .c  o  m*/
 * @param chart
 * @param width
 * @param height
 * @param fileName is a full path
 */
public static void writeChartToPDF(JFreeChart chart, int width, int height, File fileName) throws Exception {
    PdfWriter writer = null;

    Document document = new Document(new Rectangle(width, height));

    try {
        writer = PdfWriter.getInstance(document, new FileOutputStream(fileName));
        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();
        throw e;
    } finally {
        document.close();
    }
}

From source file:org.fhaes.fhsamplesize.view.SSIZCurveChart.java

License:Open Source License

/**
 * Save chart as PDF file. Requires iText library.
 * //from   w  ww  . j  a  va 2  s  .c  om
 * @param chart JFreeChart to save.
 * @param fileName Name of file to save chart in.
 * @param width Width of chart graphic.
 * @param height Height of chart graphic.
 * @throws Exception if failed.
 * @see <a href="http://www.lowagie.com/iText">iText</a>
 */
@SuppressWarnings("deprecation")
public static void writeAsPDF(File fileToSave, int width, int height) throws Exception {

    if (chart != null) {
        BufferedOutputStream out = null;
        try {
            out = new BufferedOutputStream(new FileOutputStream(fileToSave.getAbsolutePath()));

            // convert chart to PDF with iText:
            Rectangle pagesize = new Rectangle(width, height);
            Document document = new Document(pagesize, 50, 50, 50, 50);
            try {
                PdfWriter writer = PdfWriter.getInstance(document, out);
                document.addAuthor("JFreeChart");
                document.open();

                PdfContentByte cb = writer.getDirectContent();
                PdfTemplate tp = cb.createTemplate(width, height);
                Graphics2D g2 = tp.createGraphics(width, height, new DefaultFontMapper());

                Rectangle2D r2D = new Rectangle2D.Double(0, 0, width, height);
                chart.draw(g2, r2D, null);
                g2.dispose();
                cb.addTemplate(tp, 0, 0);
            } finally {
                document.close();
            }
        } finally {
            if (out != null)
                out.close();
        }
    }
}

From source file:org.ujmp.itext.ExportPDF.java

License:Open Source License

public static final void save(File file, Component c, int width, int height) {
    if (file == null) {
        logger.log(Level.WARNING, "no file selected");
        return;/* w w w.j a  va 2 s .c  o  m*/
    }
    if (c == null) {
        logger.log(Level.WARNING, "no component provided");
        return;
    }
    try {
        Document document = new Document(new Rectangle(width, height));
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file.getAbsolutePath()));
        document.addAuthor("UJMP v" + UJMP.UJMPVERSION);
        document.open();
        PdfContentByte cb = writer.getDirectContent();
        PdfTemplate tp = cb.createTemplate(width, height);
        Graphics2D g2 = new PdfGraphics2D(cb, width, height, new DefaultFontMapper());
        if (c instanceof CanRenderGraph) {
            ((CanRenderGraph) c).renderGraph(g2);
        } else {
            c.paint(g2);
        }
        g2.dispose();
        cb.addTemplate(tp, 0, 0);
        document.close();
        writer.close();
    } catch (Exception e) {
        logger.log(Level.WARNING, "could not save PDF file", e);
    }
}

From source file:sim.util.media.PDFEncoder.java

License:Academic Free License

public static void generatePDF(Component component, File file) {
    int width = component.getWidth();
    int height = component.getHeight();
    try {//from  w w w .j a v a 2 s  . co m
        Document document = new Document(new com.lowagie.text.Rectangle(width, height));
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
        document.addAuthor("MASON");
        document.open();
        PdfContentByte cb = writer.getDirectContent();
        PdfTemplate tp = cb.createTemplate(width, height);
        Graphics g2 = tp.createGraphics(width, height, new DefaultFontMapper());
        component.paint(g2);
        g2.dispose();
        cb.addTemplate(tp, 0, 0);
        document.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:sim.util.media.PDFEncoder.java

License:Academic Free License

public static void generatePDF(JFreeChart chart, int width, int height, File file) {
    try {/*from  w ww  .  j a  v  a  2s. co  m*/
        Document document = new Document(new com.lowagie.text.Rectangle(width, height));
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
        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();
    }
}