java根據模板生成,導出word和pdf(aspose.words實現word轉換pdf)


相關一部分java文件和jar包

https://github.com/momodashen/words.git

 

 

pom文件

  <dependency>
        <groupId>com.aspose</groupId>
        <artifactId>aspose-words</artifactId>
        <version>18.2</version>
    </dependency>

 

word模板 其中<forEach>的內容要在設置在表格里面

 

js導出方法

function f_export(){
    var rowsdata = gridManager.getSelectedRow();
     if (!rowsdata) {
         $.ligerDialog.alert('請先選擇一行!');
         return;
     }
     manwait = $.ligerDialog.waitting("正在導出,請稍候...");
     var statDate = rowsdata.statDate;
     $.ajax({
            type : "POST",
            url:'${ctx}/dp/schedulingLogQuery!exportView.action',
            data:$("#form").serializeArray(),
            dataType : "json",
            cache: false,
            success : f_success
        });
}

action代碼

public void exportView(){
        ISchedullingFetchMap fetchmap = (ISchedullingFetchMap) this.getMap();
        fetchmap.generation(modelId,TimeUtil.parseDate(statDate), shiftId);
        Map<String, Object> map = new HashMap<>();
        map.put("status", 200);
        JSONObject jsonObject = JSONObject.fromObject(map);
        ResponseUtil.print(jsonObject.toString());
    }

map代碼 生成words和pdf

public void generation(Long modelId, Date parseDate, Long shiftId) {
        List<Map<String, Object>> fetchList= this.findFetchs(modelId, parseDate, shiftId);
        Map<String, Object> varValues = new HashMap<String, Object>();
        Model model = (Model) this.getPersistQuery().findById(Model.class, modelId);
        varValues.put("name", model.getModelName());
        varValues.put("dateStr", parseDate);
        
        List<Map<String, Object>> fetchs = new ArrayList<>();
        //varValues.put("fetchs", fetchList);
        for (Map<String, Object> map : fetchList) {
            Map<String, Object> map2 = new HashMap<String, Object>();
            String content = map.get("demo").toString();
            map2.put("demo", content);
            map2.put("fetchName", map.get("fetchName").toString());
            fetchs.add(map2);
        }
        varValues.put("fetchs", fetchs);
        //根據msword報表模板生成msword
        String tmpFilename = ServletActionContext.getServletContext().getRealPath("/template/***.docx");//模板文件
    //要導出文件
        String workFilename = ServletActionContext.getServletContext().getRealPath("/reportWorkSpace/**********.docx");
        
        Report report = new Report();
        report.tmpFilename = tmpFilename;
        report.workFilename = workFilename;
        report.varValues = varValues;
        report.transformDOCX();    
    }

report.transformDOCX();實現根據模板轉成word並轉成pdf,html,xps,png等,該java文件可在上方連接獲取

public void transformDOCX() {
        
        //載入模板文件
        msword.report.Operate.load(this);
        //解析
        msword.report.Operate.execute(this);        
        //再替換沒有匹配的${}為空字符
        msword.report.Operate.scavengeSuperfluous(this);
        //保存工作文件
        msword.report.Operate.save(this);
        //轉換為pdf文件
        aspose.Operate.convertasPdf(this);
        //轉換為html文件
//        aspose.Operate.convertasHtml(this);
        //轉換為xps文件
//        aspose.Operate.convertasXps(this);
        //轉換為png文件
//        aspose.Operate.convertasPng(this);
    }

分別下載word文件和pdf文件

<iframe align="middle" id="belowFrame" name="main" frameborder="0" scrolling="no" src="" width="99%" height="0" ></iframe>

//下載word
function f_success(data){
    if (data.status == 200) { 
     //ligerUi提示
        var manager = $.ligerDialog.tip({
            title : '提示',
            content : '操作成功!'
        });
        manwait.close();
        setTimeout(function() {
            manager.close();
        }, 3000);
        document.getElementById("belowFrame").contentWindow.location.href="${pageContext.request.contextPath}//reportWorkSpace/********.docx";
        setTimeout(function() {
            parent.window.frames[thisTabId].f_closeWindow();
        }, 100);
    } else {
        $.ligerDialog.closeWaitting();
        $.ligerDialog.error(data.message);
    }
}
//下載pdf
function f_success(data){
    if (data.status == 200) {
                 //ligetUi提示
        var manager = $.ligerDialog.tip({
            title : '提示',
            content : '操作成功!'
        });
        manwait.close();
      //定時關閉提示
        setTimeout(function() {
            manager.close();
        }, 3000);

window.location.href='${ctx}/dp/schedulingLogQuery!exportPdfView.action'; setTimeout(function() { parent.window.frames[thisTabId].f_closeWindow(); }, 100); } else { $.ligerDialog.closeWaitting(); $.ligerDialog.error(data.message); } }

下載pdf后台代碼

public void exportPdfView(){
        HttpServletRequest request = ServletActionContext.getRequest();
        String TEMPLATE_FILE = "/reportWorkSpace/*******.pdf";
        String templatePath1 = BaseService.getInstance().getRealPath(TEMPLATE_FILE);
        File file=new File(templatePath1);
        String fileName=file.getName();
        String agent=(String)request.getHeader("USER-AGENT"); //判斷瀏覽器類型
        try {  
            if(agent!=null && agent.indexOf("Fireforx")!=-1) {
                fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");   //UTF-8編碼,防止輸出文件名亂碼
            }
            else {
                fileName=URLEncoder.encode(fileName,"UTF-8");
            }
        } catch (Exception e) {  
            e.printStackTrace();  
        }
            OutputStream os=null;
            HttpServletResponse response = ServletActionContext.getResponse();
            response.reset();
            response.setCharacterEncoding("utf-8"); 
            response.setContentType("application/pdf"); // pdf格式
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);    
            try {
                BufferedInputStream bis=new BufferedInputStream(new FileInputStream(file));
                byte[] b=new byte[bis.available()+1000];
                int i=0;
                    os = response.getOutputStream();   //直接下載導出
                    while((i=bis.read(b))!=-1) {
                        os.write(b, 0, i);
                    }
                    os.flush();
                    os.close();
            } catch (IOException e) {  
                e.printStackTrace();  
            }finally {
                if(os!=null) {
                    try {
                        os.close();
                } catch (IOException e) {
                     e.printStackTrace();
                    }
                }
            }
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM