From 7c687dd3c8fba9f7632f5e29d94a708e5f497abd Mon Sep 17 00:00:00 2001
From: kongdeqiang <123456>
Date: 星期一, 12 十月 2026 09:55:39 +0800
Subject: [PATCH] fix: 新增分组
---
src/main/java/com/custom/webui/dto/resp/ChatGroupDTO.java | 22
src/main/java/com/custom/webui/service/impl/ChatGroupServiceImpl.java | 157 ++++++
src/main/java/com/custom/webui/config/props/ExportProperties.java | 45 +
src/main/java/com/custom/webui/mapper/ChatGroupMapper.java | 8
src/main/java/com/custom/webui/dto/req/ChatGroupMoveRequest.java | 19
src/main/java/com/custom/webui/dto/req/ChatGroupRequest.java | 14
src/main/java/com/custom/webui/service/impl/ChatExportServiceImpl.java | 408 ++++++++++++++++
src/main/java/com/custom/webui/util/ChatPdfWriter.java | 300 ++++++++++++
src/main/java/com/custom/webui/service/ChatGroupService.java | 38 +
src/main/java/com/custom/webui/controller/ChatGroupController.java | 67 ++
src/main/java/com/custom/webui/service/ChatExportService.java | 66 ++
src/main/java/com/custom/webui/util/PdfFontSupport.java | 327 +++++++++++++
src/main/java/com/custom/webui/entity/ChatGroup.java | 29 +
13 files changed, 1,500 insertions(+), 0 deletions(-)
diff --git a/src/main/java/com/custom/webui/config/props/ExportProperties.java b/src/main/java/com/custom/webui/config/props/ExportProperties.java
new file mode 100644
index 0000000..3ed86f4
--- /dev/null
+++ b/src/main/java/com/custom/webui/config/props/ExportProperties.java
@@ -0,0 +1,45 @@
+package com.custom.webui.config.props;
+
+import lombok.Data;
+import org.springframework.boot.context.properties.ConfigurationProperties;
+
+/**
+ * 浼氳瘽瀵煎嚭閰嶇疆锛屽墠缂� {@code webui.export}銆�
+ */
+@Data
+@ConfigurationProperties(prefix = "webui.export")
+public class ExportProperties {
+
+ /**
+ * PDF 涓枃瀛椾綋鏂囦欢璺緞锛岀暀绌烘椂鎸夊唴缃�欓�夊垪琛ㄨ嚜鍔ㄦ帰娴嬨��
+ *
+ * <p><b>涓轰粈涔堥渶瑕佸畠</b>锛歅DF 閲岀殑涓枃蹇呴』闈�**宓屽叆瀛椾綋**鎵嶈兘淇濊瘉浠讳綍闃呰鍣�
+ * 閮借兘姝g‘鏄剧ず銆侾DF 鍐呯疆鐨� 14 涓爣鍑嗗瓧浣擄紙Helvetica 绛夛級鍙鐩� Latin-1锛�
+ * 涓枃鍐欒繘鍘讳細鐩存帴鎶� {@code IllegalArgumentException: No glyph for U+4E2D}锛�
+ * 鑰屼娇鐢ㄤ笉宓屽叆鐨勩�屾爣鍑� CJK 瀛椾綋銆嶏紙濡� STSong-Light + UniGB-UCS2-H锛�
+ * 铏界劧涓嶇敤甯﹀瓧浣撴枃浠讹紝浣� macOS 棰勮绛夐槄璇诲櫒鏈繀瑁呬簡瀵瑰簲瀛椾綋锛�
+ * 鎵撳紑灏辨槸涓�鐗囩┖鐧芥垨涔辩爜 鈥斺�� 瀵煎嚭鐨勬枃浠舵槸缁欑敤鎴烽暱鏈熶繚瀛樼殑锛�
+ * 涓嶈兘璧屽鏂规満鍣ㄤ笂瑁呬簡浠�涔堛��
+ *
+ * <p>鎵�浠ラ粯璁よ嚜鍔ㄦ帰娴嬬郴缁熼噷鐜版垚鐨勪腑鏂囧瓧浣擄紙macOS 鐨� Arial Unicode銆�
+ * Linux 鐨� Noto CJK銆乄indows 鐨勫井杞泤榛戠瓑锛夈�傛帰娴嬪け璐ヤ笉浼氳绋嬪簭璧蜂笉鏉ワ紝
+ * 鍙槸 PDF 瀵煎嚭浼氳繑鍥炰竴鏉″甫鎿嶄綔鎸囧紩鐨勯敊璇紝TXT / JSON 瀵煎嚭涓嶅彈褰卞搷銆�
+ */
+ private String pdfFontPath = "";
+
+ /**
+ * 鍗曟瀵煎嚭鏈�澶氬寘鍚殑娑堟伅鏉℃暟銆�
+ *
+ * <p>闃叉涓�鏉¤秴闀垮璇濈敓鎴愬嚑鍗佸厗鐨� PDF 鎶婂唴瀛樺拰鍝嶅簲鏃堕棿鎷栧灝锛�
+ * 瓒呭嚭鏃朵細鎴柇骞跺湪鏂囦欢鏈熬鍐欐槑銆屽凡鎴柇銆嶃��
+ */
+ private int maxMessages = 2000;
+
+ /**
+ * 鍗曟潯娑堟伅姝f枃杩涘叆瀵煎嚭鏂囦欢鐨勫瓧绗︿笂闄愩��
+ *
+ * <p>姣� maxMessages 鏇村父瑙佺殑澶辨帶鏉ユ簮鍏跺疄鏄�**鍗曟潯**瓒呴暱娑堟伅
+ * 锛堟瘮濡傛妸涓�鏁寸瘒鏂囨。绮樿繘瀵硅瘽锛夈��
+ */
+ private int maxCharsPerMessage = 20000;
+}
diff --git a/src/main/java/com/custom/webui/controller/ChatGroupController.java b/src/main/java/com/custom/webui/controller/ChatGroupController.java
new file mode 100644
index 0000000..9c6cc19
--- /dev/null
+++ b/src/main/java/com/custom/webui/controller/ChatGroupController.java
@@ -0,0 +1,67 @@
+package com.custom.webui.controller;
+
+import com.custom.webui.dto.req.ChatGroupRequest;
+import com.custom.webui.dto.resp.ChatGroupDTO;
+import com.custom.webui.dto.resp.Result;
+import com.custom.webui.security.CurrentUser;
+import com.custom.webui.service.ChatGroupService;
+import jakarta.validation.Valid;
+import lombok.RequiredArgsConstructor;
+import org.springframework.web.bind.annotation.DeleteMapping;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.PutMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import java.util.List;
+import java.util.Map;
+
+/**
+ * 瀵硅瘽鍒嗙粍鎺ュ彛锛屽搴斾晶杈规爮銆屽垎缁勩�嶅尯鍧楅噷鐨勫鍒犳敼銆�
+ *
+ * <p>鎶婁細璇濇斁杩涘幓 / 鎷垮嚭鏉ヤ笉鍦ㄨ繖閲岋紝鑰屽湪
+ * {@code PUT /api/chats/{id}/group} 鈥斺�� 鍒嗙粍鏄細璇濈殑灞炴�э紝
+ * 浠庝細璇濋偅涓�渚ф敼鏇磋嚜鐒讹紝涔熼伩鍏嶈繖涓帶鍒跺櫒瑕佷緷璧栦細璇濇湇鍔°��
+ */
+@RestController
+@RequestMapping("/api/chat-groups")
+@RequiredArgsConstructor
+public class ChatGroupController {
+
+ private final ChatGroupService chatGroupService;
+
+ /** 褰撳墠鐢ㄦ埛鐨勫叏閮ㄥ垎缁� */
+ @GetMapping
+ public Result<List<ChatGroupDTO>> list() {
+ return Result.success(chatGroupService.listByUser(CurrentUser.requireUserId()));
+ }
+
+ /** 鏂板缓鍒嗙粍 */
+ @PostMapping
+ public Result<ChatGroupDTO> create(@Valid @RequestBody ChatGroupRequest request) {
+ return Result.success(chatGroupService.create(CurrentUser.requireUserId(), request));
+ }
+
+ /** 閲嶅懡鍚嶅垎缁� */
+ @PutMapping("/{id}")
+ public Result<ChatGroupDTO> rename(@PathVariable Long id,
+ @Valid @RequestBody ChatGroupRequest request) {
+ return Result.success(chatGroupService.rename(CurrentUser.requireUserId(), id, request));
+ }
+
+ /**
+ * 鍒犻櫎鍒嗙粍銆�
+ *
+ * <p>杩斿洖 {@code movedChats}锛堣绉诲嚭鍒嗙粍銆佸洖鍒版湭鍒嗙粍鐨勪細璇濇暟锛夛紝
+ * 璁╁墠绔兘鏄庣‘鍛婅瘔鐢ㄦ埛銆屽垎缁勫垹浜嗭紝閲岄潰鐨� 3 鏉″璇濆凡鍥炲埌鏈垎缁勩�嶁�斺��
+ * 鍙銆屽凡鍒犻櫎銆嶄細璁╀汉鎷呭績瀵硅瘽鏄惁涔熶竴璧锋病浜嗐��
+ */
+ @DeleteMapping("/{id}")
+ public Result<Map<String, Object>> delete(@PathVariable Long id) {
+ int moved = chatGroupService.delete(CurrentUser.requireUserId(), id);
+ return Result.success(Map.of("movedChats", moved));
+ }
+}
diff --git a/src/main/java/com/custom/webui/dto/req/ChatGroupMoveRequest.java b/src/main/java/com/custom/webui/dto/req/ChatGroupMoveRequest.java
new file mode 100644
index 0000000..7707ccf
--- /dev/null
+++ b/src/main/java/com/custom/webui/dto/req/ChatGroupMoveRequest.java
@@ -0,0 +1,19 @@
+package com.custom.webui.dto.req;
+
+import lombok.Data;
+
+/**
+ * 鎶婁細璇濈Щ鍏� / 绉诲嚭鍒嗙粍鐨勮姹備綋銆�
+ *
+ * <p><b>涓轰粈涔堝崟鐙竴涓鐐癸紝鑰屼笉鏄鐢� {@code PUT /api/chats/{id}}</b>锛�
+ * 浼氳瘽鏇存柊鎺ュ彛绾﹀畾銆屽瓧娈典负 null 琛ㄧず涓嶄慨鏀广�嶏紝鑰屻�岀Щ鍑哄垎缁勩�嶆伆鎭板氨鏄鎶�
+ * groupId 缃负 null 鈥斺�� 涓ょ璇箟鍦ㄥ悓涓�涓瓧娈典笂鏃犳硶鍖哄垎銆�
+ * 鐢ㄤ竴涓笓闂ㄧ殑绔偣銆乥ody 閲� {@code groupId: null} 鏄庣‘琛ㄧず銆岀Щ鍑哄垎缁勩�嶏紝
+ * 灏变笉浼氭湁姝т箟銆�
+ */
+@Data
+public class ChatGroupMoveRequest {
+
+ /** 鐩爣鍒嗙粍 id锛沶ull = 绉诲嚭鍒嗙粍锛堝洖鍒版湭鍒嗙粍锛岀户缁寜鏃堕棿褰掔被锛� */
+ private Long groupId;
+}
diff --git a/src/main/java/com/custom/webui/dto/req/ChatGroupRequest.java b/src/main/java/com/custom/webui/dto/req/ChatGroupRequest.java
new file mode 100644
index 0000000..3b5d93d
--- /dev/null
+++ b/src/main/java/com/custom/webui/dto/req/ChatGroupRequest.java
@@ -0,0 +1,14 @@
+package com.custom.webui.dto.req;
+
+import jakarta.validation.constraints.NotBlank;
+import jakarta.validation.constraints.Size;
+import lombok.Data;
+
+/** 鏂板缓 / 閲嶅懡鍚嶅垎缁勭殑璇锋眰浣撱�� */
+@Data
+public class ChatGroupRequest {
+
+ @NotBlank(message = "鍒嗙粍鍚嶄笉鑳戒负绌�")
+ @Size(max = 64, message = "鍒嗙粍鍚嶈繃闀匡紙鏈�澶� 64 瀛楋級")
+ private String name;
+}
diff --git a/src/main/java/com/custom/webui/dto/resp/ChatGroupDTO.java b/src/main/java/com/custom/webui/dto/resp/ChatGroupDTO.java
new file mode 100644
index 0000000..99b3af7
--- /dev/null
+++ b/src/main/java/com/custom/webui/dto/resp/ChatGroupDTO.java
@@ -0,0 +1,22 @@
+package com.custom.webui.dto.resp;
+
+import lombok.Data;
+
+/**
+ * 瀵硅瘽鍒嗙粍杩斿洖浣撱��
+ */
+@Data
+public class ChatGroupDTO {
+
+ private Long id;
+
+ private String name;
+
+ /**
+ * 璇ュ垎缁勪笅鐨勪細璇濇暟锛堜笉鍚凡褰掓。鐨勶級銆�
+ *
+ * <p>褰掓。鐨勪細璇濅笉鍦ㄤ富鍒楄〃閲屾樉绀猴紝鑷劧涔熶笉璇ョ畻杩涘垎缁勭殑鏁板瓧閲岋紝
+ * 鍚﹀垯鐢ㄦ埛浼氱湅鍒般�屽垎缁勯噷鏈� 3 鏉°�嶄絾鐐瑰紑鍙湁 1 鏉°��
+ */
+ private Long chatCount;
+}
diff --git a/src/main/java/com/custom/webui/entity/ChatGroup.java b/src/main/java/com/custom/webui/entity/ChatGroup.java
new file mode 100644
index 0000000..140dbe0
--- /dev/null
+++ b/src/main/java/com/custom/webui/entity/ChatGroup.java
@@ -0,0 +1,29 @@
+package com.custom.webui.entity;
+
+import com.baomidou.mybatisplus.annotation.IdType;
+import com.baomidou.mybatisplus.annotation.TableId;
+import com.baomidou.mybatisplus.annotation.TableName;
+import lombok.Data;
+
+import java.time.LocalDateTime;
+
+/**
+ * 瀵硅瘽鍒嗙粍瀹炰綋锛屽搴旇〃 {@code chat_group}銆�
+ *
+ * <p>杩欐槸**鐢ㄦ埛鑷缓**鐨勬枃浠跺す锛屼笌渚ц竟鏍忛噷鐨勩�屼粖澶� / 鏄ㄥぉ / 鏇存棭銆�
+ * 鑷姩鏃堕棿鍒嗙粍鏄袱鍥炰簨锛氭椂闂村垎缁勬槸鍙鐨勮鍥惧綊绫伙紝鍒嗙粍鏄彲鍛藉悕銆佸彲澧炲垹鐨勩��
+ */
+@Data
+@TableName("chat_group")
+public class ChatGroup {
+
+ @TableId(type = IdType.AUTO)
+ private Long id;
+
+ /** 鎵�灞炵敤鎴� id锛屾墍鏈夋煡璇㈠繀椤诲甫涓婅鏉′欢鍋氭暟鎹殧绂� */
+ private Long userId;
+
+ private String name;
+
+ private LocalDateTime createdAt;
+}
diff --git a/src/main/java/com/custom/webui/mapper/ChatGroupMapper.java b/src/main/java/com/custom/webui/mapper/ChatGroupMapper.java
new file mode 100644
index 0000000..8bdc993
--- /dev/null
+++ b/src/main/java/com/custom/webui/mapper/ChatGroupMapper.java
@@ -0,0 +1,8 @@
+package com.custom.webui.mapper;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.custom.webui.entity.ChatGroup;
+
+/** 瀵硅瘽鍒嗙粍 Mapper銆� */
+public interface ChatGroupMapper extends BaseMapper<ChatGroup> {
+}
diff --git a/src/main/java/com/custom/webui/service/ChatExportService.java b/src/main/java/com/custom/webui/service/ChatExportService.java
new file mode 100644
index 0000000..4f6fe72
--- /dev/null
+++ b/src/main/java/com/custom/webui/service/ChatExportService.java
@@ -0,0 +1,66 @@
+package com.custom.webui.service;
+
+import com.custom.webui.exception.BusinessException;
+
+/**
+ * 浼氳瘽瀵煎嚭鏈嶅姟锛氭妸涓�涓璇濆鍑烘垚 JSON / TXT / PDF銆�
+ *
+ * <p>涓夎�呯殑瀹氫綅涓嶅悓锛屼笉鏄悓涓�浠藉唴瀹规崲涓夌鍚庣紑锛�
+ * <ul>
+ * <li><b>JSON</b> 鈥斺�� 缁欑▼搴忕敤鐨勩�傞櫎褰撳墠鏄剧ず鐨勫垎鏀锛岃繕甯︿笂鎵佸钩鐨勫叏閲忔秷鎭�
+ * 锛堝惈 parentId锛夛紝鍥犳**鍒嗘敮缁撴瀯涓嶄細涓�**锛屽彲浠ュ畬鏁磋繕鍘熸秷鎭爲銆�</li>
+ * <li><b>TXT</b> 鈥斺�� 缁欎汉鐪嬬殑绾枃鏈紝闅忎究浠�涔堝伐鍏烽兘鑳芥墦寮�銆佽兘 grep銆�</li>
+ * <li><b>PDF</b> 鈥斺�� 鐢ㄤ簬褰掓。銆佹墦鍗般�佸彂缁欏埆浜恒�備腑鏂囧瓧浣撴寜瀛愰泦宓屽叆锛�
+ * 鍦ㄤ换浣曢槄璇诲櫒閲岄兘鑳芥纭樉绀恒��</li>
+ * </ul>
+ */
+public interface ChatExportService {
+
+ /** 瀵煎嚭鏍煎紡 */
+ enum Format {
+ JSON, TXT, PDF;
+
+ /** 瑙f瀽鏍煎紡鍙傛暟锛屼笉璁よ瘑鐨勫�肩洿鎺ユ姤閿欒�屼笉鏄倓鎮勬寜榛樿鍊煎鐞� */
+ public static Format parse(String raw) {
+ if (raw == null || raw.isBlank()) {
+ return TXT;
+ }
+ for (Format f : values()) {
+ if (f.name().equalsIgnoreCase(raw.trim())) {
+ return f;
+ }
+ }
+ throw BusinessException.badRequest(
+ "涓嶆敮鎸佺殑瀵煎嚭鏍煎紡锛�" + raw + "锛堝彲閫� json / txt / pdf锛�");
+ }
+
+ public String extension() {
+ return name().toLowerCase();
+ }
+
+ public String contentType() {
+ return switch (this) {
+ case JSON -> "application/json;charset=UTF-8";
+ case TXT -> "text/plain;charset=UTF-8";
+ case PDF -> "application/pdf";
+ };
+ }
+ }
+
+ /**
+ * 瀵煎嚭缁撴灉銆�
+ *
+ * @param data 鏂囦欢瀛楄妭
+ * @param filename 寤鸿鐨勬枃浠跺悕锛堝凡鍋氶潪娉曞瓧绗︽竻娲楋級
+ * @param contentType MIME 绫诲瀷
+ */
+ record ExportFile(byte[] data, String filename, String contentType) {
+ }
+
+ /**
+ * 瀵煎嚭涓�涓細璇濄��
+ *
+ * @throws com.custom.webui.exception.BusinessException 浼氳瘽涓嶅瓨鍦ㄦ垨涓嶅睘浜庤鐢ㄦ埛锛�404锛�
+ */
+ ExportFile export(Long userId, Long chatId, Format format);
+}
diff --git a/src/main/java/com/custom/webui/service/ChatGroupService.java b/src/main/java/com/custom/webui/service/ChatGroupService.java
new file mode 100644
index 0000000..1e751ae
--- /dev/null
+++ b/src/main/java/com/custom/webui/service/ChatGroupService.java
@@ -0,0 +1,38 @@
+package com.custom.webui.service;
+
+import com.custom.webui.dto.req.ChatGroupRequest;
+import com.custom.webui.dto.resp.ChatGroupDTO;
+import com.custom.webui.entity.ChatGroup;
+
+import java.util.List;
+
+/**
+ * 瀵硅瘽鍒嗙粍鏈嶅姟锛堢敤鎴疯嚜寤虹殑鏂囦欢澶癸級銆�
+ *
+ * <p><b>鏁版嵁闅旂绾﹀畾</b>锛氭墍鏈夋柟娉曢兘蹇呴』鎺ユ敹 {@code userId} 骞跺湪鏌ヨ鏉′欢閲屽甫涓婏紝
+ * 涓� {@link ChatService} 涓�鑷淬�傚垎缁勪笌鏀惰棌澶圭被浼硷紝瓒婃潈璇诲彇浠栦汉鍒嗙粍鍚嶅悓鏍峰睘浜庝俊鎭硠闇层��
+ */
+public interface ChatGroupService {
+
+ /** 褰撳墠鐢ㄦ埛鐨勫叏閮ㄥ垎缁勶紝鎸夊垱寤洪『搴忥紙鏂板缓鐨勬帓鍦ㄥ悗闈級 */
+ List<ChatGroupDTO> listByUser(Long userId);
+
+ /** 鏂板缓鍒嗙粍锛屽悓鍚嶆椂杩斿洖 400 鑰屼笉鏄暟鎹簱鍞竴閿敊璇� */
+ ChatGroupDTO create(Long userId, ChatGroupRequest request);
+
+ /** 閲嶅懡鍚嶅垎缁� */
+ ChatGroupDTO rename(Long userId, Long groupId, ChatGroupRequest request);
+
+ /**
+ * 鍒犻櫎鍒嗙粍銆�
+ *
+ * <p><b>涓嶄細鍒犻櫎缁勫唴浼氳瘽</b>锛氬彧鎶婂畠浠殑 group_id 缃┖锛屽洖鍒般�屾湭鍒嗙粍銆�
+ * 缁х画鎸夋椂闂村綊绫汇�傚垎缁勫彧鏄暣鐞嗘墜娈碉紝鍒犱竴涓枃浠跺す涓嶈杩炲甫姣佹帀閲岄潰鐨勫唴瀹广��
+ *
+ * @return 琚Щ鍑哄垎缁勭殑浼氳瘽鏁帮紝鐢ㄤ簬缁欑敤鎴蜂竴涓槑纭彁绀�
+ */
+ int delete(Long userId, Long groupId);
+
+ /** 鏍¢獙鍒嗙粍褰掑睘锛涗笉灞炰簬璇ョ敤鎴锋椂鎶� 404锛堣�岄潪 403锛岄伩鍏嶆帰娴嬩粬浜哄垎缁勬槸鍚﹀瓨鍦級 */
+ ChatGroup requireOwnedGroup(Long userId, Long groupId);
+}
diff --git a/src/main/java/com/custom/webui/service/impl/ChatExportServiceImpl.java b/src/main/java/com/custom/webui/service/impl/ChatExportServiceImpl.java
new file mode 100644
index 0000000..60a7881
--- /dev/null
+++ b/src/main/java/com/custom/webui/service/impl/ChatExportServiceImpl.java
@@ -0,0 +1,408 @@
+package com.custom.webui.service.impl;
+
+import com.baomidou.mybatisplus.core.toolkit.Wrappers;
+import com.custom.webui.config.props.ExportProperties;
+import com.custom.webui.dto.resp.MessageDTO;
+import com.custom.webui.dto.resp.StreamEvent;
+import com.custom.webui.entity.Chat;
+import com.custom.webui.entity.Message;
+import com.custom.webui.exception.BusinessException;
+import com.custom.webui.mapper.MessageMapper;
+import com.custom.webui.service.ChatExportService;
+import com.custom.webui.service.ChatService;
+import com.custom.webui.util.ChatPdfWriter;
+import com.custom.webui.util.MessageTreeUtil;
+import com.custom.webui.util.PdfFontSupport;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.pdfbox.pdmodel.PDDocument;
+import org.apache.pdfbox.pdmodel.PDDocumentInformation;
+import org.apache.pdfbox.pdfwriter.compress.CompressParameters;
+import org.springframework.stereotype.Service;
+
+import java.io.ByteArrayOutputStream;
+import java.nio.charset.StandardCharsets;
+import java.time.LocalDateTime;
+import java.time.format.DateTimeFormatter;
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * 浼氳瘽瀵煎嚭瀹炵幇銆�
+ *
+ * <h2>瀵煎嚭鐨勬槸銆屽綋鍓嶅垎鏀�嶈�屼笉鏄暣妫垫爲</h2>
+ * 涓�涓細璇濆洜涓恒�岄噸鏂扮敓鎴� / 缂栬緫娑堟伅銆嶅彲鑳藉瓨鍦ㄥ鏉″垎鏀紝鑰岀敤鎴峰睆骞曚笂鍚屼竴鏃跺埢
+ * 鍙湅鍒板叾涓竴鏉°�傚鍑虹殑璇箟鏄�屾妸鎴戠幇鍦ㄧ湅鍒扮殑杩欐瀵硅瘽瀛樹笅鏉ャ�嶏紝
+ * 鎵�浠� TXT / PDF 鍙蛋褰撳墠娲昏穬鍒嗘敮锛堜笌鍓嶇 {@code buildPath} 瀹屽叏涓�鑷寸殑瑙勫垯锛�
+ * 浠庢渶鍚庝竴涓牴鑺傜偣鍑哄彂锛屾部 {@code activeChildId} 鍓嶈繘锛岀己澶辨椂鍥為��鍒版渶鍚庝竴涓瓙鑺傜偣锛夈��
+ *
+ * <p>浣�**鍒嗘敮鏈韩灏辨槸杩欎釜椤圭洰鐨勬牳蹇冭兘鍔�**锛岀洿鎺ヤ涪鎺夊お鍙儨锛�
+ * 鍥犳 JSON 閲岄澶栫粰鍑� {@code allMessages}锛堟墎骞冲叏閲忥紝甯� parentId锛夆�斺��
+ * 鎯崇湅鍏ㄩ儴鍐呭鎴栧仛浜屾澶勭悊鐨勪汉鍙互鐢ㄥ畠杩樺師鏁存5鏍戙��
+ */
+@Slf4j
+@Service
+@RequiredArgsConstructor
+public class ChatExportServiceImpl implements ChatExportService {
+
+ private static final DateTimeFormatter DATE_TIME =
+ DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
+ private static final DateTimeFormatter FILE_STAMP =
+ DateTimeFormatter.ofPattern("yyyyMMdd-HHmmss");
+
+ /** 鏂囦欢鍚嶉噷淇濈暀鐨勬渶澶у瓧绗︽暟锛堜腑鏂囨枃浠跺悕杩囬暱鍦ㄩ儴鍒嗙郴缁熶笂浼氳鎴柇鐢氳嚦澶辫触锛� */
+ private static final int MAX_FILENAME_CHARS = 40;
+
+ /** Windows / macOS 閮戒笉鍏佽鍑虹幇鍦ㄦ枃浠跺悕閲岀殑瀛楃 */
+ private static final String ILLEGAL_FILENAME_CHARS = "[\\\\/:*?\"<>|\\r\\n\\t]";
+
+ private final ChatService chatService;
+ private final MessageMapper messageMapper;
+ private final PdfFontSupport pdfFontSupport;
+ private final ExportProperties properties;
+ private final ObjectMapper objectMapper;
+
+ @Override
+ public ExportFile export(Long userId, Long chatId, Format format) {
+ Chat chat = chatService.requireOwnedChat(userId, chatId);
+
+ List<Message> all = messageMapper.selectList(
+ Wrappers.<Message>lambdaQuery()
+ .eq(Message::getChatId, chatId)
+ .orderByAsc(Message::getId));
+
+ // 鏍� 鈫� 褰撳墠鍒嗘敮銆傛病鏈変换浣曟秷鎭椂缁欏嚭绌哄垪琛紝浠嶇劧瀵煎嚭涓�浠藉甫鏍囬鐨勭┖鏂囨。锛�
+ // 鑰屼笉鏄姤閿� 鈥斺�� 銆屽鍑恒�嶆槸鍙鎿嶄綔锛屾病鏈夌悊鐢卞洜涓哄璇濅负绌哄氨澶辫触銆�
+ List<MessageDTO> tree = MessageTreeUtil.buildTree(all);
+ List<MessageDTO> branch = activeBranch(tree);
+
+ String stamp = LocalDateTime.now().format(FILE_STAMP);
+ String filename = buildFilename(chat, stamp, format);
+
+ byte[] data = switch (format) {
+ case JSON -> toJson(chat, all, branch);
+ case TXT -> toText(chat, branch).getBytes(StandardCharsets.UTF_8);
+ case PDF -> toPdf(chat, branch);
+ };
+
+ log.info("瀵煎嚭浼氳瘽 userId={} chatId={} 鏍煎紡={} 娑堟伅={}/{} 瀛楄妭={}",
+ userId, chatId, format, branch.size(), all.size(), data.length);
+ return new ExportFile(data, filename, format.contentType());
+ }
+
+ // ==================================================================
+ // 褰撳墠鍒嗘敮
+ // ==================================================================
+
+ /**
+ * 娌挎椿璺冨垎鏀蛋鍑轰竴鏉$嚎鎬у璇濄��
+ *
+ * <p>瑙勫垯涓庡墠绔� {@code utils/treeBuild.js} 鐨� {@code buildPath} 淇濇寔涓�鑷� 鈥斺��
+ * 涓ゅ蹇呴』鍚屾簮锛屽惁鍒欎細鍑虹幇銆屽睆骞曚笂鏄繖鏍枫�佸鍑烘潵鏄偅鏍枫�嶇殑璇″紓闂锛�
+ * <ol>
+ * <li>璧风偣鍙�**鏈�鍚庝竴涓�**鏍硅妭鐐癸紙鑴忔暟鎹笅鍙兘鏈夊涓牴锛�</li>
+ * <li>姣忔浼樺厛璧� {@code activeChildId}锛屽畠缂哄け鎴栧凡澶辨晥鏃跺洖閫�鍒版渶鍚庝竴涓瓙鑺傜偣</li>
+ * <li>甯︽鏁颁笂闄愶紝闃叉鑴忔暟鎹垚鐜椂姝诲惊鐜�</li>
+ * </ol>
+ */
+ private List<MessageDTO> activeBranch(List<MessageDTO> tree) {
+ List<MessageDTO> path = new ArrayList<>();
+ if (tree == null || tree.isEmpty()) {
+ return path;
+ }
+
+ MessageDTO current = tree.get(tree.size() - 1);
+ int guard = 0;
+ while (current != null && guard++ < 10000) {
+ path.add(current);
+
+ List<MessageDTO> children = current.getChildren();
+ if (children == null || children.isEmpty()) {
+ break;
+ }
+
+ MessageDTO next = null;
+ if (current.getActiveChildId() != null) {
+ for (MessageDTO child : children) {
+ if (child.getId() != null && child.getId().equals(current.getActiveChildId())) {
+ next = child;
+ break;
+ }
+ }
+ }
+ if (next == null) {
+ next = children.get(children.size() - 1);
+ }
+ current = next;
+ }
+ return path;
+ }
+
+ // ==================================================================
+ // JSON
+ // ==================================================================
+
+ private byte[] toJson(Chat chat, List<Message> all, List<MessageDTO> branch) {
+ Map<String, Object> root = new LinkedHashMap<>();
+ root.put("exportedAt", LocalDateTime.now().format(DATE_TIME));
+ root.put("formatVersion", 1);
+ root.put("source", "custom-webui");
+
+ Map<String, Object> chatNode = new LinkedHashMap<>();
+ chatNode.put("id", chat.getId());
+ chatNode.put("title", chat.getTitle());
+ chatNode.put("createdAt", chat.getCreatedAt());
+ chatNode.put("updatedAt", chat.getUpdatedAt());
+ chatNode.put("pinned", Boolean.TRUE.equals(chat.getPinned()));
+ chatNode.put("archived", Boolean.TRUE.equals(chat.getArchived()));
+ chatNode.put("messageCount", all.size());
+ root.put("chat", chatNode);
+
+ // 褰撳墠鍒嗘敮锛氬甫寮曠敤鏉ユ簮銆佸浘鐗囩瓑灞曠ず鎵�闇�鐨勪俊鎭�
+ List<Map<String, Object>> messages = new ArrayList<>();
+ for (MessageDTO m : branch) {
+ Map<String, Object> node = new LinkedHashMap<>();
+ node.put("id", m.getId());
+ node.put("parentId", m.getParentId());
+ node.put("role", m.getRole());
+ node.put("content", m.getContent());
+ node.put("model", m.getModel());
+ node.put("createdAt", m.getCreatedAt());
+ if (m.getSources() != null && !m.getSources().isEmpty()) {
+ node.put("sources", m.getSources());
+ }
+ if (m.getImageFileIds() != null && !m.getImageFileIds().isEmpty()) {
+ node.put("imageFileIds", m.getImageFileIds());
+ }
+ messages.add(node);
+ }
+ root.put("messages", messages);
+
+ // 鎵佸钩鍏ㄩ噺锛氬惈鍏朵粬鍒嗘敮锛宲arentId 鍙繕鍘熸暣妫垫爲
+ List<Map<String, Object>> flat = new ArrayList<>();
+ for (Message m : all) {
+ Map<String, Object> node = new LinkedHashMap<>();
+ node.put("id", m.getId());
+ node.put("parentId", m.getParentId());
+ node.put("role", m.getRole());
+ node.put("content", m.getContent());
+ node.put("model", m.getModel());
+ node.put("createdAt", m.getCreatedAt());
+ flat.add(node);
+ }
+ root.put("allMessages", flat);
+ root.put("note", "messages 涓哄綋鍓嶆樉绀虹殑鍒嗘敮锛沘llMessages 涓烘墎骞冲叏閲忥紙鍚叾浠栧垎鏀級锛�"
+ + "鐢� parentId 鍙繕鍘熷畬鏁存秷鎭爲");
+
+ try {
+ return objectMapper.writerWithDefaultPrettyPrinter().writeValueAsBytes(root);
+ } catch (Exception e) {
+ throw BusinessException.serverError("鐢熸垚 JSON 澶辫触锛�" + e.getMessage());
+ }
+ }
+
+ // ==================================================================
+ // TXT
+ // ==================================================================
+
+ private String toText(Chat chat, List<MessageDTO> branch) {
+ StringBuilder sb = new StringBuilder(4096);
+ sb.append(chat.getTitle() == null ? "鏂板璇�" : chat.getTitle()).append('\n');
+ sb.append("=".repeat(48)).append('\n');
+ sb.append("瀵煎嚭鏃堕棿锛�").append(LocalDateTime.now().format(DATE_TIME)).append('\n');
+ sb.append("鍒涘缓鏃堕棿锛�").append(formatTime(chat.getCreatedAt())).append('\n');
+ sb.append("娑堟伅鏉℃暟锛�").append(branch.size()).append('\n');
+ sb.append('\n');
+
+ if (branch.isEmpty()) {
+ sb.append("锛堣繖娈靛璇濊繕娌℃湁娑堟伅锛塡n");
+ return sb.toString();
+ }
+
+ // 鎴柇璇存槑鍗曠嫭鏀堕泦锛屾渶鍚庡啀杩藉姞 鈥斺�� 涓嶈兘濉炶繘 sb 璁╁畠鍦ㄦ枃妗d腑闂村啋鍑烘潵
+ StringBuilder truncationNote = new StringBuilder();
+ List<MessageDTO> visible = truncateBranch(branch, truncationNote);
+
+ boolean first = true;
+ for (MessageDTO m : visible) {
+ if (!first) {
+ sb.append('\n');
+ }
+ first = false;
+ sb.append('[').append(formatTime(m.getCreatedAt())).append("] ")
+ .append(roleLabel(m)).append('\n');
+ sb.append("鈹�".repeat(32)).append('\n');
+ sb.append(clip(m.getContent())).append('\n');
+ appendExtras(sb, m);
+ }
+
+ if (truncationNote.length() > 0) {
+ sb.append('\n').append(truncationNote).append('\n');
+ }
+ return sb.toString();
+ }
+
+ // ==================================================================
+ // PDF
+ // ==================================================================
+
+ private byte[] toPdf(Chat chat, List<MessageDTO> branch) {
+ try (PDDocument document = new PDDocument();
+ ByteArrayOutputStream out = new ByteArrayOutputStream()) {
+
+ PDDocumentInformation info = new PDDocumentInformation();
+ info.setTitle(chat.getTitle() == null ? "瀵硅瘽" : chat.getTitle());
+ info.setProducer("custom-webui");
+ document.setDocumentInformation(info);
+
+ // 娉ㄦ剰鐢熷懡鍛ㄦ湡锛歟mbedSubset 鏄欢杩熷埌 save() 鎵嶈瀛椾綋鐨勶紝
+ // 鎵�浠� handle 蹇呴』娲诲埌 save() 涔嬪悗锛堣 PdfFontSupport 鐨勭被娉ㄩ噴锛�
+ try (PdfFontSupport.PdfFontHandle handle = pdfFontSupport.open(document)) {
+ ChatPdfWriter writer = new ChatPdfWriter(document, handle);
+
+ writer.writeTitle(chat.getTitle() == null ? "鏂板璇�" : chat.getTitle());
+ writer.writeMeta("瀵煎嚭鏃堕棿锛�" + LocalDateTime.now().format(DATE_TIME)
+ + " 鍒涘缓鏃堕棿锛�" + formatTime(chat.getCreatedAt())
+ + " 娑堟伅鏉℃暟锛�" + branch.size());
+ writer.writeSpacing(6f);
+ writer.writeRule();
+
+ if (branch.isEmpty()) {
+ writer.writeSpacing(10f);
+ writer.writeMeta("锛堣繖娈靛璇濊繕娌℃湁娑堟伅锛�");
+ }
+
+ StringBuilder truncationNote = new StringBuilder();
+ for (MessageDTO m : truncateBranch(branch, truncationNote)) {
+ writer.writeMessageHeader("[" + formatTime(m.getCreatedAt()) + "] " + roleLabel(m));
+ writer.writeParagraph(clip(m.getContent()));
+
+ String extras = extrasText(m);
+ if (!extras.isEmpty()) {
+ writer.writeSpacing(2f);
+ writer.writeMeta(extras);
+ }
+ writer.writeSpacing(6f);
+ }
+
+ if (truncationNote.length() > 0) {
+ writer.writeSpacing(6f);
+ writer.writeMeta(truncationNote.toString());
+ }
+
+ writer.close();
+ // 鍘嬬缉鍐呭娴侊細涓枃闀垮璇濅笉鍘嬬缉鏃朵綋绉細鏄庢樉鍋忓ぇ
+ document.save(out, CompressParameters.DEFAULT_COMPRESSION);
+ }
+ return out.toByteArray();
+ } catch (BusinessException e) {
+ throw e;
+ } catch (Exception e) {
+ log.error("鐢熸垚 PDF 澶辫触 chatId={}", chat.getId(), e);
+ throw BusinessException.serverError("鐢熸垚 PDF 澶辫触锛�" + e.getMessage());
+ }
+ }
+
+ // ==================================================================
+ // 鍏叡灏忓伐鍏�
+ // ==================================================================
+
+ /**
+ * 鎸変笂闄愭埅鏂垎鏀紝骞舵妸銆屾埅鏂簡銆嶈繖浠朵簨鍐欒繘 {@code note}銆�
+ *
+ * <p>闈欓粯鎴柇鏄笉鍙帴鍙楃殑锛氱敤鎴蜂細浠ヤ负瀵煎嚭鐨勫氨鏄叏閮ㄥ唴瀹广��
+ */
+ private List<MessageDTO> truncateBranch(List<MessageDTO> branch, StringBuilder note) {
+ int max = properties.getMaxMessages();
+ if (max <= 0 || branch.size() <= max) {
+ return branch;
+ }
+ note.append("娉ㄦ剰锛氳瀵硅瘽鍏� ").append(branch.size())
+ .append(" 鏉℃秷鎭紝宸叉寜閰嶇疆涓婇檺鍙鍑哄墠 ").append(max)
+ .append(" 鏉★紙鍙皟鏁� webui.export.max-messages锛夈��");
+ return branch.subList(0, max);
+ }
+
+ private String clip(String content) {
+ if (content == null) {
+ return "";
+ }
+ int max = properties.getMaxCharsPerMessage();
+ if (max > 0 && content.length() > max) {
+ return content.substring(0, max) + "\n鈥︼紙鏈潯娑堟伅杩囬暱锛屽凡鎴柇 " + (content.length() - max) + " 瀛楋級";
+ }
+ return content;
+ }
+
+ /** TXT 閲岄檮鍦ㄦ秷鎭笅鏂圭殑琛ュ厖淇℃伅锛氬紩鐢ㄦ潵婧愩�佸浘鐗囨暟閲� */
+ private void appendExtras(StringBuilder sb, MessageDTO m) {
+ String extras = extrasText(m);
+ if (!extras.isEmpty()) {
+ sb.append(extras).append('\n');
+ }
+ }
+
+ private String extrasText(MessageDTO m) {
+ List<String> parts = new ArrayList<>();
+ if (m.getSources() != null && !m.getSources().isEmpty()) {
+ List<String> refs = new ArrayList<>();
+ int index = 1;
+ for (StreamEvent.Source s : m.getSources()) {
+ StringBuilder one = new StringBuilder();
+ one.append('[').append(index++).append("] ");
+ one.append(s.getFilename() == null ? "(鏈煡鏂囦欢)" : s.getFilename());
+ if (s.getSection() != null && !s.getSection().isBlank()) {
+ one.append(" 路 ").append(s.getSection());
+ }
+ refs.add(one.toString());
+ }
+ parts.add("寮曠敤鏉ユ簮锛�" + String.join("锛�", refs));
+ }
+ if (m.getImageFileIds() != null && !m.getImageFileIds().isEmpty()) {
+ // 瀵煎嚭鏂囦欢涓嶅甫鍥剧墖鏈綋锛氬浘鐗囧瓨鍦ㄦ湇鍔$锛屼笖 PDF 閲屽祵鍥句細璁╀綋绉拰瀹炵幇澶嶆潅搴﹂兘闄″銆�
+ // 浣嗗繀椤�**鏄庣‘鍐欏嚭鏉�**锛屽惁鍒欑敤鎴蜂細浠ヤ负鍥剧墖鍐呭琚涪鎺変簡銆�
+ parts.add("锛绘湰鏉℃秷鎭檮甯� " + m.getImageFileIds().size() + " 寮犲浘鐗囷紝"
+ + "瀵煎嚭鏂囦欢涓嶅惈鍥剧墖鏈綋锛屽彲鍦ㄧ綉椤甸噷鏌ョ湅锛�");
+ }
+ return String.join("\n", parts);
+ }
+
+ private String roleLabel(MessageDTO m) {
+ String role = m.getRole() == null ? "" : m.getRole();
+ return switch (role) {
+ case "user" -> "鎴�";
+ case "assistant" -> m.getModel() == null || m.getModel().isBlank()
+ ? "AI" : "AI锛�" + m.getModel() + "锛�";
+ case "system" -> "绯荤粺";
+ default -> role;
+ };
+ }
+
+ private String formatTime(LocalDateTime time) {
+ return time == null ? "-" : time.format(DATE_TIME);
+ }
+
+ /**
+ * 鐢熸垚涓嬭浇鏂囦欢鍚嶏細{鏍囬}_{鏃堕棿鎴硙.{鍚庣紑}
+ *
+ * <p>鏍囬鏉ヨ嚜鐢ㄦ埛杈撳叆锛堟棭鏈熺増鏈敋鑷虫槸妯″瀷鐢熸垚鐨勶級锛岄噷闈㈠畬鍏ㄥ彲鑳藉嚭鐜�
+ * {@code /}銆亄@code :}銆佹崲琛岀瓑瀛楃 鈥斺�� 鐩存帴鎷艰繘 Content-Disposition
+ * 杞诲垯鏂囦欢鍚嶉敊涔憋紝閲嶅垯瑙﹀彂鍝嶅簲澶存敞鍏ワ紝鎵�浠ュ繀椤荤櫧鍚嶅崟鍖栨竻娲椼��
+ */
+ private String buildFilename(Chat chat, String stamp, Format format) {
+ String title = chat.getTitle() == null ? "" : chat.getTitle().trim();
+ title = title.replaceAll(ILLEGAL_FILENAME_CHARS, " ")
+ .replaceAll("\\s+", " ")
+ .trim();
+ if (title.isEmpty()) {
+ title = "瀵硅瘽" + chat.getId();
+ }
+ if (title.length() > MAX_FILENAME_CHARS) {
+ title = title.substring(0, MAX_FILENAME_CHARS);
+ }
+ return title + "_" + stamp + "." + format.extension();
+ }
+}
diff --git a/src/main/java/com/custom/webui/service/impl/ChatGroupServiceImpl.java b/src/main/java/com/custom/webui/service/impl/ChatGroupServiceImpl.java
new file mode 100644
index 0000000..a16ae94
--- /dev/null
+++ b/src/main/java/com/custom/webui/service/impl/ChatGroupServiceImpl.java
@@ -0,0 +1,157 @@
+package com.custom.webui.service.impl;
+
+import com.baomidou.mybatisplus.core.toolkit.Wrappers;
+import com.custom.webui.dto.req.ChatGroupRequest;
+import com.custom.webui.dto.resp.ChatGroupDTO;
+import com.custom.webui.entity.Chat;
+import com.custom.webui.entity.ChatGroup;
+import com.custom.webui.exception.BusinessException;
+import com.custom.webui.mapper.ChatGroupMapper;
+import com.custom.webui.mapper.ChatMapper;
+import com.custom.webui.service.ChatGroupService;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import java.time.LocalDateTime;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+
+/** 瀵硅瘽鍒嗙粍鏈嶅姟瀹炵幇銆� */
+@Slf4j
+@Service
+@RequiredArgsConstructor
+public class ChatGroupServiceImpl implements ChatGroupService {
+
+ private final ChatGroupMapper chatGroupMapper;
+ private final ChatMapper chatMapper;
+
+ @Override
+ public List<ChatGroupDTO> listByUser(Long userId) {
+ List<ChatGroup> groups = chatGroupMapper.selectList(
+ Wrappers.<ChatGroup>lambdaQuery()
+ .eq(ChatGroup::getUserId, userId)
+ .orderByAsc(ChatGroup::getId));
+ if (groups.isEmpty()) {
+ return Collections.emptyList();
+ }
+
+ // 涓�娆¤仛鍚堝嚭姣忎釜鍒嗙粍鐨勪細璇濇暟锛岄伩鍏嶉�愪釜鍒嗙粍鏌ヤ竴娆★紙N+1锛�
+ Map<Long, Long> countByGroup = chatMapper.selectList(
+ Wrappers.<Chat>lambdaQuery()
+ .select(Chat::getGroupId)
+ .eq(Chat::getUserId, userId)
+ .eq(Chat::getArchived, false)
+ .isNotNull(Chat::getGroupId))
+ .stream()
+ .collect(Collectors.groupingBy(Chat::getGroupId, Collectors.counting()));
+
+ return groups.stream().map(g -> toDto(g, countByGroup.getOrDefault(g.getId(), 0L))).toList();
+ }
+
+ @Override
+ @Transactional(rollbackFor = Exception.class)
+ public ChatGroupDTO create(Long userId, ChatGroupRequest request) {
+ String name = normalizeName(request.getName());
+ requireNameAvailable(userId, name, null);
+
+ ChatGroup group = new ChatGroup();
+ group.setUserId(userId);
+ group.setName(name);
+ group.setCreatedAt(LocalDateTime.now());
+ chatGroupMapper.insert(group);
+
+ log.info("鏂板缓瀵硅瘽鍒嗙粍 userId={} groupId={} name={}", userId, group.getId(), name);
+ return toDto(group, 0L);
+ }
+
+ @Override
+ @Transactional(rollbackFor = Exception.class)
+ public ChatGroupDTO rename(Long userId, Long groupId, ChatGroupRequest request) {
+ requireOwnedGroup(userId, groupId);
+ String name = normalizeName(request.getName());
+ requireNameAvailable(userId, name, groupId);
+
+ ChatGroup update = new ChatGroup();
+ update.setId(groupId);
+ update.setName(name);
+ chatGroupMapper.updateById(update);
+
+ Long count = chatMapper.selectCount(
+ Wrappers.<Chat>lambdaQuery()
+ .eq(Chat::getGroupId, groupId)
+ .eq(Chat::getArchived, false));
+ return toDto(chatGroupMapper.selectById(groupId), count);
+ }
+
+ @Override
+ @Transactional(rollbackFor = Exception.class)
+ public int delete(Long userId, Long groupId) {
+ requireOwnedGroup(userId, groupId);
+
+ // 鍙В闄ゅ叧鑱旓紝**涓嶅垹浼氳瘽**锛氬垹鏂囦欢澶逛笉璇ユ瘉鎺夐噷闈㈢殑涓滆タ銆�
+ // 鎶� group_id 鏄惧紡缃� NULL 鐢� UpdateWrapper 鈥斺�� 瀹炰綋鐨� null 瀛楁
+ // 浼氳 MyBatis-Plus 蹇界暐锛岃〃杈句笉浜嗐�岀疆绌恒�嶈繖涓剰鍥俱��
+ int moved = chatMapper.update(null,
+ Wrappers.<Chat>lambdaUpdate()
+ .eq(Chat::getGroupId, groupId)
+ .eq(Chat::getUserId, userId)
+ .set(Chat::getGroupId, null));
+
+ chatGroupMapper.deleteById(groupId);
+ log.info("鍒犻櫎瀵硅瘽鍒嗙粍 userId={} groupId={}锛寋} 鏉′細璇濆洖鍒版湭鍒嗙粍", userId, groupId, moved);
+ return moved;
+ }
+
+ @Override
+ public ChatGroup requireOwnedGroup(Long userId, Long groupId) {
+ if (groupId == null) {
+ throw BusinessException.badRequest("鍒嗙粍 id 涓嶈兘涓虹┖");
+ }
+ ChatGroup group = chatGroupMapper.selectById(groupId);
+ // 涓嶅瓨鍦ㄤ笌涓嶅睘浜庡綋鍓嶇敤鎴风粺涓� 404锛氳繑鍥� 403 绛変簬纭銆岃繖涓� id 瀛樺湪銆�
+ if (group == null || !group.getUserId().equals(userId)) {
+ throw BusinessException.notFound("鍒嗙粍涓嶅瓨鍦ㄦ垨鏃犳潈璁块棶");
+ }
+ return group;
+ }
+
+ // ==================== 鍐呴儴杈呭姪 ====================
+
+ private String normalizeName(String raw) {
+ String name = raw == null ? "" : raw.trim();
+ if (name.isEmpty()) {
+ throw BusinessException.badRequest("鍒嗙粍鍚嶄笉鑳戒负绌�");
+ }
+ // 鍒楀 64锛岃秴闀跨洿鎺ユ埅鏂�屼笉鏄姏鏁版嵁搴撳紓甯�
+ return name.length() > 64 ? name.substring(0, 64) : name;
+ }
+
+ /**
+ * 妫�鏌ラ噸鍚嶃��
+ *
+ * <p>鍏堟煡涓�娆℃槸涓轰簡缁欑敤鎴蜂竴鍙ャ�屽凡鏈夊悓鍚嶅垎缁勩�嶇殑浜鸿瘽鎻愮ず锛�
+ * 鏁版嵁搴撲笂鐨勫敮涓�閿粛鐒朵繚鐣欙紝鐢ㄤ簬鍏滀綇骞跺彂鎻掑叆锛堜袱涓姹傚悓鏃堕�氳繃妫�鏌ワ級銆�
+ */
+ private void requireNameAvailable(Long userId, String name, Long excludeId) {
+ ChatGroup exists = chatGroupMapper.selectOne(
+ Wrappers.<ChatGroup>lambdaQuery()
+ .eq(ChatGroup::getUserId, userId)
+ .eq(ChatGroup::getName, name)
+ .last("LIMIT 1"));
+ if (exists != null && !exists.getId().equals(excludeId)) {
+ throw BusinessException.badRequest("宸叉湁鍚屽悕鍒嗙粍锛�" + name);
+ }
+ }
+
+ private ChatGroupDTO toDto(ChatGroup group, Long chatCount) {
+ ChatGroupDTO dto = new ChatGroupDTO();
+ dto.setId(group.getId());
+ dto.setName(group.getName());
+ dto.setChatCount(chatCount == null ? 0L : chatCount);
+ return dto;
+ }
+}
diff --git a/src/main/java/com/custom/webui/util/ChatPdfWriter.java b/src/main/java/com/custom/webui/util/ChatPdfWriter.java
new file mode 100644
index 0000000..92fc646
--- /dev/null
+++ b/src/main/java/com/custom/webui/util/ChatPdfWriter.java
@@ -0,0 +1,300 @@
+package com.custom.webui.util;
+
+import org.apache.pdfbox.pdmodel.PDDocument;
+import org.apache.pdfbox.pdmodel.PDPage;
+import org.apache.pdfbox.pdmodel.PDPageContentStream;
+import org.apache.pdfbox.pdmodel.common.PDRectangle;
+import org.apache.pdfbox.pdmodel.font.PDType0Font;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * 鏋佺畝鐨� PDF 鎺掔増鍣細鎶婁竴娈垫鏂囧瓧鎸� A4 椤甸潰鎺掍笅鏉ワ紝鑷姩鎹㈣銆佽嚜鍔ㄧ炕椤点�佸甫椤电爜銆�
+ *
+ * <h2>涓轰粈涔堜笉鐢ㄧ幇鎴愮殑鎺掔増搴�</h2>
+ * openhtmltopdf / iText 杩欑被搴撻兘瑕侀澶栧紩鍏ヤ緷璧栵紝鑰屾湰椤圭洰鍙渶瑕�
+ * 銆屾爣棰� + 鍏冧俊鎭� + 鑻ュ共鏉℃秷鎭�嶈繖涓�绉嶇増寮忥紝鑷繁鐢诲弽鑰屾洿鍙帶锛�
+ * 涔熼伩鍏嶄簡涓哄鍑轰竴涓姛鑳借儗涓婂嚑 MB 鐨勪緷璧栧拰璁稿彲璇侀棶棰樸��
+ *
+ * <h2>涓変釜蹇呴』鑷繁澶勭悊鐨勭粏鑺�</h2>
+ * <ol>
+ * <li><b>瀛楀舰缂哄け</b>锛氬瓧浣撻噷娌℃湁鐨勫瓧绗︼紙emoji銆佺綍瑙佺鍙凤級鐩存帴鍐欒繘鍘讳細鎶�
+ * {@code IllegalArgumentException: No glyph for U+1F600}锛�
+ * 鏁翠釜瀵煎嚭灏卞け璐ヤ簡銆傝繖閲岀粺涓�鏇挎崲鎴� {@code 鈻 骞剁紦瀛樺垽鏂粨鏋溿��</li>
+ * <li><b>鎹㈣</b>锛氫腑鏂囨病鏈夌┖鏍硷紝涓嶈兘鎸夊崟璇嶆柇琛屻�傝繖閲屾寜**瀛楃**瀹藉害绱姞锛�
+ * 鍚屾椂瀵广�屼笉鑳藉嚭鐜板湪琛岄銆嶇殑鏍囩偣锛堬紝銆傦紒锛熺瓑锛夊仛鎮寕澶勭悊锛�
+ * 閬垮厤鍑虹幇銆屼竴琛岀粨灏惧闆堕浂涓�涓�楀彿銆嶃��</li>
+ * <li><b>椤电爜</b>锛氬唴瀹瑰啓瀹屽悗鎵嶇煡閬撴�婚〉鏁帮紝鎵�浠ラ〉鐮佺粺涓�鍦�
+ * {@link #close()} 閲岃ˉ鐢伙紙鐢� APPEND 妯″紡閲嶆柊鎵撳紑姣忎竴椤碉級銆�</li>
+ * </ol>
+ */
+public class ChatPdfWriter implements Closeable {
+
+ private static final float PAGE_WIDTH = PDRectangle.A4.getWidth();
+ private static final float PAGE_HEIGHT = PDRectangle.A4.getHeight();
+ private static final float MARGIN = 56f;
+ private static final float CONTENT_WIDTH = PAGE_WIDTH - MARGIN * 2;
+ private static final float CURSOR_TOP = PAGE_HEIGHT - MARGIN;
+ private static final float CURSOR_BOTTOM = MARGIN + 12f;
+
+ /** 涓嶅厑璁稿嚭鐜板湪琛岄鐨勬爣鐐癸紙閬垮ご灏捐鍒欙級 */
+ private static final String NO_LINE_START = "锛屻�傘�侊紱锛氾紒锛燂級銆嬨�嶃�忋�戔�︹�斅�%鈩�";
+
+ /** 缂哄瓧褰㈡椂鐨勬浛浠g */
+ private static final char REPLACEMENT = '鈻�';
+
+ private final PDDocument document;
+ private final PdfFontSupport.PdfFontHandle handle;
+ private final PDType0Font font;
+ private final List<PDPage> pages = new ArrayList<>();
+
+ /** 鐮佷綅 -> 瀛椾綋閲屾湁娌℃湁杩欎釜瀛楀舰銆傚垽瀹氳璧� cmap 鏌ヨ锛岀紦瀛樹竴涓嬬渷鏃堕棿 */
+ private final Map<Integer, Boolean> glyphCache = new HashMap<>();
+
+ private PDPageContentStream stream;
+ private float cursorY;
+ private boolean finished;
+
+ public ChatPdfWriter(PDDocument document, PdfFontSupport.PdfFontHandle handle) throws IOException {
+ this.document = document;
+ this.handle = handle;
+ this.font = handle.font();
+ newPage();
+ }
+
+ // ------------------------------------------------------------------
+ // 瀵瑰鐨勫啓鍏ユ帴鍙o紙鎸夎涔夊懡鍚嶏紝姣旈�氱敤鐨� draw(text, size) 鏇磋兘闃叉鐢ㄩ敊瀛楀彿锛�
+ // ------------------------------------------------------------------
+
+ /** 鏂囨。鏍囬 */
+ public void writeTitle(String text) throws IOException {
+ for (String line : wrap(text, 16f)) {
+ writeLine(line, 16f, 0.11f, 0.11f, 0.13f, 24f);
+ }
+ }
+
+ /** 鍏冧俊鎭锛堝鍑烘椂闂淬�佹秷鎭暟绛夛級锛屽皬瀛楃伆鑹� */
+ public void writeMeta(String text) throws IOException {
+ for (String line : wrap(text, 9f)) {
+ writeLine(line, 9f, 0.42f, 0.45f, 0.50f, 14f);
+ }
+ }
+
+ /** 娑堟伅澶达紙銆屾垜 路 2026-10-09 10:32銆嶈繖绫伙級 */
+ public void writeMessageHeader(String text) throws IOException {
+ for (String line : wrap(text, 10f)) {
+ // 涓庡墠涓�鏉℃秷鎭暀鍑洪棿璺濓紝闈犺皟鐢ㄦ柟淇濊瘉銆屽厛 spacing 鍐� header銆嶄笉绋冲Ε锛�
+ // 杩欓噷缁熶竴鍦ㄦ秷鎭ご涔嬪墠澶氱暀 8pt
+ ensureSpace(8f + 16f + 14f);
+ cursorY -= 8f;
+ writeLine(line, 10f, 0.12f, 0.35f, 0.60f, 16f);
+ }
+ }
+
+ /** 姝f枃娈佃惤锛屼繚鐣欏師鏈夋崲琛� */
+ public void writeParagraph(String text) throws IOException {
+ for (String line : wrap(text, 10.5f)) {
+ writeLine(line, 10.5f, 0.16f, 0.17f, 0.20f, 15.5f);
+ }
+ }
+
+ /** 涓�鏉″垎闅旂嚎锛堢敤浜庢爣棰樹笌姝f枃涔嬮棿锛� */
+ public void writeRule() throws IOException {
+ ensureSpace(12f);
+ stream.setNonStrokingColor(0.80f, 0.82f, 0.85f);
+ stream.addRect(MARGIN, cursorY - 4f, CONTENT_WIDTH, 0.8f);
+ stream.fill();
+ cursorY -= 12f;
+ }
+
+ /** 娈佃惤涔嬮棿鐨勭┖鐧� */
+ public void writeSpacing(float height) throws IOException {
+ ensureSpace(height);
+ cursorY -= height;
+ }
+
+ // ------------------------------------------------------------------
+ // 鍐呴儴瀹炵幇
+ // ------------------------------------------------------------------
+
+ private void writeLine(String text, float size, float r, float g, float b, float lineHeight)
+ throws IOException {
+ ensureSpace(lineHeight);
+ if (!text.isEmpty()) {
+ stream.setNonStrokingColor(r, g, b);
+ stream.beginText();
+ stream.setFont(font, size);
+ stream.newLineAtOffset(MARGIN, cursorY - size);
+ stream.showText(text);
+ stream.endText();
+ }
+ cursorY -= lineHeight;
+ }
+
+ /**
+ * 鎸夊搴︽姌琛屻��
+ *
+ * <p>鎸�**瀛楃**鑰屼笉鏄崟璇嶆柇琛岋細涓枃娌℃湁璇嶉棿绌烘牸锛屾寜鍗曡瘝鏂細寰楀埌涓�鏁存涓嶆柇琛岀殑鏂囨湰銆�
+ * 鍚屾椂鍋氫袱浠跺皬浜嬶細
+ * <ul>
+ * <li>鍘熷鏂囨湰閲岀殑鎹㈣/tab 寰楀埌淇濈暀锛坱ab 灞曞紑鎴� 4 涓┖鏍硷級</li>
+ * <li>涓嶈銆岋紝銆傦紒锛熴�嶈繖绫绘爣鐐瑰嚭鐜板湪琛岄</li>
+ * </ul>
+ */
+ private List<String> wrap(String raw, float size) {
+ List<String> lines = new ArrayList<>();
+ if (raw == null || raw.isEmpty()) {
+ lines.add("");
+ return lines;
+ }
+
+ for (String paragraph : sanitize(raw).split("\n", -1)) {
+ if (paragraph.isEmpty()) {
+ lines.add("");
+ continue;
+ }
+ StringBuilder current = new StringBuilder();
+ float width = 0f;
+
+ int i = 0;
+ while (i < paragraph.length()) {
+ int cp = paragraph.codePointAt(i);
+ String ch = new String(Character.toChars(cp));
+ float chWidth = widthOf(ch, size);
+
+ boolean overflow = width + chWidth > CONTENT_WIDTH && current.length() > 0;
+ // 閬垮ご灏撅細涓嶅洜涓烘爣鐐硅�屾柇琛岋紝瀹佸彲璁╁畠绋嶅井鍑虹晫锛堟偓鎸傛爣鐐癸級
+ boolean isNoStart = ch.length() == 1 && NO_LINE_START.indexOf(ch.charAt(0)) >= 0;
+
+ if (overflow && !isNoStart) {
+ lines.add(current.toString());
+ current.setLength(0);
+ width = 0f;
+ }
+ current.append(ch);
+ width += chWidth;
+ i += Character.charCount(cp);
+ }
+ lines.add(current.toString());
+ }
+ return lines;
+ }
+
+ private float widthOf(String text, float size) {
+ try {
+ return font.getStringWidth(text) / 1000f * size;
+ } catch (IOException e) {
+ return size; // 浼扮畻鍗冲彲锛屼笉璇ュ洜涓烘祴閲忓け璐ヨ�屼腑鏂鍑�
+ }
+ }
+
+ /**
+ * 娓呮礂鏂囨湰锛氭帶鍒跺瓧绗︺�乼ab銆佷互鍙�**瀛椾綋閲屾病鏈夌殑瀛楃**銆�
+ *
+ * <p>瀛椾綋缂哄瓧褰㈣繖涓�鐐规槸蹇呴』澶勭悊鐨勶細Arial Unicode 杩欑被瀛椾綋瑕嗙洊浜嗕腑鏃ラ煩锛�
+ * 浣嗕笉鍚� emoji锛圲+1F600 绛夛級銆侾DFBox 閬囧埌缂哄瓧褰細鎶涘紓甯革紝
+ * 琛ㄧ幇灏辨槸銆屽璇濋噷鏈夎〃鎯呯鍙凤紝鏁翠釜 PDF 瀵煎嚭灏卞け璐ャ�嶁�斺��
+ * 涓�涓� emoji 姣佹帀鏁翠唤瀵煎嚭锛屾樉鐒朵笉鍙帴鍙楋紝鎵�浠ユ浛鎹㈡垚鏂规缁х画瀵笺��
+ *
+ * <p>瀛楀舰鍒ゆ柇璧板瓧浣撳彞鏌勭殑 cmap 鏌ヨ锛�**涓嶈兘**鐢�
+ * {@code PDType0Font.hasGlyph()}锛氬疄娴嬪畠瀵规湰璇ュ瓨鍦ㄧ殑鍏ㄨ閫楀彿涔熶細杩斿洖
+ * false锛岄偅鏍蜂腑鏂囨爣鐐逛細琚暣鐗囨浛鎹㈡垚鏂规锛堣瑙� {@link PdfFontSupport}锛夈��
+ */
+ private String sanitize(String raw) {
+ StringBuilder sb = new StringBuilder(raw.length() + 16);
+ int i = 0;
+ while (i < raw.length()) {
+ int cp = raw.codePointAt(i);
+ i += Character.charCount(cp);
+
+ if (cp == '\r') {
+ continue;
+ }
+ if (cp == '\t') {
+ sb.append(" ");
+ continue;
+ }
+ if (cp != '\n' && Character.isISOControl(cp)) {
+ continue;
+ }
+ if (cp == '\n' || hasGlyph(cp)) {
+ sb.appendCodePoint(cp);
+ } else {
+ sb.append(REPLACEMENT);
+ }
+ }
+ return sb.toString();
+ }
+
+ private boolean hasGlyph(int codePoint) {
+ Boolean cached = glyphCache.get(codePoint);
+ if (cached != null) {
+ return cached;
+ }
+ boolean has = handle.hasGlyph(codePoint);
+ glyphCache.put(codePoint, has);
+ return has;
+ }
+
+ private void ensureSpace(float needed) throws IOException {
+ if (cursorY - needed < CURSOR_BOTTOM) {
+ newPage();
+ }
+ }
+
+ private void newPage() throws IOException {
+ if (stream != null) {
+ stream.close();
+ }
+ PDPage page = new PDPage(PDRectangle.A4);
+ document.addPage(page);
+ pages.add(page);
+
+ // compress=true 璁╁唴瀹规祦璧� Flate 鍘嬬缉锛況esetContext=true 淇濊瘉姣忛〉鍥惧舰鐘舵�佺嫭绔�
+ stream = new PDPageContentStream(document, page,
+ PDPageContentStream.AppendMode.APPEND, true, true);
+ cursorY = CURSOR_TOP;
+ }
+
+ @Override
+ public void close() throws IOException {
+ if (finished) {
+ return;
+ }
+ finished = true;
+ if (stream != null) {
+ stream.close();
+ stream = null;
+ }
+ writeFooters();
+ }
+
+ /**
+ * 琛ョ敾椤电爜銆�
+ *
+ * <p>蹇呴』鍦ㄥ叏閮ㄥ唴瀹瑰啓瀹屼箣鍚庡仛锛氶〉鐮佽钀藉湪銆岀 N 椤� / 鍏� M 椤点�嶄笂锛�
+ * 鑰� M 鍙湁鍐欏埌鏈�鍚庢墠鐭ラ亾銆傜敤 APPEND 妯″紡閲嶆柊鎵撳紑姣忎竴椤电殑鍐呭娴佸嵆鍙��
+ */
+ private void writeFooters() throws IOException {
+ int total = pages.size();
+ for (int index = 0; index < total; index++) {
+ String text = "绗� " + (index + 1) + " 椤� / 鍏� " + total + " 椤�";
+ float size = 8f;
+ float width = widthOf(text, size);
+ try (PDPageContentStream footer = new PDPageContentStream(
+ document, pages.get(index), PDPageContentStream.AppendMode.APPEND, true, true)) {
+ footer.setNonStrokingColor(0.62f, 0.65f, 0.70f);
+ footer.beginText();
+ footer.setFont(font, size);
+ footer.newLineAtOffset((PAGE_WIDTH - width) / 2f, MARGIN / 2f);
+ footer.showText(text);
+ footer.endText();
+ }
+ }
+ }
+}
diff --git a/src/main/java/com/custom/webui/util/PdfFontSupport.java b/src/main/java/com/custom/webui/util/PdfFontSupport.java
new file mode 100644
index 0000000..bd6adf2
--- /dev/null
+++ b/src/main/java/com/custom/webui/util/PdfFontSupport.java
@@ -0,0 +1,327 @@
+package com.custom.webui.util;
+
+import com.custom.webui.config.props.ExportProperties;
+import com.custom.webui.exception.BusinessException;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.fontbox.ttf.CmapLookup;
+import org.apache.fontbox.ttf.TTFParser;
+import org.apache.fontbox.ttf.TrueTypeCollection;
+import org.apache.fontbox.ttf.TrueTypeFont;
+import org.apache.pdfbox.io.RandomAccessReadBufferedFile;
+import org.apache.pdfbox.pdmodel.PDDocument;
+import org.apache.pdfbox.pdmodel.font.PDType0Font;
+import org.springframework.stereotype.Component;
+
+import java.io.Closeable;
+import java.io.File;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * 涓� PDF 瀵煎嚭鍑嗗涓�浠�**鑳藉啓涓枃**鐨勫瓧浣撱��
+ *
+ * <h2>涓轰粈涔堝繀椤诲祵鍏ュ瓧浣�</h2>
+ * PDF 鍐呯疆鐨� 14 涓爣鍑嗗瓧浣擄紙Helvetica / Times 绛夛級鍙鐩� Latin-1锛�
+ * 鍐欎腑鏂囦細鐩存帴鎶� {@code IllegalArgumentException: No glyph for U+4E2D}銆�
+ * 鑰屻�屽紩鐢ㄧ郴缁熼噷鐨� CJK 鏍囧噯瀛椾綋銆嶏紙STSong-Light + UniGB-UCS2-H锛夎櫧鐒剁渷浜嬶紝
+ * 浣嗛槄璇诲櫒涓嶄竴瀹氳浜嗗搴斿瓧浣� 鈥斺�� 鐢ㄦ埛鎷垮埌鐨勬槸涓�涓墦寮�灏辩┖鐧芥垨涔辩爜鐨勬枃浠讹紝
+ * 鑰屽鍑烘枃浠跺線寰�灏辨槸鐢ㄦ潵闀挎湡淇濆瓨鍜屽彂缁欏埆浜虹殑锛屼笉鑳借祵瀵规柟鐨勭幆澧冦��
+ * 鎵�浠ヨ繖閲屼粠绯荤粺閲屾壘涓�浠界湡瀹炵殑涓枃瀛椾綋锛�**鎸夊瓙闆嗗祵鍏�**锛堝彧甯︾敤鍒扮殑瀛楀舰锛�
+ * 涓�涓嚑鐧惧瓧鐨勪腑鏂囧璇濇渶缁� PDF 閫氬父鍙湁鍑犲崄 KB锛夈��
+ *
+ * <h2>涓轰粈涔堢敤 cmap 鍒ゆ柇瀛楀舰锛岃�屼笉鏄� PDType0Font.hasGlyph()</h2>
+ * 杩欐槸瀹炴祴韪╁埌鐨勫潙锛歿@code PDType0Font.hasGlyph('锛�')} 瀵� Arial Unicode 杩斿洖
+ * <b>false</b>锛岃�屽悓涓�浠藉瓧浣撶殑 cmap 閲� U+FF0C 鏄庢槑鏈夊瓧褰紙glyphId=6632锛夈��
+ * 濡傛灉淇′簡瀹冿紝浼氭湁涓や釜鍚庢灉锛�
+ * <ol>
+ * <li>瀛椾綋閫夋嫨闃舵浼氭妸 Arial Unicode 璇垽鎴愩�屼笉鍚腑鏂囥�嶈�岃烦杩囷紱</li>
+ * <li>鏂囨湰娓呮礂闃舵浼氭妸姣忎釜鍏ㄨ閫楀彿閮芥浛鎹㈡垚鏂规 鈥斺�� 涓枃鍥炵瓟閲屾弧鍦� 鈻°��</li>
+ * </ol>
+ * 鍥犳杩欓噷缁熶竴鐢� fontbox 鐨� {@link CmapLookup#getGlyphId(int)}
+ * 锛堣繑鍥� 0 鎵嶄唬琛ㄧ湡鐨勬病鏈夎繖涓瓧褰級銆�
+ */
+@Slf4j
+@Component
+@RequiredArgsConstructor
+public class PdfFontSupport {
+
+ /**
+ * 鍏滃簳鍊欓�夊瓧浣擄紝鎸夐『搴忔帰娴嬨��
+ *
+ * <p>鍙斁**鍗曚綋**瀛椾綋鏂囦欢锛�.ttf / .otf锛変笌甯歌鐨勫瓧浣撻泦鍚堬紙.ttc锛夛細
+ * .ttc 浼氱敱 {@link TrueTypeCollection} 閫愪釜鎸戝嚭鍚腑鏂囧瓧褰㈢殑閭d竴娆俱��
+ */
+ private static final List<String> CANDIDATES = List.of(
+ // macOS
+ "/System/Library/Fonts/Supplemental/Arial Unicode.ttf",
+ "/Library/Fonts/Arial Unicode.ttf",
+ "/System/Library/Fonts/Supplemental/Songti.ttc",
+ "/System/Library/Fonts/PingFang.ttc",
+ "/System/Library/Fonts/Hiragino Sans GB.ttc",
+ // Linux
+ "/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc",
+ "/usr/share/fonts/truetype/noto/NotoSansCJK-Regular.ttc",
+ "/usr/share/fonts/opentype/noto/NotoSerifCJK-Regular.ttc",
+ "/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc",
+ "/usr/share/fonts/truetype/arphic/uming.ttc",
+ "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
+ // Windows
+ "C:/Windows/Fonts/msyh.ttc",
+ "C:/Windows/Fonts/msyh.ttf",
+ "C:/Windows/Fonts/simsun.ttc",
+ "C:/Windows/Fonts/simhei.ttf"
+ );
+
+ /** 鐢ㄦ潵鍒ゆ柇銆岃繖浠藉瓧浣撳埌搴曡涓嶈璇嗕腑鏂囥�嶇殑鎺㈤拡瀛楃 */
+ private static final int[] CJK_PROBE = {'涓�', '鏂�', '锛�', '銆�'};
+
+ private final ExportProperties properties;
+
+ private volatile File cachedFont;
+ private volatile boolean probed;
+
+ /**
+ * 涓虹粰瀹氭枃妗f墦寮�瀛椾綋銆�
+ *
+ * @throws BusinessException 鎵句笉鍒板彲鐢ㄥ瓧浣撴椂鎶涘嚭锛宮essage 閲屽甫鍏蜂綋閰嶇疆鏂规硶
+ */
+ public PdfFontHandle open(PDDocument document) {
+ File file = resolveFontFile();
+ if (file == null) {
+ throw BusinessException.serverError(
+ "瀵煎嚭 PDF 闇�瑕佷竴浠戒腑鏂囧瓧浣擄紝浣嗙郴缁熼噷娌℃湁鎺㈡祴鍒板彲鐢ㄧ殑銆�"
+ + "璇峰湪閰嶇疆閲屾樉寮忔寚瀹氾細webui.export.pdf-font-path=/path/to/涓枃瀛椾綋.ttf"
+ + "锛圱XT / JSON 瀵煎嚭涓嶅彈褰卞搷锛�");
+ }
+
+ try {
+ if (isCollection(file)) {
+ TrueTypeCollection collection = new TrueTypeCollection(file);
+ TrueTypeFont picked = pickFace(collection);
+ if (picked == null) {
+ closeQuietly(collection);
+ throw BusinessException.serverError("瀛椾綋 " + file
+ + " 閲屾病鏈夋壘鍒板寘鍚腑鏂囧瓧褰㈢殑瀛椾綋锛岃鏀归厤 webui.export.pdf-font-path");
+ }
+ return new PdfFontHandle(PDType0Font.load(document, picked, true),
+ new Closeable[]{collection}, picked.getUnicodeCmapLookup());
+ }
+
+ RandomAccessReadBufferedFile raf = new RandomAccessReadBufferedFile(file);
+ TrueTypeFont ttf = new TTFParser().parse(raf);
+ CmapLookup lookup = ttf.getUnicodeCmapLookup();
+ if (lookup == null || !knowsChinese(lookup)) {
+ closeQuietly(ttf);
+ closeQuietly(raf);
+ throw BusinessException.serverError("瀛椾綋 " + file
+ + " 涓嶅惈涓枃瀛楀舰锛岃鏀归厤 webui.export.pdf-font-path");
+ }
+ // 娉ㄦ剰锛氬瓙闆嗗寲鍙戠敓鍦� save() 闃舵锛屾墍浠� ttf / raf 蹇呴』娲诲埌閭f椂锛�
+ // 鐢� handle 缁熶竴鍏抽棴锛堣 PdfFontHandle 鐨勮鏄庯級
+ return new PdfFontHandle(PDType0Font.load(document, ttf, true),
+ new Closeable[]{ttf, raf}, lookup);
+ } catch (BusinessException e) {
+ throw e;
+ } catch (IOException e) {
+ throw BusinessException.serverError("鍔犺浇 PDF 瀛椾綋澶辫触锛�" + file + " 鈥斺�� " + e.getMessage());
+ }
+ }
+
+ /** 渚涘惎鍔ㄨ嚜妫�灞曠ず */
+ public String describe() {
+ File file = resolveFontFile();
+ if (file == null) {
+ return "鏈壘鍒颁腑鏂囧瓧浣� 鈥斺�� PDF 瀵煎嚭涓嶅彲鐢紙TXT / JSON 浠嶅彲鐢級銆�"
+ + "鍙厤缃� webui.export.pdf-font-path 鎸囧畾瀛椾綋鏂囦欢";
+ }
+ return "宸插氨缁細" + file;
+ }
+
+ // ------------------------------------------------------------------
+ // 瀛椾綋鎺㈡祴
+ // ------------------------------------------------------------------
+
+ private File resolveFontFile() {
+ if (probed) {
+ return cachedFont;
+ }
+ synchronized (this) {
+ if (probed) {
+ return cachedFont;
+ }
+
+ List<String> paths = new ArrayList<>();
+ if (properties.getPdfFontPath() != null && !properties.getPdfFontPath().isBlank()) {
+ // 鏄惧紡閰嶇疆浼樺厛锛屼笖**鍙�**鐢ㄥ畠锛氱敤鎴锋寚瀹氫簡瀛椾綋鍗撮潤榛樺洖閫�鍒板埆鐨勫瓧浣擄紝
+ // 浼氳浜轰互涓洪厤缃病鐢熸晥锛堟湰椤圭洰宸茬粡韪╄繃濂藉嚑娆°�岄厤缃闈欓粯蹇界暐銆嶇殑鍧戯級
+ paths.add(properties.getPdfFontPath().trim());
+ } else {
+ paths.addAll(CANDIDATES);
+ }
+
+ for (String path : paths) {
+ File file = new File(path);
+ if (!file.isFile() || file.length() == 0) {
+ continue;
+ }
+ if (recognizesChinese(file)) {
+ log.info("PDF 瀵煎嚭灏嗕娇鐢ㄤ腑鏂囧瓧浣�: {}", file);
+ cachedFont = file;
+ probed = true;
+ return cachedFont;
+ }
+ log.debug("瀛椾綋 {} 瀛樺湪浣嗕笉鍚腑鏂囧瓧褰紝璺宠繃", file);
+ }
+
+ log.warn("鏈壘鍒板彲鐢ㄤ簬 PDF 瀵煎嚭鐨勪腑鏂囧瓧浣擄紝PDF 瀵煎嚭灏嗕笉鍙敤锛圱XT/JSON 涓嶅彈褰卞搷锛�");
+ probed = true;
+ return null;
+ }
+ }
+
+ /**
+ * 浠庡瓧浣撻泦鍚堥噷鎸戜竴娆俱��
+ *
+ * <p>涓よ疆锛氬厛鎵惧悕瀛楅噷甯� Regular 鐨勶紙瀛椾綋闆嗗悎鐨勭涓�涓� face 寰�寰�鏄� Black / Bold
+ * 涔嬬被鐨勯噸瀛楅噸锛屽鍑虹殑姝f枃浼氱矖寰楁病娉曠湅锛夛紝鎵句笉鍒板啀閫�鍥炵涓�涓惈涓枃瀛楀舰鐨勩��
+ */
+ private TrueTypeFont pickFace(TrueTypeCollection collection) throws IOException {
+ List<TrueTypeFont> faces = new ArrayList<>();
+ collection.processAllFonts(faces::add);
+ if (faces.isEmpty()) {
+ return null;
+ }
+
+ TrueTypeFont regular = null;
+ TrueTypeFont fallback = null;
+ for (TrueTypeFont face : faces) {
+ CmapLookup lookup = face.getUnicodeCmapLookup();
+ if (lookup == null || !knowsChinese(lookup)) {
+ continue;
+ }
+ if (fallback == null) {
+ fallback = face;
+ }
+ String name = face.getName();
+ if (name != null) {
+ String lower = name.toLowerCase();
+ if (lower.contains("regular") || lower.contains("light")) {
+ regular = face;
+ break;
+ }
+ }
+ }
+ return regular != null ? regular : fallback;
+ }
+
+ private boolean recognizesChinese(File file) {
+ try {
+ if (isCollection(file)) {
+ try (TrueTypeCollection collection = new TrueTypeCollection(file)) {
+ return pickFace(collection) != null;
+ }
+ }
+ try (RandomAccessReadBufferedFile raf = new RandomAccessReadBufferedFile(file)) {
+ TrueTypeFont ttf = new TTFParser().parse(raf);
+ try {
+ CmapLookup lookup = ttf.getUnicodeCmapLookup();
+ return lookup != null && knowsChinese(lookup);
+ } finally {
+ closeQuietly(ttf);
+ }
+ }
+ } catch (Exception e) {
+ log.debug("瀛椾綋鎺㈡祴澶辫触 {}: {}", file, e.getMessage());
+ return false;
+ }
+ }
+
+ /** glyphId 涓� 0 琛ㄧず .notdef锛屽嵆杩欎唤瀛椾綋纭疄娌℃湁璇ュ瓧褰� */
+ private boolean knowsChinese(CmapLookup lookup) {
+ try {
+ for (int cp : CJK_PROBE) {
+ if (lookup.getGlyphId(cp) == 0) {
+ return false;
+ }
+ }
+ return true;
+ } catch (Exception e) {
+ return false;
+ }
+ }
+
+ private boolean isCollection(File file) {
+ return file.getName().toLowerCase().endsWith(".ttc");
+ }
+
+ private void closeQuietly(Closeable closeable) {
+ try {
+ closeable.close();
+ } catch (Exception ignored) {
+ // 鍏抽棴澶辫触涓嶅奖鍝嶄富娴佺▼
+ }
+ }
+
+ /**
+ * 瀛椾綋鍙ユ焺锛氱粰鍑虹粯鍥剧敤鐨� {@code PDType0Font}锛屽悓鏃舵妸**搴曞眰瀛椾綋璧勬簮**
+ * 涓�**瀛楀舰鍒ゆ柇鑳藉姏**涓�璧峰甫鍑烘潵銆�
+ *
+ * <p>涓夋牱涓滆タ缂轰竴涓嶅彲锛屾墍浠ョ粦鍦ㄤ竴涓彞鏌勯噷锛�
+ * <ul>
+ * <li>{@code font} 鈥斺�� 鐪熸寰� PDF 閲屽啓瀛楃殑瀵硅薄</li>
+ * <li>搴曢儴璧勬簮 鈥斺�� 鐢� {@code embedSubset=true} 鍔犺浇鏃讹紝PDFBox 鏄�
+ * <b>寤惰繜鍒� {@code save()}</b> 鎵嶅幓璇诲瓧浣撴枃浠惰瀛愰泦鐨勶紱
+ * 鑻ュ湪姝や箣鍓嶅叧闂簡鏂囦欢鍙ユ焺锛屼繚瀛樻椂浼氭姤銆孴TF is closed銆�
+ * 杩欑涓庡鍑哄唴瀹规涓嶇浉骞茬殑閿欒</li>
+ * <li>{@code cmap} 鈥斺�� 鍒ゆ柇鏌愪釜瀛楃鏈夋病鏈夊瓧褰紙鐢ㄦ潵鎶� emoji 涔嬬被鐨�
+ * 缂哄瓧褰㈠瓧绗︽浛鎹㈡帀锛屽惁鍒欎竴涓〃鎯呯鍙峰氨鑳借鏁翠唤瀵煎嚭澶辫触锛�</li>
+ * </ul>
+ *
+ * <p>鐢ㄦ硶鍥哄畾涓猴細
+ * <pre>
+ * try (var handle = fontSupport.open(doc)) {
+ * ... 鍐欏唴瀹� ...
+ * doc.save(out); // 瀛愰泦鍖栧彂鐢熷湪杩欓噷锛屾鏃跺瓧浣撳繀椤昏繕娲荤潃
+ * }
+ * </pre>
+ */
+ public static final class PdfFontHandle implements Closeable {
+
+ private final PDType0Font font;
+ private final Closeable[] resources;
+ private final CmapLookup cmap;
+
+ PdfFontHandle(PDType0Font font, Closeable[] resources, CmapLookup cmap) {
+ this.font = font;
+ this.resources = resources;
+ this.cmap = cmap;
+ }
+
+ public PDType0Font font() {
+ return font;
+ }
+
+ /** 璇ョ爜浣嶅湪杩欎唤瀛椾綋閲屾槸鍚︽湁瀛楀舰锛坒alse 鏃跺簲鏇挎崲鎴愬崰浣嶇锛� */
+ public boolean hasGlyph(int codePoint) {
+ if (cmap == null) {
+ // 鎷夸笉鍒� cmap 鏃朵繚瀹堝湴璁や负銆屾湁銆嶏紝浜ょ粰 PDFBox 鍘绘姤閿欙紝
+ // 涔熷ソ杩囨妸姝e父鏂囧瓧澶ч噺鏇挎崲鎴愭柟妗�
+ return true;
+ }
+ try {
+ return cmap.getGlyphId(codePoint) != 0;
+ } catch (Exception e) {
+ return true;
+ }
+ }
+
+ @Override
+ public void close() throws IOException {
+ for (Closeable resource : resources) {
+ resource.close();
+ }
+ }
+ }
+}
--
Gitblit v1.9.1