Create and add a new embedding {@link PreloadFont} if it is not yet
contained.

@param aFontRes
The font resource to be added for embedding. May not be
<code>null</code>.
@return The created {@link PreloadFont}. Never <code>null</code>.
177784
@Nonnull
  public PreloadFont getOrAddEmbeddingPreloadFont (@Nonnull final IFontResource aFontRes)
  {
    ValueEnforcer.notNull (aFontRes, "FontRes");
    PreloadFont aPreloadFont = getPreloadFontOfID (aFontRes);
    if (aPreloadFont == null)
    {
      aPreloadFont = PreloadFont.createEmbedding (aFontRes);
      addPreloadFont (aPreloadFont);
    }
    return aPreloadFont;
  }
468948
function FontpathRenderer(options) {
    if (!(this instanceof FontpathRenderer))
        return new FontpathRenderer(options)
    Base.call(this, options)

    this.data = {
        glyphs: [],
        underlines: []
    }
}
1018468
def add_font(self, family, style='', fname='', uni=False):
        ""
        family = family.lower()
        if (fname == ''):
            fname = family.replace(' ','') + style.lower() + '.pkl'
        if (family == 'arial'):
            family = 'helvetica'
        style = style.upper()
        if (style == 'IB'):
            style = 'BI'
        fontkey = family+style
        if fontkey in self.fonts:
            # Font already added!
            return
        if (uni):
            global SYSTEM_TTFONTS, FPDF_CACHE_MODE, FPDF_CACHE_DIR
            if os.path.exists(fname):
                ttffilename = fname
            elif (FPDF_FONT_DIR and
                os.path.exists(os.path.join(FPDF_FONT_DIR, fname))):
                ttffilename = os.path.join(FPDF_FONT_DIR, fname)
            elif (SYSTEM_TTFONTS and
                os.path.exists(os.path.join(SYSTEM_TTFONTS, fname))):
                ttffilename = os.path.join(SYSTEM_TTFONTS, fname)
            else:
                raise RuntimeError("TTF Font file not found: %s" % fname)
            name = ''
            if FPDF_CACHE_MODE == 0:
                unifilename = os.path.splitext(ttffilename)[0] + '.pkl'
            elif FPDF_CACHE_MODE == 2:                
                unifilename = os.path.join(FPDF_CACHE_DIR, \
                    hashpath(ttffilename) + ".pkl")
            else:
                unifilename = None
            if unifilename and os.path.exists(unifilename):
                fh = open(unifilename, "rb")
                try:
                    font_dict = pickle.load(fh)
                finally:
                    fh.close()
            else:
                ttf = TTFontFile()
                ttf.getMetrics(ttffilename)
                desc = {
                    'Ascent': int(round(ttf.ascent, 0)),
                    'Descent': int(round(ttf.descent, 0)),
                    'CapHeight': int(round(ttf.capHeight, 0)),
                    'Flags': ttf.flags,
                    'FontBBox': "[%s %s %s %s]" % (
                        int(round(ttf.bbox[0], 0)),
                        int(round(ttf.bbox[1], 0)),
                        int(round(ttf.bbox[2], 0)),
                        int(round(ttf.bbox[3], 0))),
                    'ItalicAngle': int(ttf.italicAngle),
                    'StemV': int(round(ttf.stemV, 0)),
                    'MissingWidth': int(round(ttf.defaultWidth, 0)),
                    }
                # Generate metrics .pkl file
                font_dict = {
                    'name': re.sub('[ ()]', '', ttf.fullName),
                    'type': 'TTF',
                    'desc': desc,
                    'up': round(ttf.underlinePosition),
                    'ut': round(ttf.underlineThickness),
                    'ttffile': ttffilename,
                    'fontkey': fontkey,
                    'originalsize': os.stat(ttffilename).st_size,
                    'cw': ttf.charWidths,
                    }
                if unifilename:
                    try:
                        fh = open(unifilename, "wb")
                        pickle.dump(font_dict, fh)
                        fh.close()
                    except IOError:
                        if not exception().errno == errno.EACCES:
                            raise  # Not a permission error.
                del ttf
            if hasattr(self,'str_alias_nb_pages'):
                sbarr = list(range(0,57))   # include numbers in the subset!
            else:
                sbarr = list(range(0,32))
            self.fonts[fontkey] = {
                'i': len(self.fonts)+1, 'type': font_dict['type'],
                'name': font_dict['name'], 'desc': font_dict['desc'],
                'up': font_dict['up'], 'ut': font_dict['ut'],
                'cw': font_dict['cw'],
                'ttffile': font_dict['ttffile'], 'fontkey': fontkey,
                'subset': sbarr, 'unifilename': unifilename,
                }
            self.font_files[fontkey] = {'length1': font_dict['originalsize'],
                                        'type': "TTF", 'ttffile': ttffilename}
            self.font_files[fname] = {'type': "TTF"}
        else:
            fontfile = open(fname)
            try:
                font_dict = pickle.load(fontfile)
            finally:
                fontfile.close()
            self.fonts[fontkey] = {'i': len(self.fonts)+1}
            self.fonts[fontkey].update(font_dict)
            if (diff):
                #Search existing encodings
                d = 0
                nb = len(self.diffs)
                for i in range(1, nb+1):
                    if(self.diffs[i] == diff):
                        d = i
                        break
                if (d == 0):
                    d = nb + 1
                    self.diffs[d] = diff
                self.fonts[fontkey]['diff'] = d
            filename = font_dict.get('filename')
            if (filename):
                if (type == 'TrueType'):
                    self.font_files[filename]={'length1': originalsize}
                else:
                    self.font_files[filename]={'length1': size1,
                                               'length2': size2}
669908
@Nonnull
  public ExcelStyle setFont (@Nonnull final Font aFont)
  {
    ValueEnforcer.notNull (aFont, "Font");
    return setFontIndex (aFont.getIndexAsInt ());
  }
713300
private Font buildFamilyFont(final FamilyFont familyFont) {
        Font font = null;
        if (familyFont.posture() == null && familyFont.weight() == null) {
            font = Font.font(transformFontName(familyFont.family()), familyFont.size());
        } else if (familyFont.posture() == null) {
            font = Font.font(transformFontName(familyFont.family()), familyFont.weight(), familyFont.size());
        } else if (familyFont.weight() == null) {
            font = Font.font(transformFontName(familyFont.family()), familyFont.posture(), familyFont.size());
        } else {
            font = Font.font(transformFontName(familyFont.family()), familyFont.weight(), familyFont.posture(), familyFont.size());
        }
        return font;
    }
822389
public static TextSymbolizerInfo createSymbolizer(FontStyleInfo style) {
		TextSymbolizerInfo symbolizerInfo = new TextSymbolizerInfo();
		FontInfo font = new FontInfo();
		font.setFamily(style.getFamily());
		font.setStyle(style.getStyle());
		font.setWeight(style.getWeight());
		font.setSize(style.getSize());
		symbolizerInfo.setFont(font);
		symbolizerInfo.setFill(createFill(style.getColor(), style.getOpacity()));
		return symbolizerInfo;
	}
621765
public static Font findCompatibleFont(final String text, final Font fallbackFont) {
        final String[] searchFonts = new String[] { Font.SANS_SERIF, Font.SERIF, "Verdana", "Arial Unicode MS",
                "MS UI Gothic", "MS Mincho", "MS Gothic", "Osaka" };
        for (final String fontName : searchFonts) {
            Font font = fonts.get(fontName);
            if (font == null) {
                font = new Font(fontName, fallbackFont.getStyle(), fallbackFont.getSize());
            }

            if (font.canDisplayUpTo(text) == -1) {
                logger.info("Font '{}' was capable, returning", fontName);
                font = font.deriveFont(fallbackFont.getSize2D());
                return font;
            }
        }

        logger.warn("Didn't find any capable fonts for text '{}'", text);
        return fallbackFont;
    }
607573
public void setFont(Font font) {
		super.setFont(font);

		if (dayChooser != null) {
			dayChooser.setFont(font);
			monthChooser.setFont(font);
			yearChooser.setFont(font);
		}
	}
935986
public BaseFont awtToPdf(Font font) {
        try {
            BaseFontParameters p = getBaseFontParameters(font.getFontName());
            if (p != null)
                return BaseFont.createFont(p.fontName, p.encoding, p.embedded, p.cached, p.ttfAfm, p.pfb);
            String fontKey = null;
            String logicalName = font.getName();

            if (logicalName.equalsIgnoreCase("DialogInput") || logicalName.equalsIgnoreCase("Monospaced") || logicalName.equalsIgnoreCase("Courier")) {

                if (font.isItalic()) {
                    if (font.isBold()) {
                        fontKey = BaseFont.COURIER_BOLDOBLIQUE;

                    } else {
                        fontKey = BaseFont.COURIER_OBLIQUE;
                    }

                } else {
                    if (font.isBold()) {
                        fontKey = BaseFont.COURIER_BOLD;

                    } else {
                        fontKey = BaseFont.COURIER;
                    }
                }

            } else if (logicalName.equalsIgnoreCase("Serif") || logicalName.equalsIgnoreCase("TimesRoman")) {

                if (font.isItalic()) {
                    if (font.isBold()) {
                        fontKey = BaseFont.TIMES_BOLDITALIC;

                    } else {
                        fontKey = BaseFont.TIMES_ITALIC;
                    }

                } else {
                    if (font.isBold()) {
                        fontKey = BaseFont.TIMES_BOLD;

                    } else {
                        fontKey = BaseFont.TIMES_ROMAN;
                    }
                }

            } else {  // default, this catches Dialog and SansSerif

                if (font.isItalic()) {
                    if (font.isBold()) {
                        fontKey = BaseFont.HELVETICA_BOLDOBLIQUE;

                    } else {
                        fontKey = BaseFont.HELVETICA_OBLIQUE;
                    }

                } else {
                    if (font.isBold()) {
                        fontKey = BaseFont.HELVETICA_BOLD;
                    } else {
                        fontKey = BaseFont.HELVETICA;
                    }
                }
            }
            return BaseFont.createFont(fontKey, BaseFont.CP1252, false);
        }
        catch (Exception e) {
            throw new ExceptionConverter(e);
        }
    }
172648
protected void CreateNewStringIndex(int Font)
	{
        String fdFontName = fonts[Font].name+"-OneRange";
        if (fdFontName.length() > 127)
            fdFontName = fdFontName.substring(0,127);
        String extraStrings = "Adobe"+"Identity"+fdFontName;
        
        int origStringsLen = stringOffsets[stringOffsets.length-1]
        - stringOffsets[0];
        int stringsBaseOffset = stringOffsets[0]-1;
        
        byte stringsIndexOffSize;
        if (origStringsLen+extraStrings.length() <= 0xff) stringsIndexOffSize = 1;
        else if (origStringsLen+extraStrings.length() <= 0xffff) stringsIndexOffSize = 2;
        else if (origStringsLen+extraStrings.length() <= 0xffffff) stringsIndexOffSize = 3;
        else stringsIndexOffSize = 4;
        
        OutputList.addLast(new UInt16Item((char)((stringOffsets.length-1)+3))); // count
        OutputList.addLast(new UInt8Item((char)stringsIndexOffSize)); // offSize
        for (int i=0; i<stringOffsets.length; i++)
            OutputList.addLast(new IndexOffsetItem(stringsIndexOffSize,
            stringOffsets[i]-stringsBaseOffset));
        int currentStringsOffset = stringOffsets[stringOffsets.length-1]
        - stringsBaseOffset;
        //l.addLast(new IndexOffsetItem(stringsIndexOffSize,currentStringsOffset));
        currentStringsOffset += "Adobe".length();
        OutputList.addLast(new IndexOffsetItem(stringsIndexOffSize,currentStringsOffset));
        currentStringsOffset += "Identity".length();
        OutputList.addLast(new IndexOffsetItem(stringsIndexOffSize,currentStringsOffset));
        currentStringsOffset += fdFontName.length();
        OutputList.addLast(new IndexOffsetItem(stringsIndexOffSize,currentStringsOffset));
        
        OutputList.addLast(new RangeItem(buf,stringOffsets[0],origStringsLen));
        OutputList.addLast(new StringItem(extraStrings));
    }
     
	/**
	 * Function creates new FDSelect for non-CID fonts.
	 * The FDSelect built uses a single range for all glyphs
	 * @param fdselectRef OffsetItem for the FDSelect
	 * @param nglyphs the number of glyphs in the font
	 */
	protected void CreateFDSelect(OffsetItem fdselectRef,int nglyphs)
	{
		OutputList.addLast(new MarkerItem(fdselectRef));
	    OutputList.addLast(new UInt8Item((char)3)); // format identifier
	    OutputList.addLast(new UInt16Item((char)1)); // nRanges
	    
	    OutputList.addLast(new UInt16Item((char)0)); // Range[0].firstGlyph
	    OutputList.addLast(new UInt8Item((char)0)); // Range[0].fd
	    
	    OutputList.addLast(new UInt16Item((char)nglyphs)); // sentinel
	}

	/**
	 * Function creates new CharSet for non-CID fonts.
	 * The CharSet built uses a single range for all glyphs
	 * @param charsetRef OffsetItem for the CharSet
	 * @param nglyphs the number of glyphs in the font
	 */
	protected void CreateCharset(OffsetItem charsetRef,int nglyphs)
	{
		OutputList.addLast(new MarkerItem(charsetRef));
	    OutputList.addLast(new UInt8Item((char)2)); // format identifier
	    OutputList.addLast(new UInt16Item((char)1)); // first glyph in range (ignore .notdef)
	    OutputList.addLast(new UInt16Item((char)(nglyphs-1))); // nLeft
	}
    
	/**
	 * Function creates new FDArray for non-CID fonts.
	 * The FDArray built has only the "Private" operator that points to the font's
	 * original private dict 
	 * @param fdarrayRef OffsetItem for the FDArray
	 * @param privateRef OffsetItem for the Private Dict
	 * @param Font the font
	 */
	protected void CreateFDArray(OffsetItem fdarrayRef,OffsetItem privateRef,int Font)
	{
		OutputList.addLast(new MarkerItem(fdarrayRef));
		// Build the header (count=offsize=first=1)
		BuildIndexHeader(1,1,1);
	    
		// Mark
	    OffsetItem privateIndex1Ref = new IndexOffsetItem(1);
	    OutputList.addLast(privateIndex1Ref);
	    IndexBaseItem privateBase = new IndexBaseItem();
	    // Insert the private operands and operator
	    OutputList.addLast(privateBase);
	    // Calc the new size of the private after subsetting
	    // Origianl size
	    int NewSize = fonts[Font].privateLength;
	    // Calc the original size of the Subr offset in the private
		int OrgSubrsOffsetSize = CalcSubrOffsetSize(fonts[Font].privateOffset,fonts[Font].privateLength);
		// Increase the ptivate's size
		if (OrgSubrsOffsetSize != 0)
			NewSize += 5-OrgSubrsOffsetSize;
	    OutputList.addLast(new DictNumberItem(NewSize));
	    OutputList.addLast(privateRef);
	    OutputList.addLast(new UInt8Item((char)18)); // Private
	    
	    OutputList.addLast(new IndexMarkerItem(privateIndex1Ref,privateBase));
	}
    
	/**
	 * Function reconstructs the FDArray, PrivateDict and LSubr for CID fonts
	 * @param Font the font
	 */
	void Reconstruct(int Font)
	{
		// Init for later use
		OffsetItem[] fdPrivate = new DictOffsetItem[fonts[Font].FDArrayOffsets.length-1];
		IndexBaseItem[] fdPrivateBase = new IndexBaseItem[fonts[Font].fdprivateOffsets.length]; 
		OffsetItem[] fdSubrs = new DictOffsetItem[fonts[Font].fdprivateOffsets.length];
		// Reconstruct each type
		ReconstructFDArray(Font,fdPrivate);
		ReconstructPrivateDict(Font,fdPrivate,fdPrivateBase,fdSubrs);
		ReconstructPrivateSubrs(Font,fdPrivateBase,fdSubrs);
	}

	/**
	 * Function subsets the FDArray and builds the new one with new offsets
	 * @param Font The font
	 * @param fdPrivate OffsetItem Array (one for each FDArray)
	 */
	void ReconstructFDArray(int Font,OffsetItem[] fdPrivate)
	{
		// Build the header of the index
		BuildIndexHeader(fonts[Font].FDArrayCount,fonts[Font].FDArrayOffsize,1);

		// For each offset create an Offset Item
		OffsetItem[] fdOffsets = new IndexOffsetItem[fonts[Font].FDArrayOffsets.length-1];
		for (int i=0;i<fonts[Font].FDArrayOffsets.length-1;i++)
		{
			fdOffsets[i] = new IndexOffsetItem(fonts[Font].FDArrayOffsize);
			OutputList.addLast(fdOffsets[i]);
		}
		
		// Declare beginning of the object array
		IndexBaseItem fdArrayBase = new IndexBaseItem();
	    OutputList.addLast(fdArrayBase);
	    
		// For each object check if that FD is used.
	    // if is used build a new one by changing the private object
	    // Else do nothing
	    // At the end of each object mark its ending (Even if wasn't written)
		for (int k=0; k<fonts[Font].FDArrayOffsets.length-1; k++) {
			if (FDArrayUsed.containsKey(Integer.valueOf (k)))
			{
				// Goto beginning of objects
	            seek(fonts[Font].FDArrayOffsets[k]);
	            while (getPosition() < fonts[Font].FDArrayOffsets[k+1])
	            {
	            	int p1 = getPosition();
	            	getDictItem();
	            	int p2 = getPosition();
	            	// If the dictItem is the "Private" then compute and copy length, 
	            	// use marker for offset and write operator number
	            	if (key=="Private") {
	            		// Save the original length of the private dict
	            		int NewSize = ((Integer)args[0]).intValue();
	            		// Save the size of the offset to the subrs in that private
	            		int OrgSubrsOffsetSize = CalcSubrOffsetSize(fonts[Font].fdprivateOffsets[k],fonts[Font].fdprivateLengths[k]);
	            		// Increase the private's length accordingly
	            		if (OrgSubrsOffsetSize != 0)
	            			NewSize += 5-OrgSubrsOffsetSize;
	            		// Insert the new size, OffsetItem and operator key number
	            		OutputList.addLast(new DictNumberItem(NewSize));
	            		fdPrivate[k] = new DictOffsetItem();
	            		OutputList.addLast(fdPrivate[k]);
	            	    OutputList.addLast(new UInt8Item((char)18)); // Private
	            	    // Go back to place 
	            	    seek(p2);
	            	}
	            	// Else copy the entire range
	            	else  // other than private
	            		OutputList.addLast(new RangeItem(buf,p1,p2-p1));
	            }
			}
            // Mark the ending of the object (even if wasn't written)
            OutputList.addLast(new IndexMarkerItem(fdOffsets[k],fdArrayBase));
        }
	}
891912
@NonNull
    public static Collection<ITypeface> getRegisteredFonts(@NonNull Context ctx) {
        init(ctx);
        return FONTS.values();
    }
1368938
public static boolean registerFont(@NonNull ITypeface font) {
        validateFont(font);

        FONTS.put(font.getMappingPrefix(), font);
        return true;
    }
1195990
function fontAPI( fonts ) {
    var promises = [];
    fonts.forEach(function (font) {
        var pro = document.fonts.load( '64px "' + font + '"' );
        promises.push( pro );
    });
    return Promise.all( promises );
}
157156
@Override
    public void addEmbeddedStylesFromCell(final StylesContainer stylesContainer) {
        for (final Paragraph par : this.paragraphs)
            par.addEmbeddedStylesFromCell(stylesContainer);
    }
1166173
@Override
    public ForwardTransferMessage createFOT() {
        ForwardTransferMessage msg = new ForwardTransferMessageImpl(_FOT_HOLDER.mandatoryCodes,
                _FOT_HOLDER.mandatoryVariableCodes, _FOT_HOLDER.optionalCodes, _FOT_HOLDER.mandatoryCodeToIndex,
                _FOT_HOLDER.mandatoryVariableCodeToIndex, _FOT_HOLDER.optionalCodeToIndex);

        return msg;
    }
225932
public static Font getFont(Properties attributes) {
        fontImp.defaultEmbedding = defaultEmbedding;
        fontImp.defaultEncoding = defaultEncoding;
        return fontImp.getFont(attributes);
    }
1005864
public static Typeface getFont(Context context, String fontName) {
        synchronized (cache) {
            if (!cache.containsKey(fontName)) {
                try {
                    Typeface t = Typeface.createFromAsset(context.getAssets(), fontName);
                    cache.put(fontName, t);
                } catch (Exception e) {
                    return null;
                }
            }
            return cache.get(fontName);
        }
    }