org.apache.fontbox.ttf.TrueTypeFont Java Examples

The following examples show how to use org.apache.fontbox.ttf.TrueTypeFont. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PDTrueTypeFontEmbedder.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Creates a new TrueType font embedder for the given TTF as a PDTrueTypeFont.
 *
 * @param document The parent document
 * @param dict Font dictionary
 * @param ttfStream TTF stream
 * @param encoding The PostScript encoding vector to be used for embedding.
 * @throws IOException if the TTF could not be read
 */
PDTrueTypeFontEmbedder(PDDocument document, COSDictionary dict, TrueTypeFont ttf,
                       Encoding encoding) throws IOException
{
    super(document, dict, ttf, false);
    dict.setItem(COSName.SUBTYPE, COSName.TRUE_TYPE);
    
    GlyphList glyphList = GlyphList.getAdobeGlyphList();
    this.fontEncoding = encoding;
    dict.setItem(COSName.ENCODING, encoding.getCOSObject());
    fontDescriptor.setSymbolic(false);
    fontDescriptor.setNonSymbolic(true);
    
    // add the font descriptor
    dict.setItem(COSName.FONT_DESC, fontDescriptor);

    // set the glyph widths
    setWidths(dict, glyphList);
}
 
Example #2
Source File: FontUtils.java    From sambox with Apache License 2.0 6 votes vote down vote up
/**
 * @return true if the fsType in the OS/2 table permits embedding.
 */
public static boolean isEmbeddingPermitted(TrueTypeFont ttf) throws IOException
{
    if (ttf.getOS2Windows() != null)
    {
        int fsType = ttf.getOS2Windows().getFsType();
        int exclusive = fsType & 0x8; // bits 0-3 are a set of exclusive bits

        if ((exclusive
                & OS2WindowsMetricsTable.FSTYPE_RESTRICTED) == OS2WindowsMetricsTable.FSTYPE_RESTRICTED)
        {
            // restricted License embedding
            return false;
        }
        else if ((exclusive
                & OS2WindowsMetricsTable.FSTYPE_BITMAP_ONLY) == OS2WindowsMetricsTable.FSTYPE_BITMAP_ONLY)
        {
            // bitmap embedding only
            return false;
        }
    }
    return true;
}
 
Example #3
Source File: TrueTypeEmbedder.java    From sambox with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new TrueType font for embedding.
 */
TrueTypeEmbedder(COSDictionary dict, TrueTypeFont ttf, boolean embedSubset) throws IOException
{
    this.embedSubset = embedSubset;
    this.ttf = ttf;
    fontDescriptor = createFontDescriptor(ttf);

    if (!isEmbeddingPermitted(ttf))
    {
        throw new IOException("This font does not permit embedding");
    }

    if (!embedSubset)
    {
        // full embedding
        PDStream stream = new PDStream(ttf.getOriginalData(), COSName.FLATE_DECODE);
        stream.getCOSObject().setLong(COSName.LENGTH1, ttf.getOriginalDataSize());
        fontDescriptor.setFontFile2(stream);
    }

    dict.setName(COSName.BASE_FONT, ttf.getName());

    // choose a Unicode "cmap"
    cmap = ttf.getUnicodeCmap();
    cmapLookup = ttf.getUnicodeCmapLookup();
}
 
Example #4
Source File: PDTrueTypeFont.java    From sambox with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new TrueType font for embedding.
 */
private PDTrueTypeFont(TrueTypeFont ttf, Encoding encoding, boolean closeTTF) throws IOException
{
    PDTrueTypeFontEmbedder embedder = new PDTrueTypeFontEmbedder(dict, ttf, encoding);
    this.encoding = encoding;
    this.ttf = ttf;
    setFontDescriptor(embedder.getFontDescriptor());
    isEmbedded = true;
    isDamaged = false;
    glyphList = GlyphList.getAdobeGlyphList();
    if (closeTTF)
    {
        // the TTF is fully loaded and it is save to close the underlying data source
        ttf.close();
    }
}
 
Example #5
Source File: FontMapperImpl.java    From sambox with Apache License 2.0 6 votes vote down vote up
/**
 * Finds a font with the given PostScript name, or a suitable substitute, or null.
 *
 * @param postScriptName PostScript font name
 */
private FontBoxFont findFontBoxFont(String postScriptName)
{
    Type1Font t1 = (Type1Font) findFont(FontFormat.PFB, postScriptName);
    if (t1 != null)
    {
        return t1;
    }

    TrueTypeFont ttf = (TrueTypeFont) findFont(FontFormat.TTF, postScriptName);
    if (ttf != null)
    {
        return ttf;
    }

    OpenTypeFont otf = (OpenTypeFont) findFont(FontFormat.OTF, postScriptName);
    if (otf != null)
    {
        return otf;
    }

    return null;
}
 
Example #6
Source File: PDTrueTypeFontEmbedder.java    From sambox with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new TrueType font embedder for the given TTF as a PDTrueTypeFont.
 *
 * @param dict Font dictionary
 * @param ttf TTF font
 * @param encoding The PostScript encoding vector to be used for embedding.
 * @throws IOException if the TTF could not be read
 */
PDTrueTypeFontEmbedder(COSDictionary dict, TrueTypeFont ttf,
                       Encoding encoding) throws IOException
{
    super(dict, ttf, false);
    dict.setItem(COSName.SUBTYPE, COSName.TRUE_TYPE);
    
    GlyphList glyphList = GlyphList.getAdobeGlyphList();
    this.fontEncoding = encoding;
    dict.setItem(COSName.ENCODING, encoding.getCOSObject());
    fontDescriptor.setSymbolic(false);
    fontDescriptor.setNonSymbolic(true);
    
    // add the font descriptor
    dict.setItem(COSName.FONT_DESC, fontDescriptor);

    // set the glyph widths
    setWidths(dict, glyphList);
}
 
Example #7
Source File: FileSystemFontProvider.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
private TrueTypeFont readTrueTypeFont(String postScriptName, File file) throws IOException
{
    if (file.getName().toLowerCase().endsWith(".ttc"))
    {
        @SuppressWarnings("squid:S2095")
        // ttc not closed here because it is needed later when ttf is accessed,
        // e.g. rendering PDF with non-embedded font which is in ttc file in our font directory
        TrueTypeCollection ttc = new TrueTypeCollection(file);
        TrueTypeFont ttf = ttc.getFontByName(postScriptName);
        if (ttf == null)
        {
            ttc.close();
            throw new IOException("Font " + postScriptName + " not found in " + file);
        }
        return ttf;
    }
    else
    {
        TTFParser ttfParser = new TTFParser(false, true);
        return ttfParser.parse(file);
    }
}
 
Example #8
Source File: PDType0Font.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Private. Creates a new PDType0Font font for embedding.
 *
 * @param document
 * @param ttf
 * @param embedSubset
 * @param closeTTF whether to close the ttf parameter after embedding. Must be true when the ttf
 * parameter was created in the load() method, false when the ttf parameter was passed to the
 * load() method.
 * @param vertical
 * @throws IOException
 */
private PDType0Font(PDDocument document, TrueTypeFont ttf, boolean embedSubset,
        boolean closeTTF, boolean vertical) throws IOException
{
    if (vertical)
    {
        ttf.enableVerticalSubstitutions();
    }
    embedder = new PDCIDFontType2Embedder(document, dict, ttf, embedSubset, this, vertical);
    descendantFont = embedder.getCIDFont();
    readEncoding();
    fetchCMapUCS2();
    if (closeTTF)
    {
        if (embedSubset)
        {
            this.ttf = ttf;
            document.registerTrueTypeFontForClosing(ttf);
        }
        else
        {
            // the TTF is fully loaded and it is safe to close the underlying data source
            ttf.close();
        }
    }
}
 
Example #9
Source File: PDType0Font.java    From sambox with Apache License 2.0 6 votes vote down vote up
/**
 *
 * @param document
 * @param ttf
 * @param embedSubset
 * @param closeTTF whether to close the ttf parameter after embedding. Must be true when the ttf parameter was
 * created in the load() method, false when the ttf parameter was passed to the load() method.
 * @param vertical
 * @throws IOException
 */
private PDType0Font(PDDocument document, TrueTypeFont ttf, boolean embedSubset,
        boolean closeTTF, boolean vertical) throws IOException
{
    if (vertical)
    {
        ttf.enableVerticalSubstitutions();
    }
    embedder = new PDCIDFontType2Embedder(document, dict, ttf, embedSubset, this, vertical);
    descendantFont = embedder.getCIDFont();
    readEncoding();
    fetchCMapUCS2();
    if (closeTTF)
    {
        if (embedSubset)
        {
            this.ttf = ttf;
            document.registerTrueTypeFontForClosing(ttf);
        }
        else
        {
            // the TTF is fully loaded and it is safe to close the underlying data source
            ttf.close();
        }
    }
}
 
Example #10
Source File: FileSystemFontProvider.java    From sambox with Apache License 2.0 6 votes vote down vote up
private TrueTypeFont readTrueTypeFont(String postScriptName, File file) throws IOException
{
    if (file.getName().toLowerCase().endsWith(".ttc"))
    {
        @SuppressWarnings("squid:S2095")
        // ttc not closed here because it is needed later when ttf is accessed,
        // e.g. rendering PDF with non-embedded font which is in ttc file in our font directory
        TrueTypeCollection ttc = new TrueTypeCollection(file);
        TrueTypeFont ttf = ttc.getFontByName(postScriptName);
        if (ttf == null)
        {
            ttc.close();
            throw new IOException("Font " + postScriptName + " not found in " + file);
        }
        return ttf;
    }
    TTFParser ttfParser = new TTFParser(false, true);
    return ttfParser.parse(file);
}
 
Example #11
Source File: TrueTypeEmbedder.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Returns true if the fsType in the OS/2 table permits embedding.
 */
private boolean isEmbeddingPermitted(TrueTypeFont ttf) throws IOException
{
    if (ttf.getOS2Windows() != null)
    {
        int fsType = ttf.getOS2Windows().getFsType();
        int exclusive = fsType & 0x8; // bits 0-3 are a set of exclusive bits

        if ((exclusive & OS2WindowsMetricsTable.FSTYPE_RESTRICTED) ==
                         OS2WindowsMetricsTable.FSTYPE_RESTRICTED)
        {
            // restricted License embedding
            return false;
        }
        else if ((exclusive & OS2WindowsMetricsTable.FSTYPE_BITMAP_ONLY) ==
                             OS2WindowsMetricsTable.FSTYPE_BITMAP_ONLY)
        {
            // bitmap embedding only
            return false;
        }
    }
    return true;
}
 
Example #12
Source File: FontMapperImpl.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Finds a font with the given PostScript name, or a suitable substitute, or null.
 *
 * @param postScriptName PostScript font name
 */
private FontBoxFont findFontBoxFont(String postScriptName)
{
    Type1Font t1 = (Type1Font)findFont(FontFormat.PFB, postScriptName);
    if (t1 != null)
    {
        return t1;
    }

    TrueTypeFont ttf = (TrueTypeFont)findFont(FontFormat.TTF, postScriptName);
    if (ttf != null)
    {
        return ttf;
    }

    OpenTypeFont otf = (OpenTypeFont) findFont(FontFormat.OTF, postScriptName);
    if (otf != null)
    {
        return otf;
    }

    return null;
}
 
Example #13
Source File: FontUtils.java    From sejda with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Tries to load the original full font from the system
 */
public PDFont loadOriginal(PDDocument document) {
    String lookupName = fontName.replace("-", " ");

    LOG.debug("Searching the system for a font matching name '{}'", lookupName);

    FontMapping<TrueTypeFont> fontMapping = FontMappers.instance().getTrueTypeFont(lookupName, null);
    if (fontMapping != null && fontMapping.getFont() != null && !fontMapping.isFallback()) {
        TrueTypeFont mappedFont = fontMapping.getFont();

        try {
            LOG.debug("Original font available on the system: {}", fontName);
            return PDType0Font.load(document, mappedFont.getOriginalData());
        } catch (IOException ioe) {
            LOG.warn("Failed to load font from system", ioe);
            try {
                mappedFont.close();
            } catch (IOException e) {
                LOG.warn("Failed closing font", e);
            }
        }
    }

    return null;
}
 
Example #14
Source File: PDFontTest.java    From sambox with Apache License 2.0 6 votes vote down vote up
/**
 * PDFBOX-3826: Test ability to reuse a TrueTypeFont created from a file or a stream for several PDFs to avoid
 * parsing it over and over again. Also check that full or partial embedding is done, and do render and text
 * extraction.
 *
 * @throws IOException
 * @throws URISyntaxException
 */
@Test
public void testPDFBox3826() throws IOException, URISyntaxException
{
    URL url = PDFont.class
            .getResource("/org/sejda/sambox/resources/ttf/LiberationSans-Regular.ttf");
    File fontFile = new File(url.toURI());

    TrueTypeFont ttf1 = new TTFParser().parse(fontFile);
    testPDFBox3826checkFonts(testPDFBox3826createDoc(ttf1), fontFile);
    ttf1.close();

    TrueTypeFont ttf2 = new TTFParser().parse(new FileInputStream(fontFile));
    testPDFBox3826checkFonts(testPDFBox3826createDoc(ttf2), fontFile);
    ttf2.close();
}
 
Example #15
Source File: PDTrueTypeFont.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Creates a new TrueType font for embedding.
 */
private PDTrueTypeFont(PDDocument document, TrueTypeFont ttf, Encoding encoding,
        boolean closeTTF)
        throws IOException
{
    PDTrueTypeFontEmbedder embedder = new PDTrueTypeFontEmbedder(document, dict, ttf,
                                                                 encoding);
    this.encoding = encoding;
    this.ttf = ttf;
    setFontDescriptor(embedder.getFontDescriptor());
    isEmbedded = true;
    isDamaged = false;
    glyphList = GlyphList.getAdobeGlyphList();
    if (closeTTF)
    {
        // the TTF is fully loaded and it is safe to close the underlying data source
        ttf.close();
    }
}
 
Example #16
Source File: TrueTypeEmbedder.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Returns true if the fsType in the OS/2 table permits subsetting.
 */
private boolean isSubsettingPermitted(TrueTypeFont ttf) throws IOException
{
    if (ttf.getOS2Windows() != null)
    {
        int fsType = ttf.getOS2Windows().getFsType();
        if ((fsType & OS2WindowsMetricsTable.FSTYPE_NO_SUBSETTING) ==
                      OS2WindowsMetricsTable.FSTYPE_NO_SUBSETTING)
        {
            return false;
        }
    }
    return true;
}
 
Example #17
Source File: TTFGlyph2D.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
private TTFGlyph2D(TrueTypeFont ttf, PDFont font, boolean isCIDFont) throws IOException
{
    this.font = font;
    this.ttf = ttf;
    this.isCIDFont = isCIDFont;
    // get units per em, which is used as scaling factor
    HeaderTable header = this.ttf.getHeader();
    if (header != null && header.getUnitsPerEm() != 1000)
    {
        // in most case the scaling factor is set to 1.0f
        // due to the fact that units per em is set to 1000
        scale = 1000f / header.getUnitsPerEm();
        hasScaling = true;
    }
}
 
Example #18
Source File: FontUtils.java    From sambox with Apache License 2.0 5 votes vote down vote up
/**
 * @return true if the fsType in the OS/2 table permits subsetting.
 */
public static boolean isSubsettingPermitted(TrueTypeFont ttf) throws IOException
{
    if (ttf.getOS2Windows() != null)
    {
        int fsType = ttf.getOS2Windows().getFsType();
        if ((fsType
                & OS2WindowsMetricsTable.FSTYPE_NO_SUBSETTING) == OS2WindowsMetricsTable.FSTYPE_NO_SUBSETTING)
        {
            return false;
        }
    }
    return true;
}
 
Example #19
Source File: FontUtils.java    From sejda with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Tries to load a similar full font from the system
 */
public PDFont loadSimilar(PDDocument document) {
    String lookupName = fontName.replace("-", " ");

    // Eg: Arial-BoldMT
    PDFontDescriptor descriptor = new PDFontDescriptor(new COSDictionary());
    descriptor.setFontName(fontName.split("-")[0]);
    descriptor.setForceBold(FontUtils.isBold(subsetFont));
    descriptor.setItalic(FontUtils.isItalic(subsetFont));

    LOG.debug(
            "Searching the system for a font matching name '{}' and description [name:{}, bold:{}, italic:{}]",
            lookupName, descriptor.getFontName(), descriptor.isForceBold(), descriptor.isItalic());

    FontMapping<TrueTypeFont> fontMapping = FontMappers.instance().getTrueTypeFont(lookupName, descriptor);
    if (fontMapping != null && fontMapping.getFont() != null) {
        TrueTypeFont mappedFont = fontMapping.getFont();

        try {
            if (fontMapping.isFallback()) {
                LOG.debug("Fallback font available on the system: {} (for {})", mappedFont.getName(), fontName);
            } else {
                LOG.debug("Original font available on the system: {}", fontName);
            }

            return PDType0Font.load(document, mappedFont.getOriginalData());
        } catch (IOException ioe) {
            LOG.warn("Failed to load font from system", ioe);
            try {
                mappedFont.close();
            } catch (Exception e) {
                LOG.warn("Failed closing font", e);
            }
        }
    }

    return null;
}
 
Example #20
Source File: PDCIDFontType2Embedder.java    From sambox with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new TrueType font embedder for the given TTF as a PDCIDFontType2.
 *
 * @param document parent document
 * @param dict font dictionary
 * @param ttf True Type Font
 * @param parent parent Type 0 font
 * @throws IOException if the TTF could not be read
 */
PDCIDFontType2Embedder(PDDocument document, COSDictionary dict, TrueTypeFont ttf,
        boolean embedSubset, PDType0Font parent, boolean vertical) throws IOException
{
    super(dict, ttf, embedSubset);
    this.document = document;
    this.dict = dict;
    this.parent = parent;
    this.vertical = vertical;

    // parent Type 0 font
    dict.setItem(COSName.SUBTYPE, COSName.TYPE0);
    dict.setName(COSName.BASE_FONT, fontDescriptor.getFontName());
    dict.setItem(COSName.ENCODING, vertical ? COSName.IDENTITY_V : COSName.IDENTITY_H); // CID = GID

    // descendant CIDFont
    cidFont = createCIDFont();
    COSArray descendantFonts = new COSArray();
    descendantFonts.add(cidFont);
    dict.setItem(COSName.DESCENDANT_FONTS, descendantFonts);

    if (!embedSubset)
    {
        // build GID -> Unicode map
        buildToUnicodeCMap(null);
    }

    // ToUnicode CMap
    buildToUnicodeCMap(null);
}
 
Example #21
Source File: TTFGlyph2D.java    From sambox with Apache License 2.0 5 votes vote down vote up
private TTFGlyph2D(TrueTypeFont ttf, PDFont font, boolean isCIDFont) throws IOException
{
    this.font = font;
    this.ttf = ttf;
    this.isCIDFont = isCIDFont;
    // get units per em, which is used as scaling factor
    HeaderTable header = this.ttf.getHeader();
    if (header != null && header.getUnitsPerEm() != 1000)
    {
        // in most case the scaling factor is set to 1.0f
        // due to the fact that units per em is set to 1000
        scale = 1000f / header.getUnitsPerEm();
        hasScaling = true;
    }
}
 
Example #22
Source File: FileSystemFontProvider.java    From sambox with Apache License 2.0 5 votes vote down vote up
private TrueTypeFont getTrueTypeFont(String postScriptName, File file)
{
    try
    {
        TrueTypeFont ttf = readTrueTypeFont(postScriptName, file);
        LOG.debug("Loaded {} from {}", postScriptName, file);
        return ttf;
    }
    catch (NullPointerException | IOException e) // TTF parser is buggy
    {
        LOG.error("Could not load font file: " + file, e);
    }
    return null;
}
 
Example #23
Source File: PDCIDFontType2Embedder.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Creates a new TrueType font embedder for the given TTF as a PDCIDFontType2.
 *
 * @param document parent document
 * @param dict font dictionary
 * @param ttf True Type Font
 * @param parent parent Type 0 font
 * @throws IOException if the TTF could not be read
 */
PDCIDFontType2Embedder(PDDocument document, COSDictionary dict, TrueTypeFont ttf,
        boolean embedSubset, PDType0Font parent, boolean vertical) throws IOException
{
    super(document, dict, ttf, embedSubset);
    this.document = document;
    this.dict = dict;
    this.parent = parent;
    this.vertical = vertical;

    // parent Type 0 font
    dict.setItem(COSName.SUBTYPE, COSName.TYPE0);
    dict.setName(COSName.BASE_FONT, fontDescriptor.getFontName());
    dict.setItem(COSName.ENCODING, vertical ? COSName.IDENTITY_V : COSName.IDENTITY_H); // CID = GID

    // descendant CIDFont
    cidFont = createCIDFont();
    COSArray descendantFonts = new COSArray();
    descendantFonts.add(cidFont);
    dict.setItem(COSName.DESCENDANT_FONTS, descendantFonts);

    if (!embedSubset)
    {
        // build GID -> Unicode map
        buildToUnicodeCMap(null);
    }
}
 
Example #24
Source File: TrueTypeEmbedder.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Creates a new TrueType font for embedding.
 */
@SuppressWarnings("deprecation")
TrueTypeEmbedder(PDDocument document, COSDictionary dict, TrueTypeFont ttf,
                 boolean embedSubset) throws IOException
{
    this.document = document;
    this.embedSubset = embedSubset;
    this.ttf = ttf;
    fontDescriptor = createFontDescriptor(ttf);

    if (!isEmbeddingPermitted(ttf))
    {
        throw new IOException("This font does not permit embedding");
    }

    if (!embedSubset)
    {
        // full embedding
        PDStream stream = new PDStream(document, ttf.getOriginalData(), COSName.FLATE_DECODE);
        stream.getCOSObject().setLong(COSName.LENGTH1, ttf.getOriginalDataSize());
        fontDescriptor.setFontFile2(stream);
    }

    dict.setName(COSName.BASE_FONT, ttf.getName());

    // choose a Unicode "cmap"
    cmap = ttf.getUnicodeCmap();
    cmapLookup = ttf.getUnicodeCmapLookup();
}
 
Example #25
Source File: FileSystemFontProvider.java    From sambox with Apache License 2.0 5 votes vote down vote up
/**
 * Adds a TTC or OTC to the file cache. To reduce memory, the parsed font is not cached.
 * 
 * @throws IOException
 */
private void addTrueTypeCollection(final File ttcFile) throws IOException
{
    try (TrueTypeCollection ttc = new TrueTypeCollection(ttcFile))
    {
        ttc.processAllFonts(new TrueTypeFontProcessor()
        {
            @Override
            public void process(TrueTypeFont ttf) throws IOException
            {
                addTrueTypeFontImpl(ttf, ttcFile);
            }
        });
    }
}
 
Example #26
Source File: PDFontTest.java    From sambox with Apache License 2.0 4 votes vote down vote up
private byte[] testPDFBox3826createDoc(TrueTypeFont ttf) throws IOException
{
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try (PDDocument doc = new PDDocument())
    {

        PDPage page = new PDPage();
        doc.addPage(page);

        // type 0 subset embedding
        PDFont font = PDType0Font.load(doc, ttf, true);
        PDPageContentStream cs = new PDPageContentStream(doc, page);

        cs.beginText();
        cs.newLineAtOffset(10, 700);
        cs.setFont(font, 10);
        cs.showText("testMultipleFontFileReuse1");
        cs.endText();

        // type 0 full embedding
        font = PDType0Font.load(doc, ttf, false);

        cs.beginText();
        cs.newLineAtOffset(10, 650);
        cs.setFont(font, 10);
        cs.showText("testMultipleFontFileReuse2");
        cs.endText();

        // tt full embedding but only WinAnsiEncoding
        font = PDTrueTypeFont.load(doc, ttf, WinAnsiEncoding.INSTANCE);

        cs.beginText();
        cs.newLineAtOffset(10, 600);
        cs.setFont(font, 10);
        cs.showText("testMultipleFontFileReuse3");
        cs.endText();

        cs.close();

        doc.writeTo(baos);
    }
    return baos.toByteArray();
}
 
Example #27
Source File: TestTTFParser.java    From sambox with Apache License 2.0 4 votes vote down vote up
/**
 * Test the post table parser.
 * 
 * @throws IOException if an error occurs.
 */
@Test
public void testPostTable() throws IOException
{
    InputStream input = PDFont.class
            .getResourceAsStream("/org/sejda/sambox/resources/ttf/LiberationSans-Regular.ttf");
    Assert.assertNotNull(input);

    TTFParser parser = new TTFParser();
    TrueTypeFont font = parser.parse(input);

    CmapTable cmapTable = font.getCmap();
    Assert.assertNotNull(cmapTable);

    CmapSubtable[] cmaps = cmapTable.getCmaps();
    Assert.assertNotNull(cmaps);

    CmapSubtable cmap = null;

    for (CmapSubtable e : cmaps)
    {
        if (e.getPlatformId() == NameRecord.PLATFORM_WINDOWS
                && e.getPlatformEncodingId() == NameRecord.ENCODING_WINDOWS_UNICODE_BMP)
        {
            cmap = e;
            break;
        }
    }

    Assert.assertNotNull(cmap);

    PostScriptTable post = font.getPostScript();
    Assert.assertNotNull(post);

    String[] glyphNames = font.getPostScript().getGlyphNames();
    Assert.assertNotNull(glyphNames);

    // test a WGL4 (Macintosh standard) name
    int gid = cmap.getGlyphId(0x2122); // TRADE MARK SIGN
    Assert.assertEquals("trademark", glyphNames[gid]);

    // test an additional name
    gid = cmap.getGlyphId(0x20AC); // EURO SIGN
    Assert.assertEquals("Euro", glyphNames[gid]);
}
 
Example #28
Source File: TrueTypeEmbedder.java    From sambox with Apache License 2.0 4 votes vote down vote up
/**
 * Returns the FontBox font.
 */
@Deprecated
public TrueTypeFont getTrueTypeFont()
{
    return ttf;
}
 
Example #29
Source File: TrueTypeEmbedder.java    From sambox with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a new font descriptor dictionary for the given TTF.
 */
private PDFontDescriptor createFontDescriptor(TrueTypeFont ttf) throws IOException
{
    PDFontDescriptor fd = new PDFontDescriptor();
    fd.setFontName(ttf.getName());

    OS2WindowsMetricsTable os2 = ttf.getOS2Windows();
    PostScriptTable post = ttf.getPostScript();

    // Flags
    fd.setFixedPitch(
            post.getIsFixedPitch() > 0 || ttf.getHorizontalHeader().getNumberOfHMetrics() == 1);

    int fsSelection = os2.getFsSelection();
    fd.setItalic(((fsSelection & (ITALIC | OBLIQUE)) != 0));

    switch (os2.getFamilyClass())
    {
    case OS2WindowsMetricsTable.FAMILY_CLASS_CLAREDON_SERIFS:
    case OS2WindowsMetricsTable.FAMILY_CLASS_FREEFORM_SERIFS:
    case OS2WindowsMetricsTable.FAMILY_CLASS_MODERN_SERIFS:
    case OS2WindowsMetricsTable.FAMILY_CLASS_OLDSTYLE_SERIFS:
    case OS2WindowsMetricsTable.FAMILY_CLASS_SLAB_SERIFS:
        fd.setSerif(true);
        break;
    case OS2WindowsMetricsTable.FAMILY_CLASS_SCRIPTS:
        fd.setScript(true);
        break;
    default:
        break;
    }

    fd.setFontWeight(os2.getWeightClass());

    fd.setSymbolic(true);
    fd.setNonSymbolic(false);

    // ItalicAngle
    fd.setItalicAngle(post.getItalicAngle());

    // FontBBox
    HeaderTable header = ttf.getHeader();
    PDRectangle rect = new PDRectangle();
    float scaling = 1000f / header.getUnitsPerEm();
    rect.setLowerLeftX(header.getXMin() * scaling);
    rect.setLowerLeftY(header.getYMin() * scaling);
    rect.setUpperRightX(header.getXMax() * scaling);
    rect.setUpperRightY(header.getYMax() * scaling);
    fd.setFontBoundingBox(rect);

    // Ascent, Descent
    HorizontalHeaderTable hHeader = ttf.getHorizontalHeader();
    fd.setAscent(hHeader.getAscender() * scaling);
    fd.setDescent(hHeader.getDescender() * scaling);

    // CapHeight, XHeight
    if (os2.getVersion() >= 1.2)
    {
        fd.setCapHeight(os2.getCapHeight() * scaling);
        fd.setXHeight(os2.getHeight() * scaling);
    }
    else
    {
        GeneralPath capHPath = ttf.getPath("H");
        if (capHPath != null)
        {
            fd.setCapHeight(Math.round(capHPath.getBounds2D().getMaxY()) * scaling);
        }
        else
        {
            // estimate by summing the typographical +ve ascender and -ve descender
            fd.setCapHeight((os2.getTypoAscender() + os2.getTypoDescender()) * scaling);
        }
        GeneralPath xPath = ttf.getPath("x");
        if (xPath != null)
        {
            fd.setXHeight(Math.round(xPath.getBounds2D().getMaxY()) * scaling);
        }
        else
        {
            // estimate by halving the typographical ascender
            fd.setXHeight(os2.getTypoAscender() / 2.0f * scaling);
        }
    }

    // StemV - there's no true TTF equivalent of this, so we estimate it
    fd.setStemV(fd.getFontBoundingBox().getWidth() * .13f);

    return fd;
}
 
Example #30
Source File: FontUtilsTest.java    From sejda with GNU Affero General Public License v3.0 4 votes vote down vote up
private boolean isFontAvailableOnSystem(String name) {
    FontMapping<TrueTypeFont> result = FontMappers.instance().getTrueTypeFont(name, null);
    return result != null && !result.isFallback();
}