Winform .net PrintDocument DrawString with Embeded Font Not Work

Viewed 56

After many search at Google, I come here to get help: The issue: when I try to draw using printDocument, the code show the default font (Arial). Please help.

enter image description here

namespace EmbededFonts
{
    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 fonts = new PrivateFontCollection();

        Font mySignatureFont;

        public Form1()
        {
            InitializeComponent();

            byte[] fontData = Properties.Resources.SignatureFont;
            IntPtr fontPtr = System.Runtime.InteropServices.Marshal.AllocCoTaskMem(fontData.Length);
            System.Runtime.InteropServices.Marshal.Copy(fontData, 0, fontPtr, fontData.Length);
            uint dummy = 0;
            fonts.AddMemoryFont(fontPtr, Properties.Resources.SignatureFont.Length);
            AddFontMemResourceEx(fontPtr, (uint)Properties.Resources.SignatureFont.Length, IntPtr.Zero, ref dummy);
            System.Runtime.InteropServices.Marshal.FreeCoTaskMem(fontPtr);

            mySignatureFont = new Font(fonts.Families[0], 16.0F);

        } 

        private void Form1_Paint(object sender, PaintEventArgs e)
        {
            e.Graphics.DrawString("My Artistic Signature", mySignatureFont, Brushes.Black, 10, 10);
        }

        private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            e.Graphics.DrawString("My Artistic Signature", mySignatureFont, Brushes.Black, 10, 10);
        }
    }
}
0 Answers
Related