English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

java实现附件预览(openoffice+swftools+flexpaper)实例

Dieser Artikel beschreibt die Implementierung von Anhängevorschau in Java, die OpenOffice, SWFTools und FlexPaper erfordert. Die spezifischen Schritte sind wie folgt:

1Zusammenfassung

Haupt原理

1Durch den OpenOffice-Dienstleister Word, Excel, PPT, TXT und andere Dateien in PDF-Dateien umwandeln

2Durch SWFTools PDF-Dateien in SWF-Dateiformat umwandeln

3Durch die FlexPaper-Dokumentkomponente auf der Seite angezeigt

2Installationspaket herunterladen

1OpenOffice ist ein unter Apache stehendes offenes und kostenloses Textverarbeitungsprogramm

   Download-Adresse: Apache OpenOffice-Webseite herunterladen Version-3.4.1 http://www.openoffice.org/zh-cn/download/

2SWFTools ist ein Set von Werkzeugen zur Verarbeitung von Flash-SWF-Dateien, die wir verwenden, um PDF-Dateien in SWF-Dateien umzuwandeln!

   Download-Adresse: SWFTools-Webseite herunterladen swftools-2013-04-09-1007.exe  http://www.swftools.org/download.html

3FlexPaper ist ein Open-Source-Lightweight-Komponente, die verschiedene Dokumente im Browser anzeigt

   Download-Adresse: FlexPaper-Webseite herunterladen Version1.5.1  https://flowpaper.com/download/

4JODConverter ist ein Java-basierter OpenDocument-Datei-Konverter, den wir hier nur für seine Jar-Datei verwenden

   Download-Adresse: JODCConverter Download  https://sourceforge.net/Projekte/jodconverter/Dateien/

3Installationsdatei

1Installieren Sie die heruntergeladenen Dateien (ausgenommen JODConverter), das Laufwerk kann nach eigenem Ermessen festgelegt werden! Zu beachten ist, dass nach der Installation von OpenOffice, wenn wir es verwenden, der Dienst geöffnet werden muss. Diesmal müssen wir den Dienst auf Befehlszeilebene öffnen:

Öffnen Sie ein DOS-Fenster, navigieren Sie in das Verzeichnis der OpenOffice-Installationsdiskette und geben Sie folgenden Code ein, um den Dienst zu starten:

soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;" -nofirststartwizard

Achtung: Der vorletzte Befehl beginnt mit einem ‘—', dies darf nicht falsch geschrieben werden! Wenn der Dienst nicht startet, kann das Projekt nicht fortgesetzt werden.

Screenshot des Dienststarts auf der offiziellen Website wie folgt:

Lokale Screenshots:

3.Entwicklung

1.Erstellen Sie ein neues Projekt, kopieren Sie das js-Verzeichnis aus der Datei flexpaper (enthielt flexpaper_flash_debug.js, flexpaper_flash.js, jquery.js, diese js-Dateien sind Plugins zum Vorschauen von swf-Dateien) in den Stammverzeichnis der Website; kopieren Sie FlexPaperViewer.swf in das Stammverzeichnis der Website (dieses Datei wird hauptsächlich zum Abspielen von swf-Dateien in Webseiten verwendet), Verzeichnisstruktur wie folgt:

Hinweis: Erstellen Sie das Verzeichnis upload

2.erstellen Sie fileUpload.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" 
  pageEncoding="UTF-8"%> 
!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
<title>文档在线预览系统</title> 
<style> 
  body {margin-top:100px;background:#fff;font-family: Verdana, Tahoma;} 
  a {color:#CE4614;} 
  #msg-box {color: #CE4614; font-size:0.9em;text-align:center;} 
  #msg-box .logo {border-bottom:5px solid #ECE5D9;margin-bottom:20px;padding-bottom:10px;} 
  #msg-box .title {font-size:1.4em;font-weight:bold;margin:0 0 30px 0;} 
  #msg-box .nav {margin-top:20px;} 
</style> 
</head> 
<body> 
<div id="msg-box"> 
  <form name="form1" method="post" enctype="multipart/form-data" action="docUploadConvertAction.jsp"> 
    <div class="title"> 
      Bitte laden Sie die zu verarbeitende Datei hoch, der Prozess kann einige Minuten dauern, bitte haben Sie etwas Geduld. 
    </div> 
    <p> 
      <input name="file1" type="file"> 
    </p> 
    <p> 
      <input type="submit" name="Submit" value="Upload"> 
    </p> 
  </form > 
</div> 
</body> 
</html>

3.erstellen Sie die Umwandlungsseite docUploadConvertAction.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> 
<%@page import="java.io."*"%> 
<%@page import="java.util.Enumeration"%> 
<%@page import="com.oreilly.servlet.MultipartRequest"%> 
<%@page import="com.oreilly.servlet.multipart.DefaultFileRenamePolicy"%> 
<%@page import="com.cectsims.util.DocConverter"%> 
<% 
//Das Dateiupload verwendet das cos-Componenten-Upload, kann jedoch durch commons ersetzt werden-fileupload Upload, nach dem Upload der Datei wird sie im upload-Verzeichnis gespeichert 
//Erfassen Sie den Pfad für die Dateiupload 
String saveDirectory = application.getRealPath("/")+"upload"; 
//Print the upload path information 
System.out.println(saveDirectory); 
//Each file maximum50m 
int maxPostSize = 50 * 1024 * 1024 ; 
//Using the default naming strategy of cos, append with1,2,3...if dfp rename is not added, it will overwrite 
DefaultFileRenamePolicy dfp = new DefaultFileRenamePolicy(); 
//response encoding is "UTF-8,
using the default filename conflict resolution strategy to implement upload, if dfp rename is not added, it will overwrite 
MultipartRequest multi = new MultipartRequest(request, saveDirectory, maxPostSize,"UTF-8,
"",dfp);
 
//MultipartRequest multi = new MultipartRequest(request, saveDirectory, maxPostSize,"UTF-8"); 
//Output feedback information 
 Enumeration files = multi.getFileNames(); 
   while (files.hasMoreElements()) { 
    System.err.println("ccc"); 
    String name = (String)files.nextElement(); 
    File f = multi.getFile(name); 
    if(f!=null){ 
     String fileName = multi.getFilesystemName(name); 
     //Get the file extension of the uploaded file 
     String extName=fileName.substring(fileName.lastIndexOf(".")+1); 
     //Full file path 
     String lastFileName= saveDirectory+"\\" + fileName; 
     //Get the file name to be converted, replace the path name with '\' with '/' 
     String converfilename = saveDirectory.replaceAll("\\\\", "/")+"/"+fileName; 
     System.out.println(converfilename); 
     //Invoke the conversion class DocConverter and pass the file to be converted to the constructor of the class 
     DocConverter d = new DocConverter(converfilename); 
     //Invoke the conver method to start conversion, first execute doc2pdf() converts office files to pdf; then execute pdf2swf()将pdf转换为swf; 
     d.conver(); 
     //调用getswfPath()方法,打印转换后的swf文件路径 
     System.out.println(d.getswfPath()); 
     //生成swf相对路径,以便传递给flexpaper播放器 
     String swfpath = "upload"+d.getswfPath().substring(d.getswfPath().lastIndexOf("/")); 
     System.out.println(swfpath); 
     //将相对路径放入sessio中保存 
     session.setAttribute("swfpath", swfpath); 
     out.println("上传的文件:"+lastFileName); 
     out.println("文件类型"+extName); 
     out.println("<hr>"); 
    } 
   } 
%> 
!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
<title>Insert title here</title> 
<style> 
  body {margin-top:100px;background:#fff;font-family: Verdana, Tahoma;} 
  a {color:#CE4614;} 
  #msg-box {color: #CE4614; font-size:0.9em;text-align:center;} 
  #msg-box .logo {border-bottom:5px solid #ECE5D9;margin-bottom:20px;padding-bottom:10px;} 
  #msg-box .title {font-size:1.4em;font-weight:bold;margin:0 0 30px 0;} 
  #msg-box .nav {margin-top:20px;} 
</style> 
</head> 
<body> 
  <div> 
    <form name="viewForm" id="form_swf" action="documentView.jsp" method="POST"> 
      <input type='submit' value='预览' class='BUTTON SUBMIT'/> 
    </form> 
  </div> 
</body> 
</html>

创建查看页documentView.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> 
<% 
  String swfFilePath=session.getAttribute("swfpath").toString(); 
%> 
!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
<script type="text/javascript" src="js/jquery.js"></script> 
<script type="text/javascript" src="js/flexpaper_flash.js"></script> 
<script type="text/javascript" src="js/flexpaper_flash_debug.js"></script> 
<style type="text/css" media="screen">  
      html, body { height:100%; } 
      body { margin:0; padding:0; overflow:auto; }   
      #flashContent { display:none; } 
    </style>  
<title>文档在线预览系统</title> 
</head> 
<body>  
    <div style="position:absolute;left:50px;top:10px;"> 
      <a id="viewerPlaceHolder" style="width:820px;height:650px;display:block"></a> 
      <script type="text/javascript">  
        var fp = new FlexPaperViewer(   
             'FlexPaperViewer', 
             'viewerPlaceHolder', { config : { 
             SwfFile : escape('<%=swfFilePath%>'), 
             Scale : 0.6,  
             ZoomTransition : 'easeOut', 
             ZoomTime : 0.5, 
             ZoomInterval : 0.2, 
             FitPageOnLoad : true, 
             FitWidthOnLoad : false, 
             FullScreenAsMaxWindow : false, 
             ProgressiveLoading : false, 
             MinZoomSize : 0.2, 
             MaxZoomSize : 5, 
             SearchMatchAll : false, 
             InitViewMode : 'SinglePage', 
             ViewModeToolsVisible : true, 
             ZoomToolsVisible : true, 
             NavToolsVisible : true, 
             CursorToolsVisible : true, 
             SearchToolsVisible : true, 
             localeChain: 'en_US' 
             }}); 
      </script>       
    </div> 
</body> 
</html>

5.创建转换类DocConverter.java

package com.cectsims.util; 
import java.io.BufferedInputStream; 
import java.io.File; 
import java.io.IOException; 
import java.io.InputStream; 
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; 
/** 
 * doc docx格式转换 
 */ 
public class DocConverter { 
  private static final int environment = 1;// 环境 1:windows 2:linux 
  private String fileString;// (只涉及pdf2swf路径问题) 
  private String outputPath = "";// 输入路径,如果不设置就输出在默认的位置 
  private String fileName; 
  private File swfFile; 
  private File docFile; 
  public DocConverter(String fileString) { 
  file neu setzen 
    Initialisierung 
  } 
  /** 
   * public void setFile(String fileString) { 
   * 
   * private void ini(String fileString) { 
   */ 
  ini(fileString); 
    Initialisierung 
  } 
  /** 
   * @param fileString 
   * 
   * private void ini(String fileString) { 
   */ 
  this.fileString = fileString; 
    fileName = fileString.substring(0, fileString.lastIndexOf(".")); 
    docFile = new File(fileString); 
    pdfFile = new File(fileName 
    ".pdf"); + swfFile = new File(fileName 
    in PDF umwandeln + ".swf"); 
  } 
  /** 
   * @param file 
   * 
   * private void doc 
   */ 
  pdf() throws Exception {2if (docFile.exists()) { 
    if (!pdfFile.exists()) { 
      OpenOfficeConnection connection = new SocketOpenOfficeConnection( 
        0);810connection.connect(); 
        try { 
          DocumentConverter converter = new OpenOfficeDocumentConverter(connection); 
          converter.convert(docFile, pdfFile); 
          close the connection 
          // connection.disconnect(); 
          PDF-Conversion erfolgreich, PDF-Ausgabe: " 
          System.out.println("****catch (java.net.ConnectException e) { + pdfFile.getPath()+ "****"); 
        } 
          e.printStackTrace(); 
          System.out.println("****SWF-Converter-Fehler: OpenOffice-Dienst ist nicht gestartet!****"); 
          throw e; 
        catch (com.artofsolving.jodconverter.openoffice.connection.OpenOfficeException e) { 
          e.printStackTrace(); 
          System.out.println("****SWF-Konverter-Exception, Lesefehler beim Umwandlungsdatei****"); 
          throw e; 
        } catch (Exception e) { 
          e.printStackTrace(); 
          throw e; 
        } 
      } else { 
        System.out.println("****Bereits in PDF umgewandelt, keine weitere Konvertierung erforderlich****"); 
      } 
    } else { 
      System.out.println("****SWF-Konverter-Exception, das zu konvertierende Dokument existiert nicht, die Umwandlung ist nicht möglich****"); 
    } 
  } 
  /** 
   * in SWF umwandeln 
   */ 
  @SuppressWarnings("unused") 
  private void pdf2swf() throws Exception { 
    Runtime r = Runtime.getRuntime(); 
    if (!swfFile.exists()) { 
      if (pdfFile.exists()) { 
        if (environment == 1) {// Windows-Umgebungsbearbeitung 
          try { 
            Process p = r.exec("D:/Programme/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-Umwandlung erfolgreich, Datei ausgegeben: " 
                + swfFile.getPath() + "****"); 
            if (pdfFile.exists()) { 
              pdfFile.delete(); 
            } 
          } catch (IOException e) { 
            e.printStackTrace(); 
            throw e; 
          } 
        } else if (environment == 2) {// Linux-Umgebungsbearbeitung 
          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-Umwandlung erfolgreich, Datei ausgegeben: " 
                + swfFile.getPath() + "****"); 
            if (pdfFile.exists()) { 
              pdfFile.delete(); 
            } 
          } catch (Exception e) { 
            e.printStackTrace(); 
            throw e; 
          } 
        } 
      } else { 
        System.out.println("****Das PDF existiert nicht, die Umwandlung ist nicht möglich****"); 
      } 
    } else { 
      System.out.println("****Der SWF existiert bereits und muss nicht umgewandelt werden****"); 
    } 
  } 
  static String loadStream(InputStream in) throws IOException { 
    int ptr = 0; 
    in = new BufferedInputStream(in); 
    StringBuffer buffer = new StringBuffer(); 
    while ((ptr = in.read()) != -1) { 
      buffer.append((char) ptr); 
    } 
    return buffer.toString(); 
  } 
  /** 
   * Umwandlungshauptmethode 
   */ 
  @SuppressWarnings("unused") 
  public boolean conver() { 
    if (swfFile.exists()) { 
      System.out.println("****Der SWF-Konverter beginnt zu arbeiten, die Datei wurde in SWF umgewandelt****"); 
      return true; 
    } 
    if (environment == 1) { 
      System.out.println("****swf转换器开始工作,当前设置运行环境windows****"); 
    } else { 
      System.out.println("****swf转换器开始工作,当前设置运行环境linux****"); 
    } 
    try { 
      doc2pdf(); 
      pdf2swf(); 
    } catch (Exception e) { 
      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("")) { 
      / 
          fileName.lastIndexOf(".")); 
      if (outputPath.charAt(outputPath.length() - 1) == '/') { 
        swfFile = new File(outputPath + realName + ".swf"); 
      } else { 
        swfFile = new File(outputPath + realName + ".swf"); 
      } 
    } 
  } 
}

6部署发布。

启动tomcat,部署当前web应用

地址栏输入http://localhost:8080/ctcesims/documentUpload.jsp 如下图:

单击预览按钮,就会生成预览界面,如下图:

4常见问题。

若出现swf无法预览,请访问

http://www.macromedia.com/支持/文档/en/flashplayer/帮助/settings_manager04a.html#119065

将生成swf的文件夹设置为信任文件位置。
以下给出 flexpaper 2.1.9 的不同之处:初始化方式改变,若文件目录与项目目录不在一起,可将附件目录在服务器中设置为虚拟目录

<%@ page language="java" contentType="text/html; charset=UTF-8"
  pageEncoding="UTF-8"%>
<%
  //String swfFilePath=session.getAttribute("swfpath").toString();
%>
!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/flexpaper.js"></script>
<script type="text/javascript" src="js/flexpaper_handlers.js"></script>
<style type="text/css" media="screen"> 
      html, body  { height:100%; }
      body { margin:0; padding:0; overflow:auto; }  
      #flashContent { display:none; }
    </style> 
<title>文档在线预览系统</title>
</head>
<body> 
    <div style="position:absolute;left:50px;top:10px;">
      <div id="documentViewer" class="flexpaper_viewer" style="width:770px;height:500px"></div>
      <script type="text/javascript"> 
      var startDocument = "Paper";
      $('#documentViewer').FlexPaperViewer(
          { config : {
            SWFFile : 'upload/ddd3.swf',
            Scale : 0.6,
            ZoomTransition : 'easeOut',
            ZoomTime : 0.5,
            ZoomInterval : 0.2,
            FitPageOnLoad : true,
            FitWidthOnLoad : false,
            FullScreenAsMaxWindow : false,
            ProgressiveLoading : false,
            MinZoomSize : 0.2,
            MaxZoomSize : 5,
            SearchMatchAll : false,
            InitViewMode : 'Portrait',
            RenderingOrder : 'flash',
            StartAtPage : '',
            ViewModeToolsVisible : true,
            ZoomToolsVisible : true,
            NavToolsVisible : true,
            CursorToolsVisible : true,
            SearchToolsVisible : true,
            WMode : 'window',
            localeChain: 'en_US'
          }}
      );
      </script>      
    </div>
</body>
</html>

Finally, if you need to remove the print function and logo, you can recompile the flexpaper flash file, and there are also downloads available on the Internet

That's all for this article, I hope it will be helpful to everyone's learning, and I also hope everyone will support the Yelling Tutorial more.

Declaration: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users, and this website does not own the copyright. It has not been manually edited and does not assume any relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#w3Please report via email to codebox.com (replace # with @) when reporting, and provide relevant evidence. Once verified, this site will immediately delete the infringing content.