2

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);
        }
    }
}
Connell.O'Donnell
  • 3,603
  • 11
  • 27
  • 61
  • Remove this `System.Runtime.InteropServices.Marshal.FreeCoTaskMem(fontPtr);` and dispose of `fonts` (the PrivateFontCollection object) and `mySignatureFont` in the `Form1.Closed` event. – dr.null Feb 17 '21 at 19:59
  • 1
    It looks like you're using a PrintPreviewControl there. Use its Paint event to draw your string with that Font, not the PrintDocument.PrintPage event. BTW, read the notes here: [How to properly render an embedded Font?](https://stackoverflow.com/a/64512339/7444103) and take the version of code that you prefer from [here](https://stackoverflow.com/a/57231407/7444103), in case you want to load the Font from a File (a byte array in any case). – Jimi Feb 18 '21 at 00:25

0 Answers0