Selaa lähdekoodia

加载字体2,不使用临时字体文件

yaoyi 1 viikko sitten
vanhempi
commit
1d8b20bcbf
1 muutettua tiedostoa jossa 16 lisäystä ja 13 poistoa
  1. 16 13
      src/main/java/com/hr/repository/service/impl/FontManager.java

+ 16 - 13
src/main/java/com/hr/repository/service/impl/FontManager.java

@@ -76,7 +76,7 @@ public class FontManager {
                 return new Font("SansSerif", Font.PLAIN, 12);
             }
 
-            // 读取为字节数组
+            // 直接读取为字节数组
             byte[] fontData = StreamUtils.copyToByteArray(resource.getInputStream());
             log.info("字体文件大小: {} bytes", fontData.length);
 
@@ -85,24 +85,27 @@ public class FontManager {
                 return new Font("SansSerif", Font.PLAIN, 12);
             }
 
-            // 写入临时文件
-            Path tempFile = Files.createTempFile("font_", ".ttf");
-            Files.write(tempFile, fontData);
-            log.info("写入临时文件:{}", tempFile.toFile().getAbsolutePath());
+            // 直接从字节数组创建字体,无需临时文件
+            Font font = Font.createFont(Font.TRUETYPE_FONT, new ByteArrayInputStream(fontData));
+            Font derivedFont = font.deriveFont(12f); // 设置字体大小
 
-            // 从临时文件加载字体
-            Font font = Font.createFont(Font.TRUETYPE_FONT, tempFile.toFile());
             log.info("字体加载成功: {} (family: {}, name: {})",
-                    font.getFontName(), font.getFamily(), font.getName());
+                    derivedFont.getFontName(), derivedFont.getFamily(), derivedFont.getName());
 
-            // 删除临时文件(可选)
-            tempFile.toFile().deleteOnExit();
-            log.info("删除临时文件");
-            return font;
+            return derivedFont;
 
         } catch (Exception e) {
             log.error("加载字体失败", e);
-            return new Font("SansSerif", Font.PLAIN, 12);
+            // 提供多种备选方案
+            try {
+                // 尝试使用系统默认字体
+                Font defaultFont = new Font("Dialog", Font.PLAIN, 12);
+                log.info("使用默认字体: {}", defaultFont.getName());
+                return defaultFont;
+            } catch (Exception ex) {
+                log.error("创建默认字体也失败", ex);
+                return Font.decode(null); // 返回系统默认字体
+            }
         }
 
     }