Browse Source

加载字体2

yaoyi 1 week ago
parent
commit
4bcfc8f1e5
1 changed files with 16 additions and 15 deletions
  1. 16 15
      src/main/java/com/hr/repository/service/impl/FontManager.java

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

@@ -13,6 +13,8 @@ import java.awt.*;
 import java.io.ByteArrayInputStream;
 import java.io.IOException;
 import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
 
 /**
  * @author yaoy
@@ -68,35 +70,34 @@ public class FontManager {
 
             log.info("尝试加载字体文件: {}", fontPath);
             log.info("资源存在: {}", resource.exists());
-            log.info("资源URL: {}", resource.getURL());
 
             if (!resource.exists()) {
                 log.error("字体文件不存在: {}", fontPath);
                 return new Font("SansSerif", Font.PLAIN, 12);
             }
 
-            // 获取文件大小
-            long contentLength = resource.contentLength();
-            log.info("字体文件大小: {} bytes", contentLength);
-
-            if (contentLength == 0) {
-                log.error("字体文件为空");
-                return new Font("SansSerif", Font.PLAIN, 12);
-            }
-
-            // 读取为字节数组并验证
+            // 读取为字节数组
             byte[] fontData = StreamUtils.copyToByteArray(resource.getInputStream());
-            log.info("实际读取字节数: {}", fontData.length);
+            log.info("字体文件大小: {} bytes", fontData.length);
 
             if (fontData.length == 0) {
-                log.error("无法读取字体数据");
+                log.error("字体文件为空");
                 return new Font("SansSerif", Font.PLAIN, 12);
             }
 
-            // 创建字体
-            Font font = Font.createFont(Font.TRUETYPE_FONT, new ByteArrayInputStream(fontData));
+            // 写入临时文件
+            Path tempFile = Files.createTempFile("font_", ".ttf");
+            Files.write(tempFile, fontData);
+            log.info("写入临时文件:{}", tempFile.getFileName().toString());
+
+            // 从临时文件加载字体
+            Font font = Font.createFont(Font.TRUETYPE_FONT, tempFile.toFile());
             log.info("字体加载成功: {} (family: {}, name: {})",
                     font.getFontName(), font.getFamily(), font.getName());
+
+            // 删除临时文件(可选)
+            tempFile.toFile().deleteOnExit();
+            log.info("删除临时文件");
             return font;
 
         } catch (Exception e) {