如何检查Font是否可嵌入

Jay*_*yan 4 java itext

我正在使用itext来创建PDf文档.由于许可限制,某些字体无法使用.

...
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)
...
Run Code Online (Sandbox Code Playgroud)

我正在考虑检查字体或PDF内容来检查这种情况.如何使用java或itext检查Font是否可嵌入?

ken*_*ohn 5

据我所知,没有直接的方法来确定是否可以嵌入字体.我做了一个快速搜索,除了使用Erik在评论中提到的异常catch方法之外,我认为不可能.

 // 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 );
   }
}
Run Code Online (Sandbox Code Playgroud)

您可以真正去硬核并执行对Windows Apis的本机调用以获得相同的结果,但我认为这对于一个简单的任务来说太多了.

做了一些研究,发现了Java如何抛出这个异常

可以在此处找到生成上述异常的代码. http://kickjava.com/src/com/lowagie/text/pdf/TrueTypeFont.java.htm 行号367,368

if (!justNames && embedded && os_2.fsType == 2)
     throw new DocumentException(fileName + style + " cannot be embedded due to licensing restrictions.");
Run Code Online (Sandbox Code Playgroud)

需要注意的有趣部分是条件 os_2.fsType == 2

os_2是WindowsMetrics查看第174行 的实例http://kickjava.com/src/com/lowagie/text/pdf/TrueTypeFont.java.htm

在Google中搜索WindowsMetrics,这就是我所获得的.

这解释了参数fsType保存了是否可以嵌入字体的信息. http://www.microsoft.com/typography/otspec/os2ver3.htm#fst

在itext中使用的java等价的WindowsMetrics http://www.docjar.org/docs/api/com/lowagie/text/pdf/TrueTypeFont.WindowsMetrics.html