how to CHECK if a Font is embeddable
I am using itext to create PDf documents. Certain fonts cannot be used due to licensing restrictions.
...
ExceptionConverter: com.lowagie.text.DocumentException: C:\WINDOWS\Fonts\LucidaSansRegular.ttf cannot be embedded due to licensing restrictions.
at com.lowagie.text.pdf.TrueTypeFontUnicode.<init>(Unknown Source)
at com.lowagie.text.pdf.BaseFont.createFont(Unknown Source)
at com.lowagie.text.pdf.BaseFont.createFont(Unknown Source)
at com.lowagie.text.pdf.BaseFont.createFont(Unknown Source)
开发者_如何转开发 at com.lowagie.text.pdf.DefaultFontMapper.awtToPdf(Unknown Source)
at com.lowagie.text.pdf.PdfGraphics2D.getCachedBaseFont(Unknown Source)
at com.lowagie.text.pdf.PdfGraphics2D.setFont(Unknown Source)
...
I am thinking of checking font or PDF content to check this case. How to check if a Font is embeddable using java or itext?
As far as I can tell there is no direct way to identify whether a font can be embedded. I did a quick search and I don't think it is possible other than using the exception catch method as mentioned by Erik in the comments.
// 1) have a list of all fonts ArrayList allAvailableFonts;
// 2) second list of fonts that that can be embedded ArrayList embedableFonts;
//Iterate through every available font in allAvailableFonts
for( .... allAvailableFonts ..... )
{
boolean isFontEmbeddable = true;
try
{
// try to embed the font
}
catch( DocumentException de)
{
//this font cannot be embedded
isEmbeddable = false;
}
if( isEmbeddable )
{
// add to list of embeddable fonts
embedableFonts.add ( font );
}
}
You can probably go really hardcore and execute native calls to Windows Apis to get the same result, but I think its too much work for a simple task as this.
Did some research and found out how this exception is thrown by Java
The code which generates the above exception can be found here. http://kickjava.com/src/com/lowagie/text/pdf/TrueTypeFont.java.htm Line number 367,368
if (!justNames && embedded && os_2.fsType == 2)
throw new DocumentException(fileName + style + " cannot be embedded due to licensing restrictions.");
The interesting part to note is the condition os_2.fsType == 2
os_2 is an instance of WindowsMetrics
see line 174 here
http://kickjava.com/src/com/lowagie/text/pdf/TrueTypeFont.java.htm
A search for WindowsMetrics in Google and this was what I got.
This explains that the parameter fsType holds information whether font can be embedded. http://www.microsoft.com/typography/otspec/os2ver3.htm#fst
The java equivalent of WindowsMetrics as used in itext http://www.docjar.org/docs/api/com/lowagie/text/pdf/TrueTypeFont.WindowsMetrics.html
精彩评论