Class OpenTypeFont

  • All Implemented Interfaces:
    Cloneable

    public class OpenTypeFont
    extends PDFFont

    A subclass of PDFFont that represents an OpenType font. OpenType fonts are a superset of TrueType fonts, but also include fonts where the glyphs are defined using Adobes "Compact Font" format (which are supported since version 2.3 of the library).

    OpenType fonts can be stored by reference only (the font is not embedded into the file), or can be embedded using either one or two bytes per glyph. One byte is only really suitable when the font is using a subset of the ASCII character set - eg. western european characters only. If the font is going to be used to display non-roman characters, two bytes should be used.

    Since 2.22 the WOFF font format can also be read and will be transparently converted to OpenType

    Note: it is highly recommended than OpenTypeFont is not shared across multiple documents. There are two reasons for this:

    • the font is typically subset, meaning only the glyphs that are actually used are embedded in the file. Sharing a font means that the used glyphs will accumulate and the file will be bigger than necessary.
    • An OpenTypeFont is not thread-safe, especially not during a call to PDF.render(java.io.OutputStream).

    The recommend method of sharing an OpenTypeFont is to load it once, then create a new copy for each PDF by calling the OpenTypeFont(org.faceless.pdf2.OpenTypeFont) constructor. This will be much faster than reloading it from the source, new copy will use less memory, and as they're all independent there will be no concurrency issues rendering two copies in two different threads.

      OpenTypeFont original = new OpenTypeFont(new File(...), 2); // Don't use this directly
      OpenTypeFont copy = new OpenTypeFont(original);  // Make one copy for each PDF.
     
    Since:
    2.0 (prior to 2.0 this class was called TrueTypeFont)
    • Constructor Detail

      • OpenTypeFont

        public OpenTypeFont​(OpenTypeFont font)
        Create a new OpenTypeFont that is a copy of the specified OpenTypeFont. If a new copy of the font is required, this method is much faster than reloading the font from disk. The new font will have the default settings for subset, embed and enabled features, ignoring those values from the original font.
        Parameters:
        font - the OpenTypeFont to copy
        Since:
        2.11.10
      • OpenTypeFont

        public OpenTypeFont​(InputStream in,
                            int bytesperglyph)
                     throws IOException
        Create a new OpenTypeFont from the specified InputStream. The InputStream is closed after use.
        Parameters:
        in - the InputStream to read the font from
        bytesperglyph - the number of bytes to use for each glyph. Must be 1 or 2. Thanks to compression there is surprisingly little difference in terms of size in the resulting file, so if in doubt, use 2.
        Throws:
        IOException - if the font cannot be read
        Since:
        2.0
      • OpenTypeFont

        public OpenTypeFont​(int index,
                            InputStream in)
                     throws IOException
        Create a new OpenTypeFont from the specified InputStream, which may contain an OpenType font or an OpenType font collection.
        Parameters:
        index - which font in the TrueType collection to use (usually this value is 0)
        in - the InputStream to read the font from
        Throws:
        IOException - if the font cannot be read
        NoSuchElementException - if the specified subfont is not found
        Since:
        2.18.3
      • OpenTypeFont

        public OpenTypeFont​(int index,
                            URL url)
                     throws IOException
        Deprecated.
        call OpenTypeFont(url) with the index specifed as the URL fragment
        Create a new OpenTypeFont from the specified URL.
        Parameters:
        index - which font in the TrueType collection to use (usually this value is 0)
        url - the URL to load the font from
        Throws:
        IOException - if the font cannot be read
        NoSuchElementException - if the specified subfont is not found
        Since:
        2.21
      • OpenTypeFont

        public OpenTypeFont​(int index,
                            URLConnection con)
                     throws IOException
        Deprecated.
        call OpenTypeFont(con) with the index specifed as the URL fragment
        Create a new OpenTypeFont from the specified URLConnection.
        Parameters:
        index - which font in the TrueType collection to use (usually this value is 0)
        con - the URLConnection to load the font from
        Throws:
        IOException - if the font cannot be read
        NoSuchElementException - if the specified subfont is not found
        Since:
        2.21
      • OpenTypeFont

        public OpenTypeFont​(InputStream in,
                            String subfont)
                     throws IOException

        Create a new OpenTypeFont from the specified InputStream, which may contain an OpenType font or an OpenType font collection.

        If a collection, the subfont parameter determines which of the fonts in the collection should be used. It can be the PostScript name of the subfont, or the index of the subfont e.g. "0", "1".

        Fonts created with this constructor always use two bytes per glyph. The InputStream is read completely and closed after use.

        Parameters:
        in - the InputStream to read the font from
        subfont - for OpenType collections, which font to load as described above, otherwise null.
        Throws:
        IOException - if the font cannot be read
        NoSuchElementException - if the specified subfont is not found
        Since:
        2.23.2
      • OpenTypeFont

        public OpenTypeFont​(File file,
                            String subfont)
                     throws IOException

        Create a new OpenTypeFont from the specified File, which may contain an OpenType font or an OpenType font collection. The font will not be loaded into memory, but the file must exist unchanged for the life of this Object.

        If a collection, the subfont parameter determines which of the fonts in the collection should be used. It can be the PostScript name of the subfont, or the index of the subfont e.g. "0", "1".

        Fonts created with this constructor always use two bytes per glyph.

        Parameters:
        file - the File to read the font from
        subfont - for OpenType collections, which font to load as described above, otherwise null.
        Throws:
        IOException - if the font cannot be read
        NoSuchElementException - if the specified subfont is not found
        Since:
        2.23.2
      • OpenTypeFont

        public OpenTypeFont​(URL url)
                     throws IOException

        Create a new OpenTypeFont from the specified URL. If the URL refers to an HTTP or HTTPS webserver that supports the "Range" header, only the parts of the font that are required will be downloaded. Otherwise the entire URL will be loaded into memory. Fonts loaded this way are always 2-byte fonts.

        • If the URL fragment is empty, the first font in the collection (or a non-collection font) will be loaded.
        • If the URL fragment is a name, it is the PostScript name of the required font in an OpenType collection.
        Parameters:
        url - the URL to load the font from
        Throws:
        IOException - if the font cannot be read
        NoSuchElementException - if the specified subfont is not found
        Since:
        2.23.2
      • OpenTypeFont

        public OpenTypeFont​(URLConnection con,
                            String subfont)
                     throws IOException

        Create a new OpenTypeFont from the specified URLConnection and fragment, to support loading OpenType font collections . If the URLConnection is to an HTTP or HTTPS webserver that supports the "Range" header, only the parts of the font that are required will be downloaded. Otherwise the entire contents of the URL will be loaded into memory Fonts loaded this way are always 2-byte fonts.

        • If the subfont is null or an empty string, the first font in the collection (or a non-collection font) will be loaded.
        • If the subfont is a name, it is the PostScript name of the required font in an OpenType collection.
        Parameters:
        con - the URLConnection to load the font from
        subfont - for OpenTypeFont collections, identifies which font from the Collection to load
        Throws:
        IOException - if the font cannot be read
        NoSuchElementException - if the specified subfont is not found
        Since:
        2.26.3
    • Method Detail

      • getOtherNames

        public List<String> getOtherNames()
        Return a list of other names for the font; these may be in different Locales.
        Since:
        2.22
      • writeCSSFontFace

        public void writeCSSFontFace​(Appendable out,
                                     String uri,
                                     Map<String,​String> extra)
                              throws IOException
        Write the CSS @font-face descriptor to the specified Appendable; if the uri parameter is not-null, use this value for the "uri" of the face. Note this method is unused by the PDF Library but may be useful to those extending it. The @font-face rule is as described in the CSS Fonts Module, 20 October 2014
        Parameters:
        out - the Appendable to write to
        uri - if not null, the URI to
        extra - if not null, a map of additonal CSS properties to include in the output
        Throws:
        IOException
        Since:
        2.22
      • setSubset

        public void setSubset​(boolean subset)
        Whether to "subset" the font by removing unused glyph definitions from the font when it's embedded in the file. This is generally a good thing, unless the font will be used to display text that's not known at PDF creation time (i.e. it's used in a form).
        Parameters:
        subset - whether to subset the font (the default is true)
      • setEmbed

        public void setEmbed​(boolean embed)
        Whether to embed the font in the PDF. Embedding the Font will result in larger files, but the PDF will be readable anywhere - choosing not to embed the font will mean a matching font is required on the system viewing the PDF. If that font is missing, the document cannot guarantee to be displayed correctly. 2-byte fonts are always embedded.
        Parameters:
        embed - whether to embed the font (the default is true)
      • isSubset

        public boolean isSubset()
        Description copied from class: PDFFont
        Return true if this font is Subset
        Overrides:
        isSubset in class PDFFont
      • isEmbedded

        public boolean isEmbedded()
        Description copied from class: PDFFont
        Return true if this font is Embedded
        Overrides:
        isEmbedded in class PDFFont
      • isDefined

        public boolean isDefined​(int unicode)
        Description copied from class: PDFFont
        Return true if the specified Unicode character is defined in the font. This method is identical to PDFFont.isDefined(char) but takes an int, to cater for the new Unicode 4.0 codepoints added in Java 1.5.
        Overrides:
        isDefined in class PDFFont
        Parameters:
        unicode - a Unicode codepoint between U+0000 and U+10FFFD
      • getEmbeddingRestrictions

        public String getEmbeddingRestrictions()
        Returns null if the font can be embedded without any restrictions, or a non-null String if the font has embedding restrictions. Note the library will not prevent you from using a font with embedding restrictions unless you have set the OutputProfile.Feature.FontEmbeddingRestrictions feature - it's your responsibility to ensure you have the right to embed the font. The content of the String is undefined but is intended to detail the restriction type.
        Since:
        2.7.8
      • getUnitsPerEm

        public int getUnitsPerEm()
        Return the fonts "units per em"
        Since:
        2.22.2
      • getMetaData

        public Reader getMetaData()
                           throws IOException
        Description copied from class: PDFFont

        Return any XML metadata associated with this object.

        Since 2.26 this simply returns getXMP().isEmpty() ? null : new StringReader(getXMP().toString()). It is strongly recommended that any code migrates to using the PDFFont.getXMP() method.

        Since 2.24.3, the returned type is guaranteed to hava a toString() method that will return the Metadata as a String.

        Overrides:
        getMetaData in class PDFFont
        Returns:
        a Reader containing the source of the XML or null if no metadata is available.
        Throws:
        IOException - if the metadata can't be extracted
      • setMetaData

        public void setMetaData​(String s)
        Description copied from class: PDFFont

        Set the XML metadata associated with this object. Since 2.26 this method calls getXMP().read(new StringReader(xmldata == null ? "" : xmldata)). We strongly recommend using the PDFFont.getXMP() method and modifying the XMP directly rather than using this method.

        Note for OpenType WOFF and WOFF2 fonts, the MetaData is transformed from the schema described in https://www.w3.org/TR/WOFF/#Metadata to an approximation of the same schema within the limitations of XMP.

        Overrides:
        setMetaData in class PDFFont
        Parameters:
        s - the XML data to embed into the document, or null to clear any existing metadata. No validation is performed on this input.
      • getDefaultLeading

        public float getDefaultLeading()
        Description copied from class: PDFFont

        Get the default leading for this font - the preferred distance between two successive baselines of text. Values are a ratio of the font size, and are typically between 1 and 1.3

        Note that the values of the different spacing-between-lines methods have changed - in versions 1.0.4 and earlier this routine normally returned 1 and the spacing was set by the PDFStyle.setTextLineSpacing(float) method. Since 1.1, the values for these two methods are effectively reversed. See the relevant method comments in the PDFStyle class for more information.

        Specified by:
        getDefaultLeading in class PDFFont
      • getDescender

        public float getDescender()
        Description copied from class: PDFFont
        Get the Descender for the font (the maximum height below the baseline the font extends), as a proportion of the point size. The returned value is usually negative. The exact source of this value is undefined except for OpenTypeFonts, where it comes from the "hhea.descender" value normally, or the from "OS2.sTypoDescender" flag if the USE_TYPO_METRICS flag is set.
        Specified by:
        getDescender in class PDFFont
      • getAscender

        public float getAscender()
        Description copied from class: PDFFont
        Get the Ascender for the font (the maximum height above the baseline the font extends), as a proportion of the point size. The exact source of of this value is undefined except for OpenTypeFonts, where it comes from the "hhea.ascender" value normally, or the from "OS2.sTypoAscender" flag if the USE_TYPO_METRICS flag is set.
        Specified by:
        getAscender in class PDFFont
      • getUnderlinePosition

        public float getUnderlinePosition()
        Description copied from class: PDFFont
        Get the underline position, as a proportion of the font size. Like the getDescender() method, the returned value is almost always negative, indicating below the baseline. The distance is from the baseline to the center of the underline.
        Specified by:
        getUnderlinePosition in class PDFFont
      • getUnderlineThickness

        public float getUnderlineThickness()
        Description copied from class: PDFFont
        Get the underline thickness, as a proportion of the font size.
        Specified by:
        getUnderlineThickness in class PDFFont
      • getStrikeoutPosition

        public float getStrikeoutPosition()
        Description copied from class: PDFFont
        Get the strikeout position, as a proportion of the font size. The value is the distance from the baseline to the center of the strikeout, and shuold be positive.
        Specified by:
        getStrikeoutPosition in class PDFFont
      • getStrikeoutThickness

        public float getStrikeoutThickness()
        Description copied from class: PDFFont
        Get the strikeout thickness, as a proportion of the font size.
        Specified by:
        getStrikeoutThickness in class PDFFont
      • getSuperscriptPosition

        public float getSuperscriptPosition()
        Description copied from class: PDFFont

        Get the recommended position of a super-script version of this font, as a proportion of the sub-scripted font size. Value is always positive.

        For some fonts (like CJK or barcode fonts) where there is no concept of super or subscript, this value is entirely arbitrary.

        Specified by:
        getSuperscriptPosition in class PDFFont
      • getSubscriptPosition

        public float getSubscriptPosition()
        Description copied from class: PDFFont

        Get the recommended position of a sub-script version of this font, as a proportion of the sub-scripted font size. Value is almost always zero or negative.

        For some fonts (like CJK or barcode fonts) where there is no concept of super or subscript, this value is entirely arbitrary.

        Specified by:
        getSubscriptPosition in class PDFFont
      • getSubscriptSize

        public float getSubscriptSize()
        Description copied from class: PDFFont

        Get the recommended size of a super/sub script version of this font, as a proportion of the normal font size. Typical value is around 0.6.

        For some fonts (like CJK or barcode fonts) where there is no concept of super or subscript, this value is entirely arbitrary.

        Specified by:
        getSubscriptSize in class PDFFont
      • getXHeight

        public float getXHeight()
        Description copied from class: PDFFont
        Get the X-Height of the font - normally the height of a lower-case 'x' character.
        Specified by:
        getXHeight in class PDFFont
      • getCapHeight

        public float getCapHeight()
        Description copied from class: PDFFont
        Get the Cap-Height of the font - normally the height of an upper-case 'O' character
        Specified by:
        getCapHeight in class PDFFont
      • isMonospace

        public boolean isMonospace()
        Description copied from class: PDFFont
        Return true if every character has the same width (like Courier), false if every character is potentially a different width (like Times-Roman)
        Specified by:
        isMonospace in class PDFFont
      • isItalic

        public boolean isItalic()
        Description copied from class: PDFFont
        Return true if the font is italic
        Specified by:
        isItalic in class PDFFont
      • isBold

        public boolean isBold()
        Description copied from class: PDFFont
        Return true if the font is bold
        Specified by:
        isBold in class PDFFont
      • isSerif

        public boolean isSerif()
        Description copied from class: PDFFont
        Return true if the font is serif
        Specified by:
        isSerif in class PDFFont
      • getPostScriptName

        public String getPostScriptName()
        Return the "PostScript" name of the font. This is a name that only applies to OpenType fonts, and it can be useful to select between different sub-fonts in an OpenType collection
        Since:
        2.23.2
      • getDefinedCodepoints

        public BitSet getDefinedCodepoints()
        Description copied from class: PDFFont
        Return read-only BitSet containing all the Unicode codepoints defined in this font
        Specified by:
        getDefinedCodepoints in class PDFFont
      • setFeature

        public void setFeature​(String feature,
                               int value)

        Set or clear an optional feature on a font. Some OpenType fonts have GPOS and GSUB tables which can be used to modify the glyphs that are displayed. This is required to display some languages correctly.

        To enable this type of glyph shaping, the font must be created using a 2-byte encoding and the "opentype" feature must first be set. This will cause the default set of OpenType features to be used for layout. The full list of features available in the font can be seen by calling the getAvailableFeatures() method (go here for their explanations), and individual features may then be turned on or off as required. Features that are required for correct layout (the case for Indic and Arabic scripts) will be selected by default when the "opentype" feature is set.

        By default, OpenType layout is not used, as it is considerably slower. The langauge of the Locale can affect which operations are run, so this should be set with care.

        The "correctleading" feature can be set to use the correct calculation for getDefaultLeading() rather than the one originally used in the PDF Library. For many fonts the two calculations will give similar, often identical results, but for some fonts it won't so we can't change this calculation by default without forcing a re-layout of many existing documents. However we recommend setting this feature for all new documents. The initial value of this feature can be set to true by setting the OpenTypeCorrectLeading property

        If the OpenType font contains "math" layout tables, and the single-character being formatted is a "stretchy" chracter, then the math.stretch feature can always be set to the desired width of the glyph by calling setFeature("math.stretch", Font.floatToIntBits(size)) where size is the desired size of the glyph in points. This is new in 2.24.1

        Overrides:
        setFeature in class PDFFont
        Parameters:
        feature - the feature name
        value - 0 to turn the feature on, greater-than-zero to turn it on (if the feature has a particular variation, the value will determine which variation to use)
        Since:
        2.11.22
      • getFeature

        public int getFeature​(String feature)
        Description copied from class: PDFFont
        Returns whether the specified feature is currently set for this font. A value of 0 means not set, any other value means it is set - for most features that is enough, but a few will make use of the actual value to select between different variations of the feature, say for swash capitals. This method provides a default value for the value returned by PDFStyle.getFontFeature(java.lang.String).
        Overrides:
        getFeature in class PDFFont
        Parameters:
        feature - the feature name
        Returns:
        0 for off, or a value greater-than-or-equal to 1 for on.
        See Also:
        PDFStyle.getFontFeature(java.lang.String)
      • getRight

        public float getRight​(String s)
        Description copied from class: PDFFont
        Get the right-most X co-ordinate if this String was rendered in 1 point high text at position (0,0). This method will make it's calculation based on the features set on this font: the PDFStyle.getTextLength(java.lang.String) method can be used to perform the same calculation based on the values set in the style.
        Overrides:
        getRight in class PDFFont
      • getOpenTypeBaseline

        public float getOpenTypeBaseline​(int script,
                                         int baseline)
        For OpenType fonts containing a BASE table, return the baseline that matches the specified script and baseline entry (scaled as if the font if it was 1pt high), or Float.NaN if no such entry exists. It is unlikely this method will be useful for anyone not doing advanced layout.
        Parameters:
        script - the OpenType script tag, encoded as a 4-byte integer, eg 0x6c61746e for "latn"
        baseline - the OpenType baseline tag, encoded as a 4-byte integer, eg 0x6964656f for "ideo"
        Since:
        2.23.2
      • getMathConstant

        public float getMathConstant​(String name)
        If the OpenTypeFont has "math" features, return the specified constant from the font, otherwise return Float.NaN
        Since:
        2.24.1
      • getCharacterMapping

        public String getCharacterMapping​(int cid)
        For a given glyph id, try to find a Unicode value that will map to it. This is not always possible, and if not this method will return 0. This is a reverse lookup and can be quite expensive to run, and is not for general use.
        Since:
        2.24.2
        See Also:
        PDFGlyphVector.getCID(int)
      • toString

        public String toString()
      • putLiteral

        public void putLiteral​(String key,
                               String tokens)
        Put a literal token sequnce. For debugging
        Parameters:
        key - the key
        tokens - the token sequence, eg "true" or "/foo" or "[/Foo/Bar]". No refs, just direct objects.