Java使用aspose生成简历

导读:本篇文章讲解 Java使用aspose生成简历,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

最近在测试通过word模板生成简历功能,搜了很多方法都是通过书签方式,要先移动到书签位置然后再进行操作,主要是书签添加起来特别麻烦。而且使用wps还添加的老是出问题。所以找了一个替换的方式。具体操作如下:

首先在word中设置好样式,然后对字符串进行替换就好了。

Java使用aspose生成简历

 使用到的jar包

        <!--aspose操作word-->
        <dependency>
            <groupId>com.aspose</groupId>
            <artifactId>aspose-words</artifactId>
            <version>14.7.0</version>
        </dependency>
        <!--糊涂工具-->
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>4.5.15</version>
        </dependency>
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;

/**
 * description: WordUtils word工具类<br>
 *
 * @date: 2021/8/6 0006 上午 10:57 <br>
 * @author: William <br>
 * version: 1.0 <br>
 */
public class WordUtils {

    /**
     * aspose操作证书
     */
    private static InputStream license;

    /**
     * Linux系统分隔符
     */
    private static final String SYSTEM_SEPARATOR = "/";

    /**
     * 文本类型
     */
    public static final int TEXT= 1;

    /**
     * HTML类型
     */
    public static final int HTML = 2;

    /**
     * 图片类型
     */
    public static final int PICTURE = 3;




    /**
     * description: getLicense 获取操作证书<br>
     * version: 1.0 <br>
     * @date: 2021/8/6 0006 上午 11:00 <br>
     * @author: William <br>
     * @param
     * @return boolean
     */
    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;
    }


    /**
     * description: getDocumentTemp 获取模板路径<br>
     * version: 1.0 <br>
     * @date: 2021/8/6 0006 下午 12:59 <br>
     * @author: William <br>
     * @param
     * @return com.aspose.words.Document
     */
    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;
    }


    /**
     *处理下载中文乱码
     * @param request   请求
     * @param fileName  文件名称
     * @return:
     * @author: William
     * @date 2019/9/12 9:56
     */
    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;
    }


    /**
     * description: preGeneWord 生成word准备工作,获取License以及获取系统字体<br>
     * version: 1.0 <br>
     * @date: 2021/4/15 0015 下午 1:27 <br>
     * @author: William <br>
     */
    private static void preGeneWord() {
        if (!getLicense()) {
            System.out.println("获取验证失败");
        }
        if(SYSTEM_SEPARATOR.equals(File.separator)){
            FontSettings.setFontsFolder("/usr/share/fonts/font", true);
        }
    }

    /**
     * description: 替换图片方法 <br>
     * version: 1.0 <br>
     * @date: 2021/4/15 0015 下午 2:45 <br>
     * @author: William <br>
     */
    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;
        }
    }


    /**
     * description: 替换文本为html方法 <br>
     * version: 1.0 <br>
     * @date: 2021/4/15 0015 下午 2:45 <br>
     * @author: William <br>
     */
    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;
        }
    }



    /**
     * description: documentWrite  <br>
     * version: 1.0 <br>
     * @date: 2021/8/6 0006 下午 1:35 <br>
     * @author: William <br>
     * @param document        word文档
     * @param replaceFiled    需要替换的字符
     * @param content         替换内容
     * @param replaceType     替换类型 1是字符串 2是HTML 3是图片
     * @return void
     */
    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();
        }
    }



    /**
     * description: geneExamBook <br>
     * version: 1.0 <br>
     * @date: 2021/8/6 0006 下午 7:04 <br>
     * @author: William <br>
     * @param examBook   准考证书信息
     * @return java.lang.String
     */
    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;
    }


    /**
     * description: getFileName 获取文件名称<br>
     * version: 1.0 <br>
     * @date: 2021/8/6 0006 下午 6:49 <br>
     * @author: William <br>
     * @param
     * @return java.lang.String
     */
    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;
    }


    /**
     * description: writeExamBook 向简历中填写内容<br>
     * version: 1.0 <br>
     * @date: 2021/8/6 0006 下午 2:46 <br>
     * @author: William <br>
     * @param document   word文档操作流
     * @param examBook   需要替换的对象实体
     * @return void
     */
    private static void writeExamBook(Document document, ExamBookVo examBook) {
        Map<String, Object> map = BeanUtil.beanToMap(examBook);
        for (Map.Entry<String, Object> 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包的可以添加微信我发给你。

Java使用aspose生成简历

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/96980.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!