Reputation: 65
Im trying to get the privatefontcollection to work. But so far its not working, not in the sense of an error, just the font seen on screen is MS Sans Serif and not the Font im trying to load. so far i have tried two diffrent methods and neither seem to have worked for me.
First i tried:
Public Function GetFontInstance(ByVal data() As Byte, ByVal Size As Single, ByVal Style As FontStyle) As Font
Dim result As Font
Try
Dim pfc = New PrivateFontCollection
'LOAD MEMORY POINTER FOR FONT RESOURCE
Dim FontPtr As System.IntPtr = Marshal.AllocCoTaskMem(data.Length)
'COPY THE DATA TO THE MEMORY LOCATION
Marshal.Copy(data, 0, FontPtr, data.Length)
'LOAD THE MEMORY FONT INTO THE PRIVATE FONT COLLECTION
pfc.AddMemoryFont(FontPtr, data.Length)
'FREE UNSAFE MEMORY
'Marshal.FreeCoTaskMem(FontPtr)
result = New Font(pfc.Families(0), Size, Style)
pfc.Families(0).Dispose()
pfc.Dispose()
Catch ex As Exception
'ERROR LOADING FONT. HANDLE EXCEPTION HERE
MsgBox("Error in [GetFontInstance()]" & vbCrLf & ex.Message)
result = New Font(FontFamily.GenericMonospace, 8)
End Try
Return result
End Function
i called this function from the Print SubRoutine:
Dim newFont As Font = GetFontInstance(My.Resources.OpenSans_Bold, 22, FontStyle.Bold)
e.Graphics.DrawString("Hello World", newFont, Brushes.Black, 50, 2)
but what i see in the printdocument print preview, is just MS Sans Serif type font. not the font i have loaded into my Resources.
I then tried this method:
Dim sAppPath As String
sAppPath = System.Windows.Forms.Application.StartupPath
Dim fcollect As New PrivateFontCollection()
fcollect.AddFontFile(sAppPath & "\OpenSans-Bold.ttf")
Dim OpenSansFont As New Font(fcollect.Families(0), 50, FontStyle.Bold)
e.Graphics.DrawString("Hello World", OpenSansFont, Brushes.Black, 50, 2)
again i got the same result
is there something I'm missing to get this to work. other questions asked about this seem to indicate this should just work.
I should mention that the end user will run the Application on a system admin locked PC, so the option to "install" the font wont be possible. Id need to make use of the font only while the application is running / when the subroutine gets called.
Upvotes: 1
Views: 418