Rajesh Pandey

Rajesh Pandey

  • NA
  • 12
  • 9.6k

Error getting while emdedding the font in the application.

Sep 6 2011 11:35 PM
Hello Sir,
I want to make the application in which i want to embedded the font. I have add the font in the resource of my application and uses the following code.
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.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Drawing.Text;

namespace embedded_font
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            LoadFont();
            label1.Font = new Font(private_fonts.Families[0], 22);
            label1.UseCompatibleTextRendering = true;
        }
       
        PrivateFontCollection private_fonts = new PrivateFontCollection();
        private void LoadFont()
        {
            // specify embedded resource name
            string resource = "embedded_font.akruie__.TTF";
            // receive resource stream
            Stream fontStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resource);
            // create an unsafe memory block for the font data
            System.IntPtr data = Marshal.AllocCoTaskMem((int)fontStream.Length);
            // create a buffer to read in to
            byte[] fontdata = new byte[fontStream.Length];
            // read the font data from the resource
            fontStream.Read(fontdata, 0, (int)fontStream.Length);
            // copy the bytes to the unsafe memory block
            Marshal.Copy(fontdata, 0, data, (int)fontStream.Length);
            // pass the font to the font collection
            private_fonts.AddMemoryFont(data, (int)fontStream.Length);
            // close the resource stream
            fontStream.Close();
            // free the unsafe memory
            Marshal.FreeCoTaskMem(data);
        }
    }
}

But While compiling the code i am getting the following error.
Error:Object reference not set to an instance of an object.
Plzzzzz help me what is wrong with this code as soon as possible plzzzzzzzzz.