package foundation.io.file.ppt;
|
|
import java.util.ArrayList;
|
import java.util.List;
|
import java.util.Map;
|
import java.util.regex.Matcher;
|
import java.util.regex.Pattern;
|
|
import org.apache.poi.xslf.usermodel.*;
|
|
import foundation.io.engine.IShapeWriter;
|
|
public class TextShapeWriter extends IShapeWriter {
|
private static String param_pattern = "\\$\\{[^}(?!{)]*\\}";
|
private static String param_left = "${";
|
private static String param_right = "}";
|
|
private XSLFTextShape textShape;
|
private List<String> params;
|
|
public TextShapeWriter(XSLFTextShape shape) {
|
super(shape);
|
this.textShape = shape;
|
this.params = parseParams(shape.getText());
|
}
|
|
@Override
|
public void writeData(XSLFSlide slide, Map<String, Object> data) throws Exception{
|
XSLFTextShape textShape = (XSLFTextShape) shape;
|
replaceTextKeepStyle(textShape, data);
|
}
|
|
public void replaceTextKeepStyle(XSLFTextShape shape, Map<String, Object> data) {
|
// 获取所有文本段落
|
List<XSLFTextParagraph> paragraphs = shape.getTextParagraphs();
|
|
for (XSLFTextParagraph paragraph : paragraphs) {
|
// 获取段落中的所有文本块
|
List<XSLFTextRun> runs = paragraph.getTextRuns();
|
|
for (int i = 0; i < runs.size(); i++){
|
XSLFTextRun run = runs.get(i);
|
String text = run.getRawText();
|
for (String param : params){
|
if (text != null && text.contains(param)) {
|
// 保留原有样式替换文本
|
Object value = data.get(param);
|
run.setText(text.replace(param, String.valueOf(value)));
|
}
|
}
|
}
|
}
|
}
|
|
private List<String> parseParams(String text){
|
Pattern p = Pattern.compile(param_pattern);
|
Matcher m = p.matcher(text);
|
|
List<String> params = new ArrayList<>();
|
String placeholder;
|
|
while(m.find()){
|
// ${}和 里面的内容
|
placeholder = m.group(0);
|
String fieldName = placeholder.substring(2, placeholder.length()-1);
|
params.add(placeholder);
|
}
|
|
// VariantExpression formExpression = new VariantExpression(text);
|
// for (VariantSegment variant : formExpression) {
|
// placeholder = variant.getName();
|
// value = data.get(placeholder);
|
// }
|
|
return params;
|
}
|
|
private String paramStr(String param){
|
return param_left + param + param_right;
|
}
|
|
@Override
|
public XSLFTextShape getShape() {
|
return textShape;
|
}
|
|
}
|