最近在测试通过word模板生成简历功能,搜了很多方法都是通过书签方式,要先移动到书签位置然后再进行 *** 作,主要是书签添加起来特别麻烦。而且使用wps还添加的老是出问题。所以找了一个替换的方式。具体 *** 作如下:
首先在word中设置好样式,然后对字符串进行替换就好了。
使用到的jar包
com.aspose aspose-words14.7.0 cn.hutool hutool-all4.5.15
package com.register.common.wps; import cn.hutool.core.bean.BeanUtil; import cn.hutool.core.io.FileUtil; import cn.hutool.core.util.IdUtil; import com.aspose.words.*; import com.register.common.utils.OSSUtils; import org.apache.commons.lang3.StringUtils; import javax.servlet.http.HttpServletRequest; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.net.URLEncoder; import java.util.Date; import java.util.Map; import java.util.regex.Pattern; import static com.register.common.utils.DateUtil.formatDate; public class WordUtils { private static InputStream license; private static final String SYSTEM_SEPARATOR = "/"; public static final int TEXT= 1; public static final int HTML = 2; public static final int PICTURE = 3; public static boolean getLicense() { boolean result = false; try { license = WordUtils.class.getClassLoader().getResourceAsStream("license.xml"); License aLicense = new License(); aLicense.setLicense(license); result = true; } catch (Exception e) { e.printStackTrace(); } return result; } private static document getdocumentTemp() throws Exception { InputStream inputStream = null; document document = null; try{ inputStream = WordUtils.class.getClassLoader().getResourceAsStream("examBookTemp.docx"); if(inputStream != null){ document = new document(inputStream); } } catch(Exception e){ e.printStackTrace(); }finally{ if(inputStream != null){ inputStream.close(); } } return document; } public static String setEncoding(HttpServletRequest request, String fileName) { String userAgent = request.getHeader("User-Agent").toUpperCase(); try{ if(StringUtils.contains(userAgent, "MSIE")|| userAgent.contains("LIKE GECKO")){ //IE浏览器 fileName = URLEncoder.encode(fileName,"UTF-8"); }else if(StringUtils.contains(userAgent, "MOZILLA")){ //google,火狐浏览器 fileName = new String(fileName.getBytes(), "ISO8859-1"); }else{ //其他浏览器 fileName = URLEncoder.encode(fileName,"UTF8"); } }catch (Exception e){ e.printStackTrace(); } return fileName; } private static void preGeneWord() { if (!getLicense()) { System.out.println("获取验证失败"); } if(SYSTEM_SEPARATOR.equals(File.separator)){ FontSettings.setFontsFolder("/usr/share/fonts/font", true); } } public static class ReplaceAndInsertImage implements IReplacingCallback{ public String url; public ReplaceAndInsertImage(String url){ this.url = url; } @Override public int replacing(ReplacingArgs e) throws Exception { //获取当前节点 Node node = e.getMatchNode(); //获取当前文档 document doc = (document) node.getdocument(); documentBuilder builder = new documentBuilder(doc); //将光标移动到指定节点 builder.moveTo(node); //插入图片 Shape shape = new Shape(doc, ShapeType.IMAGE); shape.getImageData().setImage(url); shape.setHeight(100); shape.setWidth(80); shape.setDistanceTop(10); shape.setHorizontalAlignment(HorizontalAlignment.CENTER); shape.setVerticalAlignment(VerticalAlignment.CENTER); builder.insertNode(shape); return ReplaceAction.REPLACE; } } public static class ReplaceAndInsertHtml implements IReplacingCallback{ public String html; public ReplaceAndInsertHtml(String html){ this.html = html; } @Override public int replacing(ReplacingArgs e) throws Exception { //获取当前节点 Node node = e.getMatchNode(); //获取当前文档 document doc = (document) node.getdocument(); documentBuilder builder = new documentBuilder(doc); //将光标移动到指定节点 builder.moveTo(node); //插入图片 builder.insertHtml(html,true); return ReplaceAction.REPLACE; } } private static void documentWrite(document document,String replaceFiled,String content,Integer replaceType) { try { if(TEXT == replaceType){ //文本类型 document.getRange().replace(replaceFiled,content,true,true); } else if(HTML == replaceType){ Pattern pattern = Pattern.compile(replaceFiled); document.getRange().replace(pattern,new ReplaceAndInsertHtml(content),false); } else if(PICTURE == replaceType){ if(StringUtils.isEmpty(content)){ document.getRange().replace(replaceFiled,"暂无",true,true); }else{ Pattern pattern = Pattern.compile(replaceFiled); document.getRange().replace(pattern,new ReplaceAndInsertImage(content),false); } } } catch (Exception e) { e.printStackTrace(); } } public static String geneExamBook(ExamBookVo examBook) throws Exception { String fileName = getFileName(); FileOutputStream outputStream = new FileOutputStream(fileName); // *** 作word之前的预处理 preGeneWord(); document document = getdocumentTemp(); writeExamBook(document,examBook); //注意SaveFormat的格式要与上面生成格式保持一致 document.save(outputStream, SaveFormat.PDF); outputStream.flush(); outputStream.close(); FileInputStream inputStream = new FileInputStream(fileName); String path = OSSUtils.picFolder + "/shareCodePdf/" + formatDate(new Date(), "yyyyMMdd"); String pdfUrl = OSSUtils.uploadObject2OSSByStream(inputStream, path, "aaa.pdf"); FileUtil.del(fileName); return pdfUrl; } private static String getFileName() { String fileName = ""; if(File.separator.equals("/")){ fileName = "/home/apps/register/pdf/"; }else{ fileName = "D:\apps\register\pdf\"; } File target = new File(fileName); if(!target.exists()){ target.mkdirs(); } fileName = fileName+IdUtil.fastUUID()+".pdf"; return fileName; } private static void writeExamBook(document document, ExamBookVo examBook) { Mapmap = BeanUtil.beanToMap(examBook); for (Map.Entry stringObjectEntry : map.entrySet()) { documentWrite(document,stringObjectEntry.getKey(),stringObjectEntry.getValue().toString(),TEXT); } } public static void main(String[] args) throws Exception { ExamBookVo examBookVo = new ExamBookVo(); examBookVo.setExamNo("202010110198"); examBookVo.setUserName("金XX"); examBookVo.setIdCard("310114199XXXXXXXX"); examBookVo.setPeriod("小学"); examBookVo.setSubjectName("语文"); examBookVo.setExamRoom("笔试第 07 考场(204)"); examBookVo.setExamDate("2020 年 10 月 11 日(星期日)"); examBookVo.setExamTime("9:00"); String examBook = geneExamBook(examBookVo); } }
下面是我生成准考证的方法,建立的好像不小心被删除了。其实很简单。如果有什么看不明白的地方可以微信交流。
如果需要jar包的可以添加微信我发给你。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)