`
gp562
  • 浏览: 10579 次
  • 性别: Icon_minigender_2
  • 来自: 长沙
社区版块
存档分类
最新评论

在线预览附件

阅读更多
附件预览分量大类,简单类型(TXT,图片,PDF),这一类的处理方法就是用浏览器解析response
 
office类型的复杂一些,需要安装软件等,参考链接http://my.oschina.net/baochanghong/blog/506829
这两篇文章都写得很详细,下面写一下我在项目过程中遇到的一些问题
1,使用openoffice前需要启动该服务,
     CMD命令进入OpenOffice安装目录下的program目录,键入如下命令
        soffice "-accept=socket,host=localhost,port=8100;urp;StarOffice.ServiceManager" -nologo -headless -nofirststartwizard
代码
2,flexPaper只能读取根目录下的swf文件,为了不让项目文件变多,在nginx的配置文件中配置一个虚拟目录指定到本地,将Java中生成的文件放在本地,flexPaper用虚拟目录去访问
        location ^~ /SwfFiles/ {
                    alias d:/SwfFiles/;
                }
 
前端代码:
<a href="http://127.0.0.1:8081/TroubleTicketServlet?servicecode=download&docName={{this.documentName}}&serialId={{../serialId}}&transDocName={{this.transDocName}}&WEB_HUB_PARAMS={'header':{'token':'','tenant':''}}" >Download </a>
Java代码:
    public void onlinePreview(HttpServletRequest request, HttpServletResponse response) throws Exception{
     //本地调试打开使用
     UserInfoInterface user = SessionManager. getSysUser();
     if(user == null){//servlet设置租户
           user = new UserInfo();
           user.setID(410000231);
           user.setTenantId( "21"); //为默认操作员设置租户ID
           SessionManager. setUser(user);
     }
     String serialId = request.getParameter( "serialId");
     String transDocName = request.getParameter("transDocName" );
     // 必填信息校验
     if (ValidatorUtils.isEmptyId(serialId)) {
           response.getWriter().write( "serialId can not be null!");
            return ;
     }
     if (ValidatorUtils.isEmptyString(transDocName)) {
           response.getWriter().write( "transDocName can not be null!");
            return ;
     }
     try {
           Map<String, String> map = new HashMap<String, String>();
           map.put( "serialId", serialId);
           map.put( "transDocName", transDocName);
           map.put( "pageNumber", "1"); //页号
           map.put( "pageSize", "1"); //分页记录数
           IQueryDocInfoResponseValue docInfoResponseValue = ServiceFactoryUtils.getQryPkgHubSV().queryDocInfo(QueryConditionUtils. constructQueryConditon(map));
           IDocInfoBase[] docInfoBoList = docInfoResponseValue.getResponseList();
            if(docInfoBoList == null || docInfoBoList. length<1){
                response.getWriter().write( "can not find file,failed to online preview!");
                 return ;
           }
           String docName = docInfoBoList[0].getDocumentName();
           IntfLogUtils. printLogInfo(TroubleTicketServlet.class, "find file:" + docName);
           response.setHeader( "Content-disposition", "inline; filename="
                     + new String(docInfoBoList[0].getDocumentName().getBytes("utf-8" ), "ISO8859-1"));
           InputStream inStream = FTPUtils.readRemote(transDocName);//获取附件的输入流
           BufferedInputStream bs= new BufferedInputStream(inStream);
           BufferedReader ir = new BufferedReader( new InputStreamReader(bs,"gb2312" ));
            //txt
           if(docName.toLowerCase().endsWith(TroubleTicketConstant.FileType. TXT)){
                response.setContentType( "text/html;charset=utf-8");
                String tmpStr = "";
                 while((tmpStr = ir.readLine()) != null){
                     response.getWriter().write(tmpStr+ "<br/>");
                }
           }
            //图片
           if(docName.toLowerCase().endsWith(TroubleTicketConstant.FileType. GIF)
                     ||docName.toLowerCase().endsWith(TroubleTicketConstant.FileType. JPEG)
                     ||docName.toLowerCase().endsWith(TroubleTicketConstant.FileType. JPG)
                     ||docName.toLowerCase().endsWith(TroubleTicketConstant.FileType. PNG)){
                response.setContentType( "image/jpg");  
                      byte bytes[] = readInputStream(inStream); 
                     inStream.read(bytes);     
                   response.getOutputStream().write(bytes);   
           }
            //PDF
           if(docName.toLowerCase().endsWith(TroubleTicketConstant.FileType. PDF)){
                 byte bytes[] = readInputStream(inStream); 
                     inStream.read(bytes);     
                   response.setContentType( "application/pdf");    
                   response.getOutputStream().write(bytes);   
           }
            //office类型
           if(docName.toLowerCase().endsWith(TroubleTicketConstant.FileType. DOC)
                     ||docName.toLowerCase().endsWith(TroubleTicketConstant.FileType. DOCX)
                     ||docName.toLowerCase().endsWith(TroubleTicketConstant.FileType. PPT)
                     ||docName.toLowerCase().endsWith(TroubleTicketConstant.FileType. PPTX)
                     ||docName.toLowerCase().endsWith(TroubleTicketConstant.FileType. XLS)
                     ||docName.toLowerCase().endsWith(TroubleTicketConstant.FileType. XLSX)){
                String dir = "D:/SwfFiles/";
                String suffix = docName.substring(docName.lastIndexOf("." ));//.doc
                File docFile = new File(dir+ transDocName + suffix);
                FileOutputStream fop = new FileOutputStream(docFile);
                 if (!docFile.exists()) {
                     docFile.createNewFile();
                }
                System. out.println(docFile.getAbsolutePath());
                fop.write(readInputStream(inStream));
                    fop.close();
                DocConverter d = new DocConverter(dir + transDocName + suffix, docFile);
               d.conver();
               String swfFileName = transDocName + ".swf";
               response.sendRedirect("http://127.0.0.1:7777/ARIESRES/crm-bj/trouble-ticket/ticket-business/flexPaper/online-view.html?swfFileName=" +swfFileName);
           }
           inStream.close(); 
           bs.close();
           ir.close();
                ServiceFactoryUtils. getBizSV().createHandlingLog("", DataTypeUtils.toLong(serialId), 0, 0, TroubleTicketConstant.OperateType.DOWNLOAD_ATTACHMENT , null);
                ServiceFactoryUtils. getBizSV().createDocFtpDoneLog(docInfoBoList[0].getDocumentId());
           } catch (Exception e) {
                 log.error(e,e);
                response.getWriter().write( "failed to online preview file!");
           }
    }
 
 
 
package com.ai.veriscrm.paas.troubleticket.common.util;
 
 
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
 
import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;
 
public class DocConverter {
    private static final int environment = 1;// 环境1:windows,2:linux(涉及pdf2swf路径问题)
    private String fileString;
    private String outputPath = "";// 输入路径,如果不设置就输出在默认位置
    private String fileName;
    private File pdfFile;
    private File swfFile;
    private File docFile;
 
    public DocConverter(String fileString,File file) {
        ini(fileString, file);
    }
 
    /*
     * 初始化 @param fileString
     */
    private void ini(String fileString, File file) {
        this.fileString = fileString;
        fileName = fileString.substring(0, fileString.lastIndexOf("."));
        docFile = file;
        pdfFile = new File(fileName + ".pdf");
        swfFile = new File(fileName + ".swf");
    }
 
    /*
     * 转为PDF @param file
     */
    private void doc2pdf() throws Exception {
        if (docFile.exists()) {
            if (!pdfFile.exists()) {
                OpenOfficeConnection connection = new SocketOpenOfficeConnection(8100);
                try {
                    connection.connect();
                    DocumentConverter converter = new OpenOfficeDocumentConverter(connection);
                    converter.convert(docFile, pdfFile);
                    // close the connection
                    connection.disconnect();
                    System.out.println("****pdf转换成功,PDF输出:" + pdfFile.getPath() + "****");
                } catch (java.net.ConnectException e) {
                    // ToDo Auto-generated catch block
                    e.printStackTrace();
                    System.out.println("****swf转换异常,openoffice服务未启动!****");
                    throw e;
                } catch (com.artofsolving.jodconverter.openoffice.connection.OpenOfficeException e) {
                    e.printStackTrace();
                    System.out.println("****swf转换器异常,读取转换文件失败****");
                    throw e;
                } catch (Exception e) {
                    e.printStackTrace();
                    throw e;
                }
            } else {
                System.out.println("****已经转换为pdf,不需要再进行转化****");
            }
        } else {
            System.out.println("****swf转换器异常,需要转换的文档不存在,无法转换****");
        }
    }
 
    /*
     * 转换成swf
     */
    private void pdf2swf() throws Exception {
        Runtime r = Runtime.getRuntime();
        if (!swfFile.exists()) {
            if (pdfFile.exists()) {
                if (environment == 1)// windows环境处理
                {
                    try {
                        // 这里根据SWFTools安装路径需要进行相应更改
                        Process p = r.exec("D:/ttonline/SWFTools/pdf2swf.exe " + pdfFile.getPath() + " -o " + swfFile.getPath() + " -T 9");
                        System.out.print(loadStream(p.getInputStream()));
                        System.err.print(loadStream(p.getErrorStream()));
                        System.out.print(loadStream(p.getInputStream()));
                        System.err.println("****swf转换成功,文件输出:" + swfFile.getPath() + "****");
                        if (pdfFile.exists()) {
                            pdfFile.delete();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        throw e;
                    }
                } else if (environment == 2)// linux环境处理
                {
                    try {
                        Process p = r.exec("pdf2swf " + pdfFile.getPath() + " -o " + swfFile.getPath() + " -T 9");
                        System.out.print(loadStream(p.getInputStream()));
                        System.err.print(loadStream(p.getErrorStream()));
                        System.err.println("****swf转换成功,文件输出:" + swfFile.getPath() + "****");
                        if (pdfFile.exists()) {
                            pdfFile.delete();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        throw e;
                    }
                }
            } else {
                System.out.println("****pdf不存在,无法转换****");
            }
        } else {
            System.out.println("****swf已存在不需要转换****");
        }
    }
 
    static String loadStream(InputStream in) throws IOException {
        int ptr = 0;
        //把InputStream字节流 替换为BufferedReader字符流 2013-07-17修改
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        StringBuilder buffer = new StringBuilder();
        while ((ptr = reader.read()) != -1) {
            buffer.append((char) ptr);
        }
        return buffer.toString();
    }
 
    /*
     * 转换主方法
     */
    public boolean conver() {
        if (swfFile.exists()) {
            System.out.println("****swf转换器开始工作,该文件已经转换为swf****");
            return true;
        }
 
        if (environment == 1) {
            System.out.println("****swf转换器开始工作,当前设置运行环境windows****");
        } else {
            System.out.println("****swf转换器开始工作,当前设置运行环境linux****");
        }
 
        try {
            doc2pdf();
            pdf2swf();
        } catch (Exception e) {
            // TODO: Auto-generated catch block
            e.printStackTrace();
            return false;
        }
 
        if (swfFile.exists()) {
            return true;
        } else {
            return false;
        }
    }
 
    /*
     * 返回文件路径 @param s
     */
    public String getswfPath() {
        if (swfFile.exists()) {
            String tempString = swfFile.getPath();
            tempString = tempString.replaceAll("\\\\", "/");
            return tempString;
        } else {
            return "";
        }
    }
 
    /*
     * 设置输出路径
     */
    public void setOutputPath(String outputPath) {
        this.outputPath = outputPath;
        if (!outputPath.equals("")) {
            String realName = fileName.substring(fileName.lastIndexOf("/"), fileName.lastIndexOf("."));
            if (outputPath.charAt(outputPath.length()) == '/') {
                swfFile = new File(outputPath + realName + ".swf");
            } else {
                swfFile = new File(outputPath + realName + ".swf");
            }
        }
    }
}
 
 
<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd' >
<html xmlns= 'http://www.w3.org/1999/xhtml' lang ='en' xml:lang= 'en'>  
    <head >
        <title >FlexPaper </title >        
        <meta http-equiv ='Content-Type' content='text/html; charset=utf-8' />
        <style type ='text/css' media='screen'>
                 html, body { height: 100%; }
                 body { margin: 0; padding: 0; overflow: auto; }  
                 #flashContent { display: none; }
        </style >
            <script type ='text/javascript' src= '/ARIESRES/crm-bj/trouble-ticket/ticket-business/flexPaper/flexpaper_flash.js' ></script >
    </head >
    <body >
     <div style ='position :absolute;left:10px;top:10px;'>
             <a id ='viewerPlaceHolder' style=' width: 1300px; height: 680px; display: block' ></a >
             <script type ='text/javascript'>
                      var str=window.location.href; //取得整个地址栏
                      var num=str.indexOf( "?");
                     str=str.substr(num+1);
                      var arr=str.split( "&");
                     num=arr[0].indexOf( "=");
                      var value = arr[0].substr(num+1);
                      var fp = new FlexPaperViewer(   
                                 'FlexPaperViewer',
                                 'viewerPlaceHolder', { config : {
                                 SwfFile : escape("/SwfFiles/"+value),
                                 Scale : 1,
                                 ZoomTransition : 'easeOut',
                                 ZoomTime : 0.5,
                                 ZoomInterval : 0.2,
                                 FitPageOnLoad : false,
                                 FitWidthOnLoad : false,
                                 FullScreenAsMaxWindow : false,
                                 ProgressiveLoading : false,
                                 MinZoomSize : 0.2,
                                 MaxZoomSize : 5,
                                 SearchMatchAll : true,
                                 InitViewMode : 'Portrait',
                                 PrintPaperAsBitmap : false,
                                 ViewModeToolsVisible : true,
                                 ZoomToolsVisible : true,
                                 NavToolsVisible : true,
                                 CursorToolsVisible : true,
                                 SearchToolsVisible : false,
                                 localeChain: 'en_US'
                                 }});
             </script >
        </div >
   </body >
</html>
 
分享到:
评论

相关推荐

    java Aspose实现附件在线预览功能

    在Java开发环境中,有时我们需要为用户提供在线预览附件的功能,比如查看Excel、Word或PowerPoint文档,而无需下载文件到本地。在这种情况下,Aspose是一个强大的工具,它提供了丰富的API来处理各种办公文档格式,...

    spring+element+vue附件上传、下载及在线预览

    本文将深入探讨如何在基于Spring Boot后端和Vue.js前端的环境中,利用Element UI组件库实现附件的上传、下载以及在线预览功能。Element UI是基于Vue.js的组件库,提供了丰富的UI组件,对于构建企业级应用非常方便。 ...

    Windows下实现php在线预览功能

    在Windows环境下实现PHP在线预览功能是一个涉及多个步骤的复杂过程,主要涉及到文件格式转换以及显示。...这种在线预览功能在很多企业网站或在线教育平台有着广泛的应用,对于提高用户体验和操作便利性具有重要意义。

    谷歌浏览器在线预览office文件插件。适用于86以上

    谷歌浏览器在线预览Office文件插件是一款专为Web开发者设计的工具,旨在提供在浏览器中直接查看Word、Excel、PowerPoint以及PDF等办公文档的能力,无需安装任何额外的桌面应用程序。这款插件适用于Chrome浏览器的86...

    uniapp移动端H5在线预览PDF等文件实现源码及注解

    本教程将详细讲解如何在uniapp移动端通过H5实现PDF和其他文件的在线预览功能。通过提供的源码和注解,开发者可以深入理解其实现机制,并在自己的项目中进行应用。 首先,我们需要了解uniapp的组件系统。uniapp允许...

    Aspose实现附件在线预览功能

    利用Aspose实现的附件在线预览功能,包括excel、word、ppt 已是破解版不限时间可次数 去除水印 工程为java工程 导入即可用

    C#模仿百度文库实现附件在线预览

    在IT行业中,实现在线预览功能对于提升用户...以上就是"C#模仿百度文库实现附件在线预览"项目的核心技术点和实施步骤。通过这样的功能,用户可以方便快捷地预览各类文件,而无需下载,大大提升了工作效率和用户体验。

    android实现附件预览效果

    3. 第三方应用交互:在本例中,预览附件可能需要借助WPS等第三方应用。使用`Intent`是Android中启动其他应用的常见方式。开发者需要创建一个包含`ACTION_VIEW`动作的`Intent`,并设置`setDataAndType()`来指定文件...

    odoo14 附件预览图片及pdf

    odoo14 附件预览图片及pdf

    预览pdf附件1

    预览pdf的详细代码,可以实现在线预览pdf

    Office附件预览公共服务

    使用office附件预览公共服务,您不用在服务器端部署、浏览者不用客户端下载,仅仅使用浏览器就可以实现,只需要使用URI提交简单的参数给office附件预览公共服务即可; 兼容PC和手机浏览器; 支持Office文档在线预览...

    泛微E9 JS实现流程字段联动出附件图片效果.docx

    为了优化这一过程,我们可以利用泛微E9系统中的字段联动功能,并结合JavaScript进行自定义开发,实现一个在线预览附件图片的功能。下面是实现这一解决方案的具体步骤: 1. **配置字段联动**: 首先,我们需要创建...

    附件在线预览pdf双手指滑动缩放.zip

    标题 "附件在线预览pdf双手指滑动缩放.zip" 提到的核心技术是PDF在线预览功能,特别是针对手机端的交互方式,即通过双手指滑动进行缩放操作。在移动设备上,用户通常使用触摸屏进行交互,因此这种手势操作是优化用户...

    redmine附件图片预览技术

    为了在Redmine中预览附件图片,我们需要对系统的代码进行一定的修改。具体来说,我们需要修改`app\views\attachments\_links.rhtml`文件来实现这一功能。 #### 步骤一:安装必要的插件或依赖 在开始之前,请确保你...

    DocumentViewer在线预览

    "DocumentViewer在线预览"是一个功能强大的解决方案,它允许用户在Web环境中查看和处理各种类型的文档,无需下载或安装任何额外软件。这个系统的核心在于提供一个安全、便捷的方式来浏览附件,尤其是在协作和信息...

    java实现附件预览(openoffice+PDF.js)

    java实现附件预览(openoffice+PDF.js),将office文档,通过openoffice工具转换为PDF文件,使用PDF.js进行前端展示 是对openoffice+swftools+flexpaper的升级版,减少一次swf文件转换,及flexpaper只能预览十页内容...

    SpringBoot在线预览PDF文件

    本项目的核心是实现PDF在线预览功能,它利用了SpringBoot的Web服务特性,结合PDF.js库来实现在浏览器中预览PDF文件。 首先,我们需要理解SpringBoot的Web开发基础。SpringBoot内置了对HTTP请求处理的支持,通过创建...

    C# 文件在线预览(word execl ppt Image txt pdf)

    1.文件不需下载 2.在线打开预览 3.支持多种格式

    Office文件在线预览

    6. **协作与共享**:在线预览对于团队协作尤其有用,因为它允许用户即时查看他人的更改,同时可以添加评论或反馈,而无需邮件附件的来回发送。 7. **跨平台兼容性**:由于大多数现代浏览器都支持HTML5,因此在线...

    鼠标掠过主题列表图片附件即时预览插件 for discuz 7.0.rar

    标题中的“鼠标掠过主题列表图片附件即时预览插件 for discuz 7.0.rar”指的是一个专为Discuz! 7.0论坛系统设计的增强功能插件。Discuz! 是一款广泛使用的开源社区论坛软件,它允许用户创建和管理在线论坛。这个插件...

Global site tag (gtag.js) - Google Analytics