1、引入依賴
<dependency> <groupId>com.aspose.words</groupId> <artifactId>aspose-words-18.8-jdk16-crack</artifactId> <version>18.8</version> </dependency>
2、因為這個包下載不下來,在idea中Terminal運行引入本地倉庫
因為我本地是無需安裝的maven,進入本地mvn的bin目錄下,運行語句
mvn install:install-file -Dfile=D:\workspace\aspose-words-18.8-jdk16-crack-18.8.jar -DgroupId=com.aspose.words -DartifactId=aspose-words-18.8-jdk16-crack -Dversion=18.8 -Dpackaging=jar
3、文書制作方法
word上的占位符分為純文字和域,占位符格式«key»
import com.aspose.words.*;//引用包
/**
* 制作文書方法
* @param request
* @param inFilePath
* @param outFilePath
* @param datas
* @return
* @throws Exception
*/
public Map<String, String> readwriteWord(HttpServletRequest request, String inFilePath, String outFilePath, Map<Object, Object> datas) throws Exception {
Map<String, String> map = new HashMap<>();
Document doc = null;
for (int i = 0; i < 1; i++) {
// 驗證License
if (!getLicense()) {
continue;
}
}
//定義文檔接口
doc = new Document(inFilePath);
//處理列表數據
Object object = datas.get("placeFileInfoList");
List<Map> list = JSON.parseArray(String.valueOf(object), Map.class);
if (list != null && list.size() > 0) {
// 獲取word中的第一個表格,index指定表格位置
Table table = (Table) doc.getChild(NodeType.TABLE, 0, true);
int rowNum = 1;
for (Map map1 : list) { // 替換變量
Node deepClone = table.getRows().get(rowNum).deepClone(true);
Range range = table.getRows().get(rowNum).getRange();
range.replace("«seq»", map1.get("seq") != null ? String.valueOf(map1.get("seq")) : "", true, false);
range.replace("«itemName»", map1.get("itemName") != null ? String.valueOf(map1.get("itemName")) : "", true, false);
range.replace("«number»", map1.get("number") != null ? String.valueOf(map1.get("number")) : "", true, false);
range.replace("«remark»", map1.get("remark") != null ? String.valueOf(map1.get("remark")) : "", true, false);
rowNum = rowNum + 1;
table.getRows().insert(rowNum, deepClone);
}
table.getRows().get(rowNum).remove();
}
for (Map.Entry<Object, Object> entry : datas.entrySet()) {
String key = entry.getKey().toString();
Object value;
if ("placeFileInfoList".equals(key)) {
value = null;
} else {
value = entry.getValue();
}
if (value != null) {
if("myPic".equals(key)){
String imgPath = fileAPIUtils.downloadImg(datas.get(key)+"", datas.get("token")+"");//這里是自定義的下載功能,這里返回的是圖片路徑
doc.getRange().replace("«" + key + "»", "", new FindReplaceOptions(new ReplaceSignPhoto(imgPath, "«" + key + "»")));
}else{
Pattern p = Pattern.compile("\n");
Matcher m = p.matcher(value.toString());
int i = 0;
String replaceValue = "";
Boolean flag = false;
while (m.find()) {
//換行處理
replaceValue = value.toString().replace(m.group(), "" + ControlChar.LINE_BREAK + "");
flag = true;
}
if (flag) {
// 要求替換的內容是完全匹配時的替換
doc.getRange().replace("«" + key + "»", replaceValue, true, false);
} else {
// 要求替換的內容是完全匹配時的替換
doc.getRange().replace("«" + key + "»", value.toString(), true, false);
}
}
}
}
//如果是寫的占位符是文本域,可以實現
Object object1 = datas.get("photoPath");
List<Map> photoPath = JSON.parseArray(String.valueOf(object1), Map.class);
if (CommonUtils.isNotEmpty(photoPath)) {
Document fileDocs = null;
int count = 0;
for (String path : photoPath) {
Document fileDoc = doc.deepClone();
DocumentBuilder builder = new DocumentBuilder(fileDoc);
builder.moveToMergeField("livePhotos");
builder.insertImage(path, RelativeHorizontalPosition.MARGIN, 5, RelativeVerticalPosition.MARGIN, 15, 420, 300, WrapType.SQUARE);
if(count==0){
fileDocs = fileDoc.deepClone();
}else{
fileDocs.appendDocument(fileDoc, ImportFormatMode.KEEP_SOURCE_FORMATTING);
}
count++;
}
doc = fileDocs;
}
//生成四位隨機數
Random ne = new Random();
int num = ne.nextInt(9999 - 1000 + 1) + 1000;
String random = String.valueOf(num);
String fileName = "" + System.currentTimeMillis() + random;
//替換后的Word
String docPath = outFilePath + fileName + inFilePath.substring(inFilePath.lastIndexOf("."));
//生成的PDF位置
String pdfPath = outFilePath + fileName + ".pdf";
doc.save(docPath);
File file = new File(docPath);
if (file.exists()) {
doc2pdf(docPath, pdfPath);
map.put("pdfPath", pdfPath);
map.put("docPath", docPath);
}
return map;
}
package net.longjin.comm.utils;
import com.aspose.words.*;
/**
* @Description 簽名照片處理
* @Author chenling
* @Date 2021/3/30
**/
public class ReplaceSignPhoto implements IReplacingCallback {
private String url;
private String name;
public ReplaceSignPhoto(String url, String name){
this.url = url;
this.name = name;
}
@Override
public int replacing(ReplacingArgs e) throws Exception {
//獲取當前節點
Node currentNode = e.getMatchNode();
//節點拆分處理當前匹配字段
splitRun(currentNode,e.getMatchOffset());
//獲取當前文檔
Document document = (Document) currentNode.getDocument();
DocumentBuilder builder = new DocumentBuilder(document);
//將光標移動到指定節點
builder.moveTo(currentNode);
//插入圖片
Shape img = builder.insertImage(url);//shape可以設置圖片的位置及屬性
//設置寬高
img.setWidth(80);
img.setHeight(30);
img.setWrapType(WrapType.SQUARE);
img.setDistanceLeft(10);
img.setHorizontalAlignment(HorizontalAlignment.CENTER);
img.setVerticalAlignment(VerticalAlignment.CENTER);
img.setName(name);
return ReplaceAction.SKIP;
}
private void splitRun(Node currentNode ,int position){
String text = currentNode.getText();
Node newNode = currentNode.deepClone(true);
if(text.length() >= position+this.name.length()){
((Run)currentNode).setText (text.substring(position+this.name.length()));
}else{
int morlength = position+this.name.length() - text.length();
((Run)currentNode).setText ("");
Node tmpnode = currentNode;
for(int i=0;i<this.name.length();i++){
System.out.println(i);
tmpnode = tmpnode.getNextSibling();
String tmptext= tmpnode.getText();
System.out.println(tmptext);
System.out.println(morlength);
System.out.println("--------"+(tmptext.length() >= morlength));
if(tmptext.length() >= morlength){
((Run)tmpnode).setText(tmptext.substring(morlength));
break;
}else{
morlength = morlength - tmptext.length();
((Run)tmpnode).setText("");
}
}
}
if(position>0){
((Run)newNode).setText(text.substring(0, position));
currentNode.getParentNode().insertBefore(newNode, currentNode);
}
}
}
4、勾選框處理
默認都是□ 根據是或者否 將□ 替換成 ☑
個人工作中用到的,如有更好的方式請留言,謝謝
