Example usage for com.lowagie.text.pdf BaseFont createFont

List of usage examples for com.lowagie.text.pdf BaseFont createFont

Introduction

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

Prototype

public static BaseFont createFont(String name, String encoding, boolean embedded, boolean cached, byte ttfAfm[],
        byte pfb[]) throws DocumentException, IOException 

Source Link

Document

Creates a new font.

Usage

From source file:org.pentaho.reporting.libraries.fonts.itext.BaseFontSupport.java

License:Open Source License

/**
 * Creates a BaseFontRecord for an font.  If no basefont could be created, an BaseFontCreateException is thrown.
 *
 * @param logicalName the name of the font (null not permitted).
 * @param bold        a flag indicating whether the font is rendered as bold font.
 * @param italic      a flag indicating whether the font is rendered as italic or cursive font.
 * @param encoding    the encoding./*from www.  ja  v a  2  s  .c o m*/
 * @param embedded    a flag indicating whether to embed the font glyphs in the generated documents.
 * @return the base font record.
 * @throws BaseFontCreateException if there was a problem setting the font for the target.
 */
public BaseFontRecord createBaseFontRecord(final String logicalName, final boolean bold, final boolean italic,
        String encoding, final boolean embedded) throws BaseFontCreateException {
    if (logicalName == null) {
        throw new NullPointerException("Font definition is null.");
    }
    if (encoding == null) {
        encoding = getDefaultEncoding();
    }

    // use the Java logical font name to map to a predefined iText font.

    final String fontKey;
    if (FontMappingUtility.isCourier(logicalName)) {
        fontKey = "Courier";
    } else if (FontMappingUtility.isSymbol(logicalName)) {
        fontKey = "Symbol";
    } else if (FontMappingUtility.isSerif(logicalName)) {
        fontKey = "Times";
    } else if (FontMappingUtility.isSansSerif(logicalName)) {
        // default, this catches Dialog and SansSerif
        fontKey = "Helvetica";
    } else {
        fontKey = logicalName;
    }

    // iText uses some weird mapping between IDENTY-H/V and java supported encoding, IDENTITY-H/V is
    // used to recognize TrueType fonts, but the real JavaEncoding is used to encode Type1 fonts
    final String stringEncoding;
    if ("utf-8".equalsIgnoreCase(encoding)) {
        stringEncoding = "utf-8";
        encoding = BaseFont.IDENTITY_H;
    } else if ("utf-16".equalsIgnoreCase(encoding)) {
        stringEncoding = "utf-16";
        encoding = BaseFont.IDENTITY_H;
    } else {
        // Correct the encoding for truetype fonts
        // iText will crash if IDENTITY_H is used to create a base font ...
        if (encoding.equalsIgnoreCase(BaseFont.IDENTITY_H) || encoding.equalsIgnoreCase(BaseFont.IDENTITY_V)) {
            //changed to UTF to support all unicode characters ..
            stringEncoding = "utf-8";
        } else {
            stringEncoding = encoding;
        }
    }

    try {
        final FontFamily registryFontFamily = registry.getFontFamily(fontKey);
        FontRecord registryFontRecord = null;
        if (registryFontFamily != null) {
            registryFontRecord = registryFontFamily.getFontRecord(bold, italic);

            if (registryFontRecord instanceof CompoundFontRecord) {
                final CompoundFontRecord cfr = (CompoundFontRecord) registryFontRecord;
                registryFontRecord = cfr.getBase();
            }
        }

        if (registryFontRecord != null) {
            // Check, whether this is an built-in font. If not, then the record points to a file.
            if ((registryFontRecord instanceof ITextBuiltInFontRecord) == false) {

                boolean embeddedOverride = embedded;
                if (embedded == true && registryFontRecord instanceof FontSource) {
                    final FontSource source = (FontSource) registryFontRecord;
                    if (source.isEmbeddable() == false) {
                        logger.warn("License of font forbids embedded usage for font: " + fontKey);
                        // strict mode here?
                        embeddedOverride = false;
                    }
                }

                final BaseFontRecord fontRecord = createFontFromTTF(registryFontRecord, bold, italic, encoding,
                        stringEncoding, embeddedOverride);
                if (fontRecord != null) {
                    return fontRecord;
                }
            } else {
                final ITextBuiltInFontRecord buildInFontRecord = (ITextBuiltInFontRecord) registryFontRecord;
                // So this is one of the built-in records.
                final String fontName = buildInFontRecord.getFullName();

                // Alternative: No Registered TrueType font was found. OK; don't panic,
                // we try to create a font anyway..

                BaseFontRecord fontRecord = getFromCache(fontName, encoding, embedded);
                if (fontRecord != null) {
                    return fontRecord;
                }
                fontRecord = getFromCache(fontName, stringEncoding, embedded);
                if (fontRecord != null) {
                    return fontRecord;
                }

                // filename is null, so no ttf file registered for the fontname, maybe this is
                // one of the internal fonts ...
                final BaseFont f = BaseFont.createFont(fontName, stringEncoding, embedded, useGlobalCache, null,
                        null);
                if (f != null) {
                    fontRecord = new BaseFontRecord(fontName, false, embedded, f, bold, italic);
                    putToCache(fontRecord);
                    return fontRecord;
                }
            }
        }

        // If we got to this point, then the font was not recognized as any known font. We will fall back
        // to Helvetica instead ..
    } catch (Exception e) {
        if (logger.isDebugEnabled()) {
            logger.debug("BaseFont.createFont failed. Key = " + fontKey + ": " + e.getMessage(), e);
        } else if (logger.isWarnEnabled()) {
            logger.warn("BaseFont.createFont failed. Key = " + fontKey + ": " + e.getMessage(), e);
        }
    }
    // fallback .. use BaseFont.HELVETICA as default
    try {
        // check, whether HELVETICA is already created - yes, then return cached instance instead
        BaseFontRecord fontRecord = getFromCache(BaseFont.HELVETICA, stringEncoding, embedded);
        if (fontRecord != null) {
            // map all font references of the invalid font to the default font..
            // this might be not very nice, but at least the report can go on..
            putToCache(new BaseFontRecordKey(fontKey, encoding, embedded), fontRecord);
            return fontRecord;
        }

        // no helvetica created, so do this now ...
        final BaseFont f = BaseFont.createFont(BaseFont.HELVETICA, stringEncoding, embedded, useGlobalCache,
                null, null);
        if (f != null) {
            fontRecord = new BaseFontRecord(BaseFont.HELVETICA, false, embedded, f, bold, italic);
            putToCache(fontRecord);
            putToCache(new BaseFontRecordKey(fontKey, encoding, embedded), fontRecord);
            return fontRecord;
        }
    } catch (Exception e) {
        logger.warn("BaseFont.createFont for FALLBACK failed.", e);
        throw new BaseFontCreateException("Null font = " + fontKey);
    }
    throw new BaseFontCreateException("BaseFont creation failed, null font: " + fontKey);
}

From source file:org.pentaho.reporting.libraries.fonts.itext.BaseFontSupport.java

License:Open Source License

/**
 * Creates a PDF font record from a true type font.
 *
 * @param encoding       the encoding.//from  w  w  w . ja v  a2 s .  c om
 * @param stringEncoding the string encoding.
 * @param embedded       a flag indicating whether to embed the font glyphs in the generated documents.
 * @return the PDF font record.
 * @throws com.lowagie.text.DocumentException if the BaseFont could not be created.
 */
private BaseFontRecord createFontFromTTF(final FontRecord fontRecord, final boolean bold, final boolean italic,
        final String encoding, final String stringEncoding, final boolean embedded) throws DocumentException {
    // check if this font is in the cache ...
    //Log.warn ("TrueTypeFontKey : " + fontKey + " Font: " + font.isItalic() + " Encoding: "
    //          + encoding);
    final String rawFilename;
    if (fontRecord instanceof TrueTypeFontRecord) {
        final TrueTypeFontRecord ttfRecord = (TrueTypeFontRecord) fontRecord;
        if (ttfRecord.getCollectionIndex() >= 0) {
            rawFilename = ttfRecord.getFontSource() + ',' + ttfRecord.getCollectionIndex();
        } else {
            rawFilename = ttfRecord.getFontSource();
        }
    } else if (fontRecord instanceof FontSource) {
        final FontSource source = (FontSource) fontRecord;
        rawFilename = source.getFontSource();
    } else {
        return null;
    }

    final String filename;
    // check, whether the the physical font does not provide some of the
    // required styles. We have to synthesize them, if neccessary
    if ((fontRecord.isBold() == false && bold) && (fontRecord.isItalic() == false && italic)) {
        filename = rawFilename + ",BoldItalic";
    } else if (fontRecord.isBold() == false && bold) {
        filename = rawFilename + ",Bold";
    } else if (fontRecord.isItalic() == false && italic) {
        filename = rawFilename + ",Italic";
    } else {
        filename = rawFilename;
    }

    final BaseFontRecord fontRec = getFromCache(filename, encoding, embedded);
    if (fontRec != null) {
        return fontRec;
    }

    BaseFont f;
    try {
        try {
            f = BaseFont.createFont(filename, encoding, embedded, false, null, null);
        } catch (DocumentException e) {
            f = BaseFont.createFont(filename, stringEncoding, embedded, false, null, null);
        }
    } catch (IOException ioe) {
        throw new DocumentException("Failed to read the font: " + ioe);
    }

    // no, we have to create a new instance
    final BaseFontRecord record = new BaseFontRecord(filename, true, embedded, f, fontRecord.isBold(),
            fontRecord.isItalic());
    putToCache(record);
    return record;
}

From source file:org.xhtmlrenderer.pdf.ITextFontResolver.java

License:Open Source License

private void addFontFaceFont(String fontFamilyNameOverride, IdentValue fontWeightOverride,
        IdentValue fontStyleOverride, String uri, String encoding, boolean embedded, byte[] afmttf, byte[] pfb)
        throws DocumentException, IOException {
    String lower = uri.toLowerCase();
    if (lower.endsWith(".otf") || lower.endsWith(".ttf") || lower.indexOf(".ttc,") != -1) {
        BaseFont font = BaseFont.createFont(uri, encoding, embedded, false, afmttf, pfb);

        String[] fontFamilyNames;
        if (fontFamilyNameOverride != null) {
            fontFamilyNames = new String[] { fontFamilyNameOverride };
        } else {/* w  w w.  java2  s .  co  m*/
            fontFamilyNames = TrueTypeUtil.getFamilyNames(font);
        }

        for (int i = 0; i < fontFamilyNames.length; i++) {
            FontFamily fontFamily = getFontFamily(fontFamilyNames[i]);

            FontDescription descr = new FontDescription(font);
            try {
                TrueTypeUtil.populateDescription(uri, afmttf, font, descr);
            } catch (Exception e) {
                throw new XRRuntimeException(e.getMessage(), e);
            }

            descr.setFromFontFace(true);

            if (fontWeightOverride != null) {
                descr.setWeight(convertWeightToInt(fontWeightOverride));
            }

            if (fontStyleOverride != null) {
                descr.setStyle(fontStyleOverride);
            }

            fontFamily.addFontDescription(descr);
        }
    } else if (lower.endsWith(".afm") || lower.endsWith(".pfm") || lower.endsWith(".pfb")
            || lower.endsWith(".pfa")) {
        if (embedded && pfb == null) {
            throw new IOException("When embedding a font, path to PFB/PFA file must be specified");
        }

        String name = uri.substring(0, uri.length() - 4) + ".afm";
        BaseFont font = BaseFont.createFont(name, encoding, embedded, false, afmttf, pfb);

        String fontFamilyName = font.getFamilyFontName()[0][3];
        FontFamily fontFamily = getFontFamily(fontFamilyName);

        FontDescription descr = new FontDescription(font);
        descr.setFromFontFace(true);
        // XXX Need to set weight, underline position, etc.  This information
        // is contained in the AFM file (and even parsed by Type1Font), but
        // unfortunately it isn't exposed to the caller.
        fontFamily.addFontDescription(descr);
    } else {
        throw new IOException("Unsupported font type");
    }
}