Commit 257c8d2d authored by wujipeng's avatar wujipeng
Browse files

优化

parent 0562fc83
...@@ -9,11 +9,13 @@ import com.platform.business.model.vo.StudentCertificationScopeVO; ...@@ -9,11 +9,13 @@ import com.platform.business.model.vo.StudentCertificationScopeVO;
import com.platform.business.model.vo.StudentCertificationTreeVO; import com.platform.business.model.vo.StudentCertificationTreeVO;
import com.platform.business.service.StudentCertificationAdminService; import com.platform.business.service.StudentCertificationAdminService;
import com.platform.exception.BusinessException; import com.platform.exception.BusinessException;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import javax.annotation.Resource; import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.URLEncoder; import java.net.URLEncoder;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
...@@ -25,19 +27,25 @@ import java.util.LinkedHashSet; ...@@ -25,19 +27,25 @@ import java.util.LinkedHashSet;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry; import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream; import java.util.zip.ZipOutputStream;
/** /**
* 管理端学员认证实现。 * 管理端学员认证实现。
* *
* <p>B2文件使用Word/WPS均原生支持的RTF格式生成,并继续沿用历史接口的 {@code .doc} * <p>B2文件沿用教师J2档案的稳定方案:资源目录保存由原始DOC无损另存得到的RTF模板,
* 扩展名。原Word 97-2003模板包含POI无法完整保留的OfficeArt记录,使用HWPF重写后虽然 * 运行时只替换指定表格单元格内的可见文字,不让POI重建旧版DOC的OfficeArt结构。
* 文件容器仍然存在,但正文会在WPS中显示为空;直接生成RTF可以从根本上避免该兼容问题。</p> * 下载扩展名仍为Word/WPS兼容的 {@code .doc},同时保留原报名表的行高、边框和合并单元格。</p>
*/ */
@Service @Service
public class StudentCertificationAdminServiceImpl implements StudentCertificationAdminService { public class StudentCertificationAdminServiceImpl implements StudentCertificationAdminService {
private static final String TEMPLATE =
"templates/certification/B2-student-training-assessment-registration.rtf";
private static final int MAX_EXPORT = 500; private static final int MAX_EXPORT = 500;
private static final Pattern ROW_END_PATTERN = Pattern.compile("\\\\row(?![a-zA-Z])");
private static final Pattern CELL_END_PATTERN = Pattern.compile("\\\\cell(?![a-zA-Z])");
@Resource private StudentCertificationMapper mapper; @Resource private StudentCertificationMapper mapper;
@Override @Override
...@@ -125,127 +133,316 @@ public class StudentCertificationAdminServiceImpl implements StudentCertificatio ...@@ -125,127 +133,316 @@ public class StudentCertificationAdminServiceImpl implements StudentCertificatio
} }
/** /**
* 生成可由Microsoft Word和WPS直接打开的RTF报名表。 * 使用原版式RTF模板生成B2报名表。
* *
* <p>这里不再通过HWPF修改旧版二进制DOC模板。该模板含有损坏或非标准的OfficeArt、 * <p>与教师J2导出一致,这里不重新创建表格,也不让HWPF重写二进制DOC;只在已经确认的
* 段落格式记录,POI写出时会静默丢弃这些记录,最终造成下载文件正文为空。RTF是文本型 * 行列坐标内清除示例值并插入业务数据。这样生成文件虽然沿用 {@code .doc} 扩展名,
* Word格式,不依赖OfficeArt,且能够稳定表达中文、表格、边框和勾选项。</p> * 其内容是Word/WPS原生支持的RTF,能够同时避免“导出为空”和“模板样式变化”。</p>
*/ */
byte[] createDocument(StudentCertificationProfileVO p) { byte[] createDocument(StudentCertificationProfileVO profile) {
StringBuilder rtf = new StringBuilder(8192); try (InputStream input = new ClassPathResource(TEMPLATE).getInputStream()) {
// A4纵向页面,正文使用宋体;RTF统一转义为ASCII,避免服务器默认编码影响中文。 String template = new String(readAllBytes(input), StandardCharsets.ISO_8859_1);
rtf.append("{\\rtf1\\ansi\\ansicpg936\\deff0") List<RtfRow> rows = parseRows(template);
.append("{\\fonttbl{\\f0\\fnil\\fcharset134 SimSun;}}") validateTemplate(template, rows);
.append("\\paperw11906\\paperh16838\\margl720\\margr720\\margt720\\margb720")
.append("\\viewkind4\\uc1\\f0\\fs20 "); List<RtfEdit> edits = new ArrayList<>();
appendParagraph(rtf, "B2 学员培训鉴定报名表", true, 32); addBasicInformationEdits(edits, rows, profile);
appendFieldRow(rtf, "填表日期", formatDate(p.getSubmitTime()), "班级编号", string(p.getClassId())); addTrainingInformationEdits(edits, rows, profile);
String result = applyEdits(template, edits);
appendSection(rtf, "基本信息"); validateFilledResult(result, profile);
appendFieldRow(rtf, "姓名", p.getName(), "性别", p.getGender()); return result.getBytes(StandardCharsets.ISO_8859_1);
appendFieldRow(rtf, "出生日期", p.getBirthday(), "户口性质", p.getHouseholdType()); } catch (BusinessException e) {
appendFieldRow(rtf, "证件类型", p.getIdType(), "证件号码", p.getIdCard()); throw e;
appendFieldRow(rtf, "最高学历", p.getHighestEducation(), "所学专业", p.getMajor()); } catch (Exception e) {
appendFieldRow(rtf, "行政区", p.getAdministrativeDistrict(), "人员类别", personTypes(p)); throw new BusinessException("生成B2学员培训鉴定报名表失败");
appendFieldRow(rtf, "联系地址", p.getHomeAddress(), "邮编", p.getZipCode()); }
appendFieldRow(rtf, "劳动手册编号", p.getLaborBookNo(), "联系电话", p.getPhoneNumber()); }
appendSection(rtf, "工作信息"); private byte[] readAllBytes(InputStream input) throws java.io.IOException {
appendFieldRow(rtf, "工作单位", p.getWorkUnit(), "单位联系电话", p.getUnitPhone()); ByteArrayOutputStream output = new ByteArrayOutputStream();
appendFieldRow(rtf, "单位地址", p.getWorkUnitAddress(), "社保缴费年限", years(p.getSocialSecurityYears())); byte[] buffer = new byte[8192];
appendFieldRow(rtf, "本工种工作年限", years(p.getCurrentWorkYears()), "相关职业年限", years(p.getJobYears())); int length;
while ((length = input.read(buffer)) >= 0) output.write(buffer, 0, length);
appendSection(rtf, "原职业与教育背景"); return output.toByteArray();
appendFieldRow(rtf, "原职业(工种)", p.getPreviousOccupation(), "原职业等级", p.getPreviousLevel()); }
appendFieldRow(rtf, "原职业证书编号", p.getPreviousCertNo(), "上一等级证书编号", p.getPreviousLevelCertNo());
appendFieldRow(rtf, "发证日期", p.getPreviousIssueDate(), "发证部门", p.getPreviousIssueDept()); /** RTF的真实行结束符是唯一稳定边界,不能按换行符或\trowd直接切分复杂合并表格。 */
appendFieldRow(rtf, "毕业院校", p.getGraduationSchool(), "毕业日期", p.getGraduationDate()); private List<RtfRow> parseRows(String rtf) {
appendFieldRow(rtf, "毕业证书编号", p.getGraduationCertNo(), "", ""); List<RtfRow> rows = new ArrayList<>();
Matcher rowMatcher = ROW_END_PATTERN.matcher(rtf);
appendSection(rtf, "培训信息"); int rowStart = 0;
appendFieldRow(rtf, "培训职业(工种)", p.getTrainingOccupation(), "培训等级", p.getTrainingLevel()); while (rowMatcher.find()) {
appendFieldRow(rtf, "培训类别", options(p.getTrainingCategory(), "政府补贴培训", "企业培训", "院校培训"), List<Integer> cellEnds = new ArrayList<>();
"申请培训补贴", Boolean.TRUE.equals(p.getSubsidyFlag()) ? "是" : "否"); Matcher cellMatcher = CELL_END_PATTERN.matcher(rtf);
cellMatcher.region(rowStart, rowMatcher.start());
appendSection(rtf, "鉴定信息"); while (cellMatcher.find()) cellEnds.add(cellMatcher.start());
appendFieldRow(rtf, "鉴定职业(工种)", p.getAssessmentOccupation(), "鉴定等级", p.getAssessmentLevel()); rows.add(new RtfRow(rowStart, cellEnds));
appendParagraph(rtf, "本人承诺以上信息及提交材料真实、准确,并遵守职业技能鉴定相关规定。", false, 20); rowStart = rowMatcher.end();
appendParagraph(rtf, "申请人(签字):________________ 日期:____年__月__日", false, 20); }
rtf.append('}'); return rows;
return rtf.toString().getBytes(StandardCharsets.US_ASCII); }
}
/** 模板结构变化时立即失败,避免姓名、身份证等字段被写入错误单元格。 */
/** 写入普通段落;所有动态内容统一经过RTF转义,防止花括号或反斜杠破坏文档结构。 */ private void validateTemplate(String template, List<RtfRow> rows) {
private void appendParagraph(StringBuilder rtf, String text, boolean centered, int fontSize) { int[] expectedCells = {15, 9, 8, 8, 18, 10, 10, 5, 5, 5, 5, 7, 8, 3, 3, 8,
rtf.append("\\pard").append(centered ? "\\qc" : "\\ql") 8, 6, 9, 3, 8, 8, 2, 2, 2, 2, 2, 19, 16, 1, 1, 1, 1};
.append("\\sa120\\fs").append(fontSize).append(' ') if (!template.startsWith("{\\rtf1") || rows.size() != expectedCells.length) {
.append(rtfText(text)).append("\\par "); throw new BusinessException("B2模板结构已变化,请重新确认字段映射");
} }
for (int i = 0; i < expectedCells.length; i++) {
/** 分区标题单独成行,便于打印时快速区分报名表的资料模块。 */ if (rows.get(i).cellEnds.size() != expectedCells[i]) {
private void appendSection(StringBuilder rtf, String title) { throw new BusinessException("B2模板第" + (i + 1) + "行结构已变化,请重新确认字段映射");
rtf.append("\\pard\\sb100\\sa50\\b\\fs22 ").append(rtfText(title)).append("\\b0\\par "); }
}
}
private void addBasicInformationEdits(List<RtfEdit> edits, List<RtfRow> rows,
StudentCertificationProfileVO profile) {
putSubmitDate(edits, rows, profile.getSubmitTime());
put(edits, rows, 0, 14, profile.getClassId(), true);
put(edits, rows, 1, 2, profile.getName(), true);
put(edits, rows, 1, 4, profile.getBirthday(), true);
put(edits, rows, 2, 2, profile.getGender(), true);
// 户口性质、人员类别位于标签的下一行,未选项必须清空模板原有空格或示例勾。
markOne(edits, rows, 3, 4, 6, normalizeHouseholdType(profile.getHouseholdType()),
"本市非农", "本市农", "外地");
putIdCard(edits, rows, profile.getIdCard());
put(edits, rows, 5, 2, profile.getHighestEducation(), true);
markMany(edits, rows, 6, 4, 8, profile.getPersonTypes(),
"失业", "协保", "农村富余劳动力", "在职", "其他");
put(edits, rows, 7, 2, profile.getHomeAddress(), true);
put(edits, rows, 7, 4, profile.getZipCode(), true);
put(edits, rows, 8, 2, profile.getAdministrativeDistrict(), true);
put(edits, rows, 8, 4, profile.getPhoneNumber(), true);
put(edits, rows, 9, 2, profile.getWorkUnit(), true);
put(edits, rows, 9, 4, profile.getUnitPhone(), true);
put(edits, rows, 10, 2, profile.getWorkUnitAddress(), true);
put(edits, rows, 11, 2, profile.getPreviousOccupation(), true);
put(edits, rows, 11, 4, profile.getPreviousLevel(), true);
put(edits, rows, 11, 6, profile.getPreviousCertNo(), true);
put(edits, rows, 12, 2, profile.getPreviousIssueDept(), true);
put(edits, rows, 12, 4, profile.getPreviousIssueDate(), true);
Integer workYears = profile.getCurrentWorkYears() == null
? profile.getJobYears() : profile.getCurrentWorkYears();
put(edits, rows, 12, 6, workYears, true);
put(edits, rows, 13, 2, profile.getLaborBookNo(), true);
}
private void addTrainingInformationEdits(List<RtfEdit> edits, List<RtfRow> rows,
StudentCertificationProfileVO profile) {
put(edits, rows, 14, 2, profile.getTrainingOccupation(), true);
markOne(edits, rows, 16, 2, 7, profile.getTrainingLevel(),
"五级", "四级", "三级", "二级", "一级", "专项职业能力");
markOne(edits, rows, 18, 2, 4, profile.getTrainingCategory(),
"社会培训", "企业培训", "院校培训");
put(edits, rows, 18, 6, Boolean.TRUE.equals(profile.getSubsidyFlag()) ? "√" : "", true);
put(edits, rows, 18, 8, Boolean.TRUE.equals(profile.getSubsidyFlag()) ? "" : "√", true);
put(edits, rows, 19, 2, profile.getAssessmentOccupation(), true);
markOne(edits, rows, 21, 2, 7, profile.getAssessmentLevel(),
"五级", "四级", "三级", "二级", "一级", "专项职业能力");
} }
/** /**
* 输出一行两组“标签-内容”单元格。固定列宽与完整边框保证Word、WPS渲染一致, * 原政府模板为早期15位身份证预留了15格。对于现行18位号码,把多出的前三位均匀放入
* 同时允许较长地址在内容单元格内自动换行。 * 前三个格(每格两位),剩余格仍保持一格一位,既不丢数据,也不改变模板列宽。
*/ */
private void appendFieldRow(StringBuilder rtf, String label1, Object value1, String label2, Object value2) { private void putIdCard(List<RtfEdit> edits, List<RtfRow> rows, String value) {
rtf.append("\\trowd\\trgaph60\\trleft0\\trrh420") String idCard = trim(value);
.append(cellDefinition(1600)).append(cellDefinition(5000)) List<String> parts = new ArrayList<>();
.append(cellDefinition(6600)).append(cellDefinition(10000)); if (idCard != null) {
appendCell(rtf, label1, true); int capacity = 15;
appendCell(rtf, string(value1), false); int doubleCellCount = Math.max(0, idCard.length() - capacity);
appendCell(rtf, label2, true); int offset = 0;
appendCell(rtf, string(value2), false); for (int i = 0; i < capacity; i++) {
rtf.append("\\row "); int width = i < doubleCellCount ? 2 : 1;
int end = Math.min(idCard.length(), offset + width);
parts.add(offset < idCard.length() ? idCard.substring(offset, end) : "");
offset = end;
}
if (offset < idCard.length()) throw new BusinessException("身份证号超过B2模板可显示容量");
}
for (int i = 0; i < 15; i++) {
// 身份证格宽按旧15位号码设计,统一使用7磅字体可让18位号码的双字符格保持单行。
putWithFontSize(edits, rows, 4, i + 2,
i < parts.size() ? parts.get(i) : "", 14);
}
}
/** 把日期拆进模板预留的“年份 / 年 / 月日”窄格,防止完整日期在首格中竖排。 */
private void putSubmitDate(List<RtfEdit> edits, List<RtfRow> rows, Date submitTime) {
if (submitTime == null) {
put(edits, rows, 0, 1, "", true);
return;
}
String[] parts = new SimpleDateFormat("yyyy-MM-dd").format(submitTime).split("-");
putWithFontSize(edits, rows, 0, 1, parts[0], 16);
put(edits, rows, 0, 2, "年", true);
putWithFontSize(edits, rows, 0, 3, parts[1] + "月", 12);
putWithFontSize(edits, rows, 0, 4, parts[2] + "日", 12);
} }
private String cellDefinition(int right) { private void markOne(List<RtfEdit> edits, List<RtfRow> rows, int rowIndex,
return "\\clvertalc\\clbrdrt\\brdrs\\brdrw10\\clbrdrl\\brdrs\\brdrw10" int startCell, int endCell, String actual, String... labels) {
+ "\\clbrdrb\\brdrs\\brdrw10\\clbrdrr\\brdrs\\brdrw10\\cellx" + right; for (int i = startCell; i <= endCell; i++) {
String label = labels[i - startCell];
put(edits, rows, rowIndex, i, label.equals(actual) ? "√" : "", true);
}
} }
private void appendCell(StringBuilder rtf, String text, boolean label) { private void markMany(List<RtfEdit> edits, List<RtfRow> rows, int rowIndex,
rtf.append("\\pard\\intbl\\vertalc\\ql\\fs20 "); int startCell, int endCell, List<String> actualValues, String... labels) {
if (label) rtf.append("\\b "); Set<String> selected = actualValues == null ? new HashSet<>() : new HashSet<>(actualValues);
rtf.append(rtfText(text)); for (int i = startCell; i <= endCell; i++) {
if (label) rtf.append("\\b0 "); put(edits, rows, rowIndex, i, selected.contains(labels[i - startCell]) ? "√" : "", true);
rtf.append("\\cell "); }
} }
/** RTF的Unicode控制字使用有符号16位值;ASCII控制字符则按语法逐一转义。 */ private String normalizeHouseholdType(String value) {
private String rtfText(String value) { String normalized = trim(value);
String text = string(value); if (normalized == null) return null;
StringBuilder escaped = new StringBuilder(text.length() * 2); if (normalized.contains("外地")) return "外地";
for (int i = 0; i < text.length(); i++) { if (normalized.contains("非农") || normalized.contains("城镇")) return "本市非农";
char ch = text.charAt(i); if (normalized.contains("本市农") || normalized.contains("农业")) return "本市农";
if (ch == '\\' || ch == '{' || ch == '}') escaped.append('\\').append(ch); return normalized;
else if (ch == '\r') { /* CR由紧随其后的LF统一处理,避免生成两个换行。 */ }
else if (ch == '\n') escaped.append("\\line ");
else if (ch < 128) escaped.append(ch);
else escaped.append("\\u").append((short) ch).append('?');
} }
return escaped.toString();
private void put(List<RtfEdit> edits, List<RtfRow> rows, int rowIndex, int cellIndex,
Object value, boolean clearExistingText) {
String text = value == null ? "" : String.valueOf(value).trim();
RtfRow row = rows.get(rowIndex);
int end = row.cellEnds.get(cellIndex);
int start = cellIndex == 0 ? row.start : row.cellEnds.get(cellIndex - 1) + "\\cell".length();
if (clearExistingText) edits.add(new RtfEdit(start, end, null));
if (!text.isEmpty()) edits.add(new RtfEdit(end, end, encodeRtfText(text)));
} }
private String personTypes(StudentCertificationProfileVO p) { /** 在不改变单元格边框和尺寸的前提下,仅为特别窄的内容格指定较小字号。 */
if (p.getPersonTypes() == null || p.getPersonTypes().isEmpty()) return ""; private void putWithFontSize(List<RtfEdit> edits, List<RtfRow> rows, int rowIndex,
List<String> values = new ArrayList<>(p.getPersonTypes()); int cellIndex, Object value, int halfPoints) {
if (values.contains("其他") && trim(p.getPersonTypeOther()) != null) { String text = value == null ? "" : String.valueOf(value).trim();
values.add("其他说明:" + p.getPersonTypeOther().trim()); RtfRow row = rows.get(rowIndex);
int end = row.cellEnds.get(cellIndex);
int start = cellIndex == 0 ? row.start : row.cellEnds.get(cellIndex - 1) + "\\cell".length();
edits.add(new RtfEdit(start, end, null));
if (!text.isEmpty()) {
edits.add(new RtfEdit(end, end, "\\fs" + halfPoints + " " + encodeRtfText(text)));
} }
return String.join("、", values);
} }
private String options(String actual, String... values) { private String applyEdits(String template, List<RtfEdit> edits) {
List<String> marked = new ArrayList<>(); // 从后向前处理,确保前方插入文字后不会让尚未处理的原模板坐标发生偏移。
for (String value : values) marked.add(value.equals(actual) ? "[√]" + value : "[ ]" + value); edits.sort((left, right) -> Integer.compare(right.start, left.start));
return String.join(" ", marked); StringBuilder result = new StringBuilder(template);
for (RtfEdit edit : edits) {
if (edit.replacement == null) {
String original = result.substring(edit.start, edit.end);
result.replace(edit.start, edit.end, clearVisibleRtfText(original));
} else {
result.replace(edit.start, edit.end, edit.replacement);
}
}
return result.toString();
} }
private String years(Integer value) { return value == null ? "" : value + "年"; } /** 清除单元格可见文字,但保留字体、段落、边框、行高及合并关系等全部RTF控制字。 */
private String clearVisibleRtfText(String source) {
StringBuilder result = new StringBuilder(source.length());
for (int i = 0; i < source.length();) {
char ch = source.charAt(i);
if (ch == '{' || ch == '}') {
result.append(ch);
i++;
} else if (ch == '\\') {
int controlStart = i++;
if (i < source.length() && source.charAt(i) == '\'') {
i = Math.min(source.length(), i + 3); // \'hh表示一个可见字节,清空时删除。
continue;
}
if (i < source.length() && Character.isLetter(source.charAt(i))) {
int controlNameStart = i;
while (i < source.length() && Character.isLetter(source.charAt(i))) i++;
String controlName = source.substring(controlNameStart, i);
while (i < source.length()
&& (source.charAt(i) == '-' || Character.isDigit(source.charAt(i)))) i++;
if (i < source.length() && source.charAt(i) == ' ') i++;
if ("u".equals(controlName)) {
// RTF Unicode控制字后的单字符是旧阅读器回退值;两者都属于可见正文。
if (i < source.length() && source.charAt(i) != '\\'
&& source.charAt(i) != '{' && source.charAt(i) != '}') i++;
} else {
result.append(source, controlStart, i);
}
} else {
i = Math.min(source.length(), i + 1);
}
} else {
i++;
}
}
return result.toString();
}
/** 动态中文统一写成RTF Unicode控制字,避免服务器默认字符集影响导出内容。 */
private String encodeRtfText(String value) {
StringBuilder result = new StringBuilder(value.length() * 8);
for (int i = 0; i < value.length(); i++) {
char ch = value.charAt(i);
if (ch == '\\' || ch == '{' || ch == '}') {
result.append('\\').append(ch);
} else if (ch == '\r' || ch == '\n') {
if (ch == '\n' || (i + 1 >= value.length() || value.charAt(i + 1) != '\n')) {
result.append("\\line ");
}
} else if (ch >= 32 && ch <= 126) {
result.append(ch);
} else {
result.append("\\u").append((short) ch).append('?');
}
}
return result.toString();
}
private void validateFilledResult(String rtf, StudentCertificationProfileVO profile) {
requireEncodedText(rtf, profile.getName(), "姓名");
requireEncodedText(rtf, profile.getIdCard(), "身份证号");
requireEncodedText(rtf, profile.getPhoneNumber(), "联系电话");
requireEncodedText(rtf, profile.getTrainingOccupation(), "培训职业");
requireEncodedText(rtf, profile.getAssessmentOccupation(), "鉴定职业");
}
private void requireEncodedText(String rtf, String expected, String fieldName) {
String normalized = trim(expected);
if (normalized != null && !rtf.contains(encodeRtfText(normalized))) {
// 身份证被拆分进多个格,不会以连续字符串出现,逐段写入时已通过容量检查。
if ("身份证号".equals(fieldName)) return;
throw new BusinessException("B2模板" + fieldName + "填充校验失败");
}
}
private static final class RtfRow {
private final int start;
private final List<Integer> cellEnds;
private RtfRow(int start, List<Integer> cellEnds) {
this.start = start;
this.cellEnds = cellEnds;
}
}
private static final class RtfEdit {
private final int start;
private final int end;
private final String replacement;
private RtfEdit(int start, int end, String replacement) {
this.start = start;
this.end = end;
this.replacement = replacement;
}
}
private void fillPersonTypes(StudentCertificationProfileVO p) { private void fillPersonTypes(StudentCertificationProfileVO p) {
if (p.getPersonTypes() != null) return; if (p.getPersonTypes() != null) return;
...@@ -262,7 +459,6 @@ public class StudentCertificationAdminServiceImpl implements StudentCertificatio ...@@ -262,7 +459,6 @@ public class StudentCertificationAdminServiceImpl implements StudentCertificatio
private StudentCertificationTreeVO node(String type,String label,String value,Integer classId) { private StudentCertificationTreeVO node(String type,String label,String value,Integer classId) {
StudentCertificationTreeVO node=new StudentCertificationTreeVO(); node.setNodeType(type); node.setLabel(label); node.setValue(value); node.setClassId(classId); return node; StudentCertificationTreeVO node=new StudentCertificationTreeVO(); node.setNodeType(type); node.setLabel(label); node.setValue(value); node.setClassId(classId); return node;
} }
private String formatDate(Date value) { return value == null ? "" : new SimpleDateFormat("yyyy年MM月dd日").format(value); }
private String safe(String value) { String result=value(value,"未知").replaceAll("[\\\\/:*?\"<>|]","_"); return result.length()>80?result.substring(0,80):result; } private String safe(String value) { String result=value(value,"未知").replaceAll("[\\\\/:*?\"<>|]","_"); return result.length()>80?result.substring(0,80):result; }
private String string(Object value) { return value == null ? "" : String.valueOf(value); } private String string(Object value) { return value == null ? "" : String.valueOf(value); }
private String value(String value,String fallback) { return trim(value)==null?fallback:value.trim(); } private String value(String value,String fallback) { return trim(value)==null?fallback:value.trim(); }
......
...@@ -9,11 +9,14 @@ import java.io.ByteArrayInputStream; ...@@ -9,11 +9,14 @@ import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.Arrays; import java.util.Arrays;
import java.util.Date; import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
/** 直接验证RTF正文,防止测试只检查文件外壳而漏掉Word/WPS打开后内容为空的问题。 */ /** 验证原版式RTF模板的结构和可见正文,防止只检查文件外壳而遗漏空白导出。 */
class B2TemplateInspectionTest { class B2TemplateInspectionTest {
@Test @Test
void generatedDocumentShouldContainProfileValuesAndWordTableStructure() throws Exception { void generatedDocumentShouldContainProfileValuesAndWordTableStructure() throws Exception {
...@@ -36,27 +39,34 @@ class B2TemplateInspectionTest { ...@@ -36,27 +39,34 @@ class B2TemplateInspectionTest {
byte[] bytes = new StudentCertificationAdminServiceImpl().createDocument(profile); byte[] bytes = new StudentCertificationAdminServiceImpl().createDocument(profile);
String rtf = new String(bytes, StandardCharsets.US_ASCII); String rtf = new String(bytes, StandardCharsets.US_ASCII);
// RTF内容全部以ASCII控制字表达,测试可稳定检查中文对应的Unicode转义值。 // 原模板固定为33行复杂合并表格;行数变化意味着字段坐标需要重新人工确认。
assertTrue(rtf.startsWith("{\\rtf1")); assertTrue(rtf.startsWith("{\\rtf1"));
assertTrue(rtf.contains("\\trowd")); assertTrue(rtf.contains("\\trowd"));
assertEquals(33, countMatches(rtf, Pattern.compile("\\\\row(?![a-zA-Z])")));
assertTrue(rtf.contains(toRtfUnicode("张三"))); assertTrue(rtf.contains(toRtfUnicode("张三")));
assertTrue(rtf.contains("310101199506011234"));
assertTrue(rtf.contains("13800138000")); assertTrue(rtf.contains("13800138000"));
assertTrue(rtf.contains(toRtfUnicode("企业培训")));
assertTrue(rtf.contains(toRtfUnicode("污水处理工"))); assertTrue(rtf.contains(toRtfUnicode("污水处理工")));
assertTrue(rtf.contains(toRtfUnicode("[√]企业培训"))); assertTrue(rtf.contains(toRtfUnicode("示例水务公司")));
assertTrue(rtf.contains("CERT-001"));
assertFalse(rtf.contains("WordDocument")); assertFalse(rtf.contains("WordDocument"));
// 使用JDK自带RTF解析器执行一次真实回读,证明输出不是“控制字存在但文档不可解析”。 // 使用JDK自带RTF解析器真实回读;去除单元格间空白后,18位身份证必须完整可见。
DefaultStyledDocument parsedDocument = new DefaultStyledDocument(); DefaultStyledDocument parsedDocument = new DefaultStyledDocument();
new RTFEditorKit().read(new ByteArrayInputStream(bytes), parsedDocument, 0); new RTFEditorKit().read(new ByteArrayInputStream(bytes), parsedDocument, 0);
String visibleText = parsedDocument.getText(0, parsedDocument.getLength()); String visibleText = parsedDocument.getText(0, parsedDocument.getLength());
String compactText = visibleText.replaceAll("\\s+", "");
assertTrue(visibleText.contains("张三")); assertTrue(visibleText.contains("张三"));
assertTrue(visibleText.contains("310101199506011234")); assertTrue(compactText.contains("310101199506011234"));
assertTrue(visibleText.contains("企业培训"));
assertTrue(visibleText.contains("污水处理工")); assertTrue(visibleText.contains("污水处理工"));
} }
private int countMatches(String source, Pattern pattern) {
int count = 0;
Matcher matcher = pattern.matcher(source);
while (matcher.find()) count++;
return count;
}
/** 与生产代码相同地把中文转换为RTF Unicode控制字,避免测试依赖本机字符集。 */ /** 与生产代码相同地把中文转换为RTF Unicode控制字,避免测试依赖本机字符集。 */
private String toRtfUnicode(String value) { private String toRtfUnicode(String value) {
StringBuilder escaped = new StringBuilder(); StringBuilder escaped = new StringBuilder();
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment