package com.dpkj.modules.print.utils; import com.itextpdf.text.pdf.BaseFont; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; /** * @author 余文财 * @description 字体加载 * @date 2025.6.24 */ public class FontLoader { public static BaseFont loadFont(String resourcePath) { try (InputStream fontStream = FontLoader.class.getResourceAsStream(resourcePath)) { if (fontStream == null) { throw new IllegalArgumentException("字体文件未找到: " + resourcePath); } byte[] fontBytes = toByteArray(fontStream); return BaseFont.createFont( resourcePath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED, false, fontBytes, null ); } catch (Exception e) { throw new RuntimeException("字体加载失败: " + resourcePath, e); } } private static byte[] toByteArray(InputStream input) throws IOException { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); int nRead; byte[] data = new byte[4096]; while ((nRead = input.read(data, 0, data.length)) != -1) { buffer.write(data, 0, nRead); } return buffer.toByteArray(); } }