Reputation: 25058
I have a code that writes a triangle char inside a table using itextsharp in visual studio (it could be vb or c#).
To do so I am using threbuchet font which contains it. It works fine, but I would like to colour the triangle to red. When trying to do so using iTextSharp.text.FontFactory.GetFont
(which I think is good to get color), no symbol at all is written to pdf.
Is there other way to colour a font inside New iTextSharp.text.Font(bf, 8)
?
this is the code
' table
Dim nTbl As PdfPTable = New PdfPTable(2)
nTbl.HorizontalAlignment = PdfContentByte.ALIGN_CENTER
nTbl.SetTotalWidth({40, 60})
' this works and adds the triangle char
Dim FONT As String = "fonts\trebucbd.ttf"
Dim bf As BaseFont = BaseFont.CreateFont(FONT, BaseFont.IDENTITY_H, BaseFont.EMBEDDED)
Cell = New PdfPCell(New Phrase("Δ", New iTextSharp.text.Font(bf, 8)))
Cell.HorizontalAlignment = 1
Cell.VerticalAlignment = 1
nTbl.AddCell(Cell)
' this does not work, when trying to colour triangle
Cell = New PdfPCell(New Phrase("Δ", iTextSharp.text.FontFactory.GetFont("fonts\trebucbd.ttf", 8, iTextSharp.text.Font.NORMAL, New iTextSharp.text.Color(128, 0, 0))))
Cell.HorizontalAlignment = 1
Cell.VerticalAlignment = 1
nTbl.AddCell(Cell)
Upvotes: 0
Views: 3958
Reputation: 55457
The problem is that in your BaseFont.CreateFont()
you are explicitly saying to embed but in your FontFactory.GetFont()
you are relying on system defaults which is to not embed. You need to use the longer version of the GetFont()
method which specifies embedding.
It looks like you're using the 4.1.6 version which I don't have laying around but this should be pretty much the same except for the last parameter:
iTextSharp.text.FontFactory.GetFont(FONT, BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 20, iTextSharp.text.Font.BOLD, BaseColor.RED)
Also, GetFont()
is intended to take a font name, not a path, although if that name lookup fails it does still restort to calling BaseFont.Create()
but I'm not sure if you should rely on that. Instead, you should pre-register your fonts:
iTextSharp.text.FontFactory.Register(FONT, "Treb")
Then you can use GetFont()
with the alias.
iTextSharp.text.FontFactory.GetFont("Treb", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 20, iTextSharp.text.Font.BOLD, BaseColor.RED)
The advantage of doing this is that if for some reason your font file gets renamed or deleted, FontFactory.Register()
will throw an exception whereas FontFactory.GetFont()
will silently fail with a fallback font. The silent fallback sounds nice but you also might spend hours troubleshooting something that's an easy fix.
Upvotes: 1