Friday, June 26, 2009

How to embed a True Type font in using C#

 
It is easy to use any true type font in your application without installing.

Example: using C#


1) Create new project (myFont).
2) Create label(lblUsemyFontName).
3) Add your font file (myFontName.ttf) to Resources


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Text;

namespace myFont
{
public partial class Form1 : Form
{
[System.Runtime.InteropServices.DllImport("gdi32.dll")]

private static extern IntPtr AddFontMemResourceEx(IntPtr pbFont,uint cbFont,
IntPtr pdv, [System.Runtime.InteropServices.In] ref uint pcFonts);

private PrivateFontCollection MYpfc = new PrivateFontCollection();

public Form1()
{
InitializeComponent();
try
{
unsafe
{
fixed (byte* pFontData = Properties.Resources.myFontName)
{
uint dummy = 0;
MYpfc.AddMemoryFont((IntPtr)pFontData, Properties.Resources.myFontName.Length);
AddFontMemResourceEx((IntPtr)pFontData, (uint)Properties.Resources.myFontName.Length, IntPtr.Zero, ref dummy);
}
}
}
catch
{
MessageBox.Show("Font does not correctly appear");

}
}

private void Form1_Load(object sender, EventArgs e)
{
lblUsemyFontName.Font = new Font(MYpfc.Families[0], 36); //Font size is 36
//lblUsemyFontName1.Font = new Font(MYpfc.Families[0], 22);//Font size is 22
// lblUsemyFontName2.Font = new Font(MYpfc.Families[0], 16);//Font size is 16
}
}
}


Now Your labels text displayed your font....

5 comments:

pathurun said...

Hi
I am getting this error WindosApp1.Properties.Resources does not contain a defintion for myfontname. I have added a ttf file and changed in the properties to embedded resource. Please let me know if we need to make any additional changes.
Thanks
N

Sarath Ambegoda said...

Hi Pathurun,
In this program i am used myfontname.ttf,
Please change myfontname to your ttf font name.
Thanks

Sarath Ambegoda said...
This comment has been removed by the author.
Matt Whitby said...

Would something like this work in a webpage?

Ernest Poletaev said...

Matt, have look my article that have a code sample to solve this problem