Files
yinyitong-zhongyuyuan-dll-s…/src/main/java/com/dpkj/modules/print/utils/FontLoader.java

44 lines
1.3 KiB
Java
Raw Normal View History

2025-06-25 10:01:50 +08:00
package com.dpkj.modules.print.utils;
import com.itextpdf.text.pdf.BaseFont;
2025-06-26 11:33:08 +08:00
import java.io.ByteArrayOutputStream;
import java.io.IOException;
2025-06-25 10:01:50 +08:00
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);
}
2025-06-26 11:33:08 +08:00
byte[] fontBytes = toByteArray(fontStream);
2025-06-25 10:01:50 +08:00
return BaseFont.createFont(
resourcePath,
BaseFont.IDENTITY_H,
BaseFont.EMBEDDED,
false,
2025-06-26 11:33:08 +08:00
fontBytes,
2025-06-25 10:01:50 +08:00
null
);
} catch (Exception e) {
throw new RuntimeException("字体加载失败: " + resourcePath, e);
}
}
2025-06-26 11:33:08 +08:00
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();
}
2025-06-25 10:01:50 +08:00
}