How to Create Subset Fonts in .NET?

后端 未结 5 630
天命终不由人
天命终不由人 2021-01-05 04:35

I have a Silverlight application that I need to embed some less-than-common fonts in. It\'s simple enough for me to just copy over the TTF/OTF and compile that with my app.

相关标签:
5条回答
  • 2021-01-05 05:10

    The native API CreateFontPackage may be what you're looking for. You can pass a TTF and a list of characters to keep. If you pass TTFCFP_SUBSET for usSubsetFormat, you'll then get back a working TTF with only those characters.

    Here's a thread with what appears to be code of a working example (in C, unfortunately).

    0 讨论(0)
  • 2021-01-05 05:14

    In WPF for fonts there are static and dynamic linking. It all can be defined in Blend. With static linking of fonts only needed characters are compiled and embedded in your assembly. With dynamic linking all font set is embedded. So try to set static linking for selected fonts and try if it works.

    UPD

    Try to add the following code into you .csproj file. Here we including Tahoma fonts. AutoFill property set to true says that we will embed in assembly only used characters of our controls. The set of chars in <Charachters/> tag fill point to include these chars into assembly. All other tags set to false, because we don't need them.

    <ItemGroup>
        <BlendEmbeddedFont Include="Fonts\tahoma.ttf">
          <IsSystemFont>True</IsSystemFont>
          <All>False</All>
          <AutoFill>True</AutoFill>
          <Characters>dasf</Characters>
          <Uppercase>False</Uppercase>
          <Lowercase>False</Lowercase>
          <Numbers>False</Numbers>
          <Punctuation>False</Punctuation>
        </BlendEmbeddedFont>
        <BlendEmbeddedFont Include="Fonts\tahomabd.ttf">
          <IsSystemFont>True</IsSystemFont>
          <All>False</All>
          <AutoFill>True</AutoFill>
          <Characters>dasf</Characters>
          <Uppercase>False</Uppercase>
          <Lowercase>False</Lowercase>
          <Numbers>False</Numbers>
          <Punctuation>False</Punctuation>
        </BlendEmbeddedFont>
      </ItemGroup>
      <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
    
      <Import Project="$(MSBuildExtensionsPath)\Microsoft\Expression\Blend\3.0\WPF\Microsoft.Expression.Blend.WPF.targets" />
    
    0 讨论(0)
  • 2021-01-05 05:30

    I know it's an old question but I found very difficult to use the CreateFontPackage API from C# (as mentioned by @josh3736's answer) so I thought to share my code.

    I'm using the API with the glyphIndices, you can use it directly with the characters by removing the TTFCFP_FLAGS_GLYPHLIST flag.

    This is my code:

    public byte[] CreateSubset(byte[] inputData, IEnumerable<ushort> glyphIndices)
    {
        AllocProc allocProc = Marshal.AllocHGlobal;
        ReallocProc reallocProc = (p, c) =>
            p == IntPtr.Zero
                ? Marshal.AllocHGlobal(c)
                : Marshal.ReAllocHGlobal(p, c);
        FreeProc freeProc = Marshal.FreeHGlobal;
    
        var resultCode = CreateFontPackage(
            inputData, (uint) inputData.Length,
            out var bufferPtr,
            out _,
            out var bytesWritten,
            TTFCFP_FLAGS_SUBSET | TTFCFP_FLAGS_GLYPHLIST,
            0,
            TTFMFP_SUBSET,
            0,
            TTFCFP_MS_PLATFORMID,
            TTFCFP_UNICODE_CHAR_SET,
            glyphIndices,
            (ushort)glyphIndices.Length,
            allocProc, reallocProc, freeProc, (IntPtr)0);
    
        if (resultCode != 0 || bufferPtr == IntPtr.Zero)
        {
            return null;
        }
    
        try
        {
            var buffer = new byte[bytesWritten];
            Marshal.Copy(bufferPtr, buffer, 0, buffer.Length);
            return buffer;
        }
        finally
        {
            freeProc(bufferPtr);
        }
    }
    
    internal const ushort TTFCFP_FLAGS_SUBSET = 0x0001;
    internal const ushort TTFCFP_FLAGS_COMPRESS = 0x0002;
    internal const ushort TTFCFP_FLAGS_TTC = 0x0004;
    internal const ushort TTFCFP_FLAGS_GLYPHLIST = 0x0008;
    
    internal const ushort TTFMFP_SUBSET = 0x0000;
    
    internal const ushort TTFCFP_UNICODE_PLATFORMID = 0x0000;
    internal const ushort TTFCFP_MS_PLATFORMID = 0x0003;
    
    internal const ushort TTFCFP_UNICODE_CHAR_SET = 0x0001;
    
    [UnmanagedFunctionPointer(CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
    private delegate IntPtr AllocProc(Int32 size);
    
    [UnmanagedFunctionPointer(CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
    private delegate IntPtr ReallocProc(IntPtr memBlock, IntPtr size);
    
    [UnmanagedFunctionPointer(CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
    private delegate void FreeProc(IntPtr memBlock);
    
    [DllImport("FontSub.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)]
    private static extern uint CreateFontPackage(
        [In, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)]
        byte[] puchSrcBuffer,
        uint ulSrcBufferSize,
        out IntPtr puchFontPackageBufferPtr,
        out uint pulFontPackageBufferSize,
        out uint pulBytesWritten,
        ushort usFlags,
        ushort usTtcIndex,
        ushort usSubsetFormat,
        ushort usSubsetLanguage,
        ushort usSubsetPlatform,
        ushort usSubsetEncoding,
        [In, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 12)]
        ushort[] pusSubsetKeepList,
        ushort usSubsetKeepListCount,
        AllocProc lpfnAllocate,
        ReallocProc lpfnReAllocate,
        FreeProc lpfnFree,
        IntPtr lpvReserved
    );
    

    I used with code only with TTF files, for TTC (font collections) you have to change a few things but it should work nonetheless.

    0 讨论(0)
  • 2021-01-05 05:30

    FontForge (http://fontforge.sourceforge.net/) is an open source font editor that allows for automated format conversions. It looks like it is Python only but it might be worth checking out.

    0 讨论(0)
  • 2021-01-05 05:33

    Changing the accepted answer to this one as it is pure .NET with no external references. Uses .NET 4.0:

    Imports System.Windows.Media
    Imports System.Text.Encoding
    Imports System.Collections
    
    Public Sub CreateSubSet(sourceText As String, fontURI As Uri)
        Dim gt As FontEmbeddingManager = New FontEmbeddingManager
    
        Dim glyphTypeface As GlyphTypeface = New GlyphTypeface(fontURI)
        Dim Index As Generic.ICollection(Of UShort)
        Index = New Generic.List(Of UShort)
        Dim sourceTextBytes As Byte() = Unicode.GetBytes(sourceText)
        Dim sourceTextChars As Char() = Unicode.GetChars(sourceTextBytes)
        Dim sourceTextCharVal As Integer
        Dim glyphIndex As Integer
        For sourceTextCharPos = 0 To UBound(sourceTextChars)
            sourceTextCharVal = AscW(sourceTextChars(sourceTextCharPos))
            glyphIndex = glyphTypeface.CharacterToGlyphMap(sourceTextCharVal)
            Index.Add(glyphIndex)
        Next
        Dim filebytes() As Byte = glyphTypeface.ComputeSubset(Index)
        Using fileStream As New System.IO.FileStream("C:\Users\Me\new-subset.ttf", System.IO.FileMode.Create)
            fileStream.Write(filebytes, 0, filebytes.Length)
        End Using
    End Sub
    
    0 讨论(0)
提交回复
热议问题