Example usage for java.awt Font createFont

List of usage examples for java.awt Font createFont

Introduction

In this page you can find the example usage for java.awt Font createFont.

Prototype

public static Font createFont(int fontFormat, File fontFile)
        throws java.awt.FontFormatException, java.io.IOException 

Source Link

Document

Returns a new Font using the specified font type and the specified font file.

Usage

From source file:org.jfree.eastwood.ChartServlet.java

private Font readFontFile(String fontFileParam, float fontSize) throws ServletException {

    File f = new File(fontFileParam);
    if (!f.exists()) {
        throw new ServletException("Font file '" + f + "' doesn't exist");
    }//  w  w  w  .ja v  a 2 s . c o  m
    try {
        FileInputStream fis = new FileInputStream(f);
        Font font = Font.createFont(Font.TRUETYPE_FONT, fis).deriveFont(fontSize);
        fis.close();
        return font;
    } catch (FontFormatException e) {
        throw new ServletException("Font file '" + f + "' is not a truetype font", e);
    } catch (IOException e) {
        throw new ServletException("I/O error when reading font file '" + f + "'", e);
    }
}

From source file:view.AppearanceSettingsDialog.java

/**
 * Creates new form NewJDialog/*from   w  w  w. jav a 2 s  .c  o m*/
 *
 * @param parent
 * @param modal
 * @param signatureSettings
 */
public AppearanceSettingsDialog(java.awt.Frame parent, boolean modal, CCSignatureSettings signatureSettings) {
    super(parent, modal);
    initComponents();
    this.signatureSettings = signatureSettings;

    updateText();

    // Pastas conforme o SO
    ArrayList<String> dirs = new ArrayList<>();
    if (SystemUtils.IS_OS_WINDOWS) {
        dirs.add(System.getenv("windir") + File.separator + "fonts");
    } else if (SystemUtils.IS_OS_LINUX) {
        dirs.add("/usr/share/fonts/truetype/");
        dirs.add("/usr/X11R6/lib/X11/fonts/");
    } else if (SystemUtils.IS_OS_MAC_OSX) {
        dirs.add("/Library/Fonts");
        dirs.add("/System/Library/Fonts");
    }
    dirs.add("extrafonts");

    // Hashmap com fonts
    hmFonts = getAllFonts(dirs);
    ArrayList<com.itextpdf.text.Font> alFonts = new ArrayList<>(hmFonts.keySet());

    Collections.sort(alFonts, new Comparator<com.itextpdf.text.Font>() {
        @Override
        public int compare(com.itextpdf.text.Font f1, com.itextpdf.text.Font f2) {
            return f1.getFamilyname().compareToIgnoreCase(f2.getFamilyname());
        }
    });

    DefaultComboBoxModel dcbm = new DefaultComboBoxModel();
    for (com.itextpdf.text.Font font : alFonts) {
        dcbm.addElement(font.getFamilyname());
    }
    cbFontType.setModel(dcbm);

    String fontLocation = signatureSettings.getAppearance().getFontLocation();
    boolean italic = signatureSettings.getAppearance().isItalic();
    boolean bold = signatureSettings.getAppearance().isBold();
    boolean showName = signatureSettings.getAppearance().isShowName();
    boolean showLocation = signatureSettings.getAppearance().isShowLocation();
    boolean showReason = signatureSettings.getAppearance().isShowReason();
    boolean showDate = signatureSettings.getAppearance().isShowDate();
    int align = signatureSettings.getAppearance().getAlign();

    switch (align) {
    case 0:
        cbAlign.setSelectedIndex(0);
        break;
    case 1:
        cbAlign.setSelectedIndex(1);
        break;
    case 2:
        cbAlign.setSelectedIndex(2);
        break;
    default:
        cbAlign.setSelectedIndex(0);
    }

    previewPanel1.setReason(signatureSettings.getReason());
    previewPanel1.setShowDate(showDate);

    if (signatureSettings.getCcAlias() != null) {
        previewPanel1.setAliasName(signatureSettings.getCcAlias().getName());
    } else {
        previewPanel1.setAliasName(Bundle.getBundle().getString("name"));
    }

    if (!signatureSettings.getLocation().isEmpty()) {
        previewPanel1.setLocation(signatureSettings.getLocation());
        cbShowLocation.setSelected(showLocation);
        previewPanel1.setShowLocation(showLocation);
    } else {
        cbShowLocation.setEnabled(false);
        cbShowLocation.setSelected(false);
    }

    cbShowName.setSelected(showName);
    previewPanel1.setShowName(showName);

    if (!signatureSettings.getReason().isEmpty()) {
        previewPanel1.setReason(signatureSettings.getReason());
        cbShowReason.setSelected(showReason);
        previewPanel1.setShowReason(showReason);
    } else {
        cbShowReason.setEnabled(false);
        cbShowReason.setSelected(false);
    }
    previewPanel1.setText(signatureSettings.getText());
    previewPanel1.setAlign(align);
    colorChooser.setPreviewPanel(new JPanel());
    Color color = signatureSettings.getAppearance().getFontColor();
    colorChooser.setColor(color);
    lblSampleText.setForeground(color);
    cbShowReason.setSelected(showReason);
    cbShowLocation.setSelected(showLocation);
    cbShowDateTime.setSelected(showDate);

    ColorSelectionModel model = colorChooser.getSelectionModel();
    ChangeListener changeListener = new ChangeListener() {
        @Override
        public void stateChanged(ChangeEvent changeEvent) {
            Color newForegroundColor = colorChooser.getColor();
            lblSampleText.setForeground(newForegroundColor);
        }
    };
    model.addChangeListener(changeListener);

    if (fontLocation.contains("aCCinaPDF" + File.separator + "extrafonts")) {
        try {
            Font newFont = Font.createFont(Font.TRUETYPE_FONT, new File(fontLocation));
            Font font = null;
            if (italic && bold) {
                font = newFont.deriveFont(Font.ITALIC + Font.BOLD, 36);
            } else if (italic && !bold) {
                font = newFont.deriveFont(Font.ITALIC, 36);
            } else if (!italic && bold) {
                font = newFont.deriveFont(Font.BOLD, 36);
            } else {
                font = newFont.deriveFont(Font.PLAIN, 36);
            }
            lblSampleText.setFont(font);
        } catch (FontFormatException | IOException ex) {
        }
    } else {
        if (italic && bold) {
            lblSampleText.setFont(new Font(fontLocation, Font.ITALIC + Font.BOLD, 36));
        } else if (italic && !bold) {
            lblSampleText.setFont(new Font(fontLocation, Font.ITALIC, 36));
        } else if (!italic && bold) {
            lblSampleText.setFont(new Font(fontLocation, Font.BOLD, 36));
        } else {
            lblSampleText.setFont(new Font(fontLocation, Font.PLAIN, 36));
        }
    }

    cbBold.setSelected(bold);
    cbItalic.setSelected(italic);

    updateSettings(fontLocation, bold, italic);

    previewPanel1.repaint();
}

From source file:net.technicpack.launcher.lang.ResourceLoader.java

public Font getFont(String name, float size, int style) {
    Font font;/*w ww  .j a  va 2 s .c om*/
    try {
        font = Font
                .createFont(Font.TRUETYPE_FONT,
                        ResourceLoader.class.getResourceAsStream(getResourcePath("/fonts/" + getString(name))))
                .deriveFont(size).deriveFont(style);
    } catch (Exception e) {
        e.printStackTrace();
        // Fallback
        font = new Font("Arial", Font.PLAIN, 12);
    }
    return font;
}

From source file:org.apache.pdfbox.pdmodel.font.PDType1Font.java

/**
 * {@inheritDoc}/*from  w w w . j a v a  2 s. c o  m*/
 */
public Font getawtFont() throws IOException {
    if (awtFont == null) {
        if (type1CFont != null) {
            awtFont = type1CFont.getawtFont();
        } else {
            String baseFont = getBaseFont();
            PDFontDescriptor fd = getFontDescriptor();
            if (fd != null && fd instanceof PDFontDescriptorDictionary) {
                PDFontDescriptorDictionary fdDictionary = (PDFontDescriptorDictionary) fd;
                if (fdDictionary.getFontFile() != null) {
                    try {
                        // create a type1 font with the embedded data
                        awtFont = Font.createFont(Font.TYPE1_FONT,
                                fdDictionary.getFontFile().createInputStream());
                    } catch (FontFormatException e) {
                        log.info("Can't read the embedded type1 font " + fd.getFontName());
                    }
                }
                if (awtFont == null) {
                    // check if the font is part of our environment
                    awtFont = FontManager.getAwtFont(fd.getFontName());
                    if (awtFont == null) {
                        log.info("Can't find the specified font " + fd.getFontName());
                    }
                }
            } else {
                // check if the font is part of our environment
                awtFont = FontManager.getAwtFont(baseFont);
                if (awtFont == null) {
                    log.info("Can't find the specified basefont " + baseFont);
                }
            }
        }
        if (awtFont == null) {
            // we can't find anything, so we have to use the standard font
            awtFont = FontManager.getStandardFont();
            log.info("Using font " + awtFont.getName() + " instead");
        }
    }
    return awtFont;
}

From source file:GUI.GraphicalInterface.java

/**
 * Set console (monospace) fonts in Terminal and Command Description.
 *///from   ww  w  .ja  v  a 2 s  .c  o m
private void setFont() {
    try {
        InputStream is = GraphicalInterface.class.getResourceAsStream("/Resources/style/fonts/Inconsolata.otf");
        Font font = Font.createFont(Font.PLAIN, is);
        Font sizedFont = font.deriveFont(14f);

        terminalJTextArea.setFont(sizedFont);
        descriptionJTextArea.setFont(sizedFont);
        statusJLabel.setFont(sizedFont);
    } catch (FontFormatException ex) {
        Logger.getLogger(GraphicalInterface.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(GraphicalInterface.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:net.padaf.preflight.font.Type1FontValidator.java

/**
 * This methods validates the Font Stream, if the font program is damaged or
 * missing the FontContainer is updated and false is returned.
 * //from   ww w .j  a  v  a  2  s  .  c  o  m
 * @throws ValidationException
 */
protected boolean checkFontFileElement() throws ValidationException {
    // ---- if the this font is a Subset, the CharSet entry must be present in
    // the FontDescriptor
    if (isSubSet(pFontDesc.getFontName())) {
        String charsetStr = pFontDesc.getCharSet();
        if (charsetStr == null || "".equals(charsetStr)) {
            this.fontContainer
                    .addError(new ValidationResult.ValidationError(ERROR_FONTS_CHARSET_MISSING_FOR_SUBSET,
                            "The Charset entry is missing for the Type1 Subset"));
            return false;
        }
    }

    // ---- FontFile Validation
    PDStream ff1 = pFontDesc.getFontFile();
    PDStream ff2 = pFontDesc.getFontFile2();
    PDStream ff3 = pFontDesc.getFontFile3();
    boolean onlyOne = (ff1 != null && ff2 == null && ff3 == null) || (ff1 == null && ff2 != null && ff3 == null)
            || (ff1 == null && ff2 == null && ff3 != null);

    if ((ff1 == null && (ff3 == null
            || !"Type1C".equals(((COSDictionary) ff3.getCOSObject()).getNameAsString(COSName.SUBTYPE))))
            || !onlyOne) {
        this.fontContainer.addError(new ValidationResult.ValidationError(ERROR_FONTS_FONT_FILEX_INVALID,
                "The FontFile is invalid"));
        return false;
    }

    if (ff1 != null) {
        COSStream stream = ff1.getStream();
        if (stream == null) {
            this.fontContainer.addError(new ValidationResult.ValidationError(ERROR_FONTS_FONT_FILEX_INVALID,
                    "The FontFile is missing"));
            this.fontContainer.setFontProgramEmbedded(false);
            return false;
        }

        boolean hasLength1 = stream.getInt(COSName.getPDFName(FONT_DICTIONARY_KEY_LENGTH1)) > 0;
        boolean hasLength2 = stream.getInt(COSName.getPDFName(FONT_DICTIONARY_KEY_LENGTH2)) > 0;
        boolean hasLength3 = stream.getInt(COSName.getPDFName(FONT_DICTIONARY_KEY_LENGTH3)) > 0;
        if (!(hasLength1 && hasLength2 && hasLength3)) {
            this.fontContainer.addError(new ValidationResult.ValidationError(ERROR_FONTS_FONT_FILEX_INVALID,
                    "The FontFile is invalid"));
            return false;
        }

        // ---- Stream validation should be done by the StreamValidateHelper.
        // ---- Process font specific check
        // ---- try to load the font using the java.awt.font object.
        // ---- if the font is invalid, an exception will be thrown
        ByteArrayInputStream bis = null;
        try {
            bis = new ByteArrayInputStream(ff1.getByteArray());
            Font.createFont(Font.TYPE1_FONT, bis);
            return checkFontMetricsDataAndFeedFontContainer(ff1) && checkFontFileMetaData(pFontDesc, ff1);
        } catch (IOException e) {
            this.fontContainer.addError(new ValidationResult.ValidationError(ERROR_FONTS_TYPE1_DAMAGED,
                    "The FontFile can't be read"));
            return false;
        } catch (FontFormatException e) {
            this.fontContainer.addError(
                    new ValidationResult.ValidationError(ERROR_FONTS_TYPE1_DAMAGED, "The FontFile is damaged"));
            return false;
        } finally {
            if (bis != null) {
                IOUtils.closeQuietly(bis);
            }
        }
    } else {
        return checkCIDFontWidths(ff3) && checkFontFileMetaData(pFontDesc, ff3);
    }
}

From source file:iqq.app.core.service.impl.SkinServiceImpl.java

private Font loadFontFromFile(File file) {
    BufferedInputStream in = null;
    try {/*w  ww. j a va 2s  . c o m*/
        in = new BufferedInputStream(new FileInputStream(file));
        Font font = Font.createFont(Font.TRUETYPE_FONT, in);
        return font;
    } catch (FileNotFoundException e) {
        LOG.warn("font " + file + "not found!", e);
    } catch (FontFormatException e) {
        LOG.warn("invalid font file!", e);
    } catch (IOException e) {
        LOG.warn("read font error!", e);
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                LOG.warn("close font file error!", e);
            }
        }
    }
    return null;
}

From source file:PolyGlot.IOHandler.java

/**
 * compares testfont to loaded file. returns file if it represents the font
 *
 * @param path full path of file to test
 * @param testFont font to test against//from   w  w w. ja  v  a 2s  . c  o  m
 * @return file if path leads to passed font, null otherwise
 */
private static File loadFont(String path, Font testFont) {
    File fontFile = new File(path);
    File ret = null;

    // unrecgnized types won't be loaded
    if (path.toLowerCase().endsWith(".ttf") || path.toLowerCase().endsWith(".otf")
            || path.toLowerCase().endsWith(".ttc") || path.toLowerCase().endsWith(".ttc")
            || path.toLowerCase().endsWith(".dfont")) {
        try {
            Font f = Font.createFont(Font.TRUETYPE_FONT, fontFile);

            // if names match, set ret to return file
            if (f.getName().equals(testFont.getName()) || f.getName().equals(testFont.getName() + " Regular")) {
                ret = fontFile;
            }

        } catch (FontFormatException e) {
            // null detected and message bubbled to user elsewhere
            ret = null;
        } catch (IOException e) {
            // null detected and message bubbled to user elsewhere
            ret = null;
        }
    }

    return ret;
}

From source file:pcgen.system.Main.java

private static void initPrintPreviewFonts() {
    GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
    String fontDir = ConfigurationSettings.getOutputSheetsDir() + File.separator + "fonts" + File.separator
            + "NotoSans" + File.separator;
    try {/*from  www .  j a  v  a  2  s .  c  o m*/
        ge.registerFont(Font.createFont(Font.TRUETYPE_FONT, new File(fontDir + "NotoSans-Regular.ttf")));
        ge.registerFont(Font.createFont(Font.TRUETYPE_FONT, new File(fontDir + "NotoSans-Bold.ttf")));
        ge.registerFont(Font.createFont(Font.TRUETYPE_FONT, new File(fontDir + "NotoSans-Italic.ttf")));
        ge.registerFont(Font.createFont(Font.TRUETYPE_FONT, new File(fontDir + "NotoSans-BoldItalic.ttf")));
    } catch (IOException | FontFormatException ex) {
        Logging.errorPrint("Unexpected exception loading fonts fo print p", ex);
    }
}

From source file:me.oriley.crate.CrateGenerator.java

@Nullable
private static String getFontName(@NonNull String filePath) {
    try {/*from   w  ww .  j  a  v  a2 s.  com*/
        FileInputStream inputStream = new FileInputStream(filePath);
        Font font = Font.createFont(Font.TRUETYPE_FONT, inputStream);
        inputStream.close();
        return font.getName();
    } catch (FontFormatException | IOException e) {
        e.printStackTrace();
        return null;
    }
}