zoukankan      html  css  js  c++  java
  • 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();
                        }
                    }
                }
        }
  • 相关阅读:
    Civil 3D 二次开发 创建Civil 3D 对象—— 01 —— 创建几何空间点
    Civil 3D 二次开发 创建Civil 3D 对象—— 00 ——
    Civil 3D 二次开发 创建AutoCAD对象—— 01 —— 创建直线
    Civil 3D 二次开发 新建CLR项目出现错误C2143
    Civil 3D 二次开发 创建AutoCAD对象—— 00 ——
    了解AutoCAD对象层次结构 —— 6 ——块表记录
    datepicker97使用
    使用angular 外接 templateUrl,使用ng-include
    angularJs 遮罩
    网上找的有关css兼容问题
  • 原文地址:https://www.cnblogs.com/hnzkljq/p/11244220.html
Copyright © 2011-2022 走看看