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

Java Implementation of Attachment Preview (openoffice+swftools+flexpaper) Example

This article mainly introduces the implementation of attachment preview in Java, which requires the use of openoffice, SWFTools, and FlexPaper, the specific steps are as follows:

1.Overview

Main principle

1.Convert word, excel, ppt, txt and other files to pdf files through the third-party tool openoffice

2.Convert pdf files to swf format files through swfTools

3.Display on the page through the FlexPaper document component

2.Installation package download

1.openoffice is an open-source free word processing software under Apache

   Download address: Apache openoffice official website download version-3.4.1 http://www.openoffice.org/zh-cn/download/

2.SWFTools is a set of tools for processing Flash swf files, which we use to convert pdf files to swf files!

   Download address: SWFTools official website download swftools-2013-04-09-1007.exe  http://www.swftools.org/download.html

3.FlexPaper is an open-source lightweight component for displaying various documents in the browser

   Download address: FlexPaper official website download version1.5.1  https://flowpaper.com/download/

4.JODConverter is a Java OpenDocument file converter, in which we only use its jar package

   Download address: JODCConverter download  https://sourceforge.net/projects/jodconverter/files/

3.Installation file

1.Install the downloaded files (excluding JODConverter), the drive letter can be set as desired! It should be noted that after the openoffice installation is complete, when we use it, we need to open its service. In this case, we need to open it in command mode:

Open the DOS window, navigate to the drive letter of the openoffice installation disk, and enter the following code to start the service:

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

Note that the hyphen before the last command should not be written incorrectly! If the service cannot start, the project cannot continue.

Official website service start screenshot as follows:

Local screenshot:

3.Development process

1.New project, copy the js folder in the flexpaper file (which includes flexpaper_flash_debug.js, flexpaper_flash.js, jquery.js, these three js files are mainly used as plugins to preview swf files) to the root directory of the website; copy FlexPaperViewer.swf to the root directory of the website (this file is mainly used for playing swf files in web pages), the directory structure is as shown in the figure below:

Note: You need to create the upload folder

2.Create 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>Online Document Preview System</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"> 
      Please upload the file to be processed, the process may take a few minutes, please wait a moment. 
    </div> 
    <p> 
      <input name="file1" type="file"> 
    </p> 
    <p> 
      <input type="submit" name="Submit" value="Upload"> 
    </p> 
  </form > 
</div> 
</body> 
</html>

3.Create the conversion page 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"%> 
<% 
//File upload uses the cos component for upload, it can be replaced with commons-fileupload upload, after the file is uploaded, it is saved in the upload folder 
//Get the file upload path 
String saveDirectory = application.getRealPath("/")+"upload"; 
//Print the upload path information 
System.out.println(saveDirectory); 
//Each file's maximum size50m 
int maxPostSize = 50 * 1024 * 1024 ; 
//Use the default naming strategy of cos, add a suffix after renaming1,2,3...if dfp is not used, the original name will be overwritten 
DefaultFileRenamePolicy dfp = new DefaultFileRenamePolicy(); 
//response encoding is "UTF-8",and use the default file name conflict resolution strategy to implement upload, if dfp is not used, the original name will be overwritten 
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 extension name of the uploaded file 
     String extName=fileName.substring(fileName.lastIndexOf(".")+1); 
     //Full file path 
     String lastFileName= saveDirectory+"\\" + fileName; 
     //Get the name of the file to be converted, replace the path name '\' with '"/' 
     String converfilename = saveDirectory.replaceAll("\\\\", "/")+"/"+fileName; 
     System.out.println(converfilename); 
     //Call the conversion class 'DocConverter' and pass the file to be converted to the constructor of the class 
     DocConverter d = new DocConverter(converfilename); 
     //Call the 'conver' method to start conversion, first execute 'doc'2The 'pdf()' function converts office files to PDF; then execute 'pdf'2swf() converts pdf to swf; 
     d.conver(); 
     //Call the getswfPath() method and print the converted swf file path 
     System.out.println(d.getswfPath()); 
     //Generate the relative path of swf for passing to the flexpaper player 
     String swfpath = "upload"+d.getswfPath().substring(d.getswfPath().lastIndexOf("/")); 
     System.out.println(swfpath); 
     //Place the relative path into the session and save it 
     session.setAttribute("swfpath", swfpath); 
     out.println("Uploaded file:"+lastFileName); 
     out.println("File type"+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='Preview' class='BUTTON SUBMIT'>/> 
    </form> 
  </div> 
</body> 
</html>

Create the view page 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>Online Document Preview System</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.Create conversion class 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 format conversion 
 */ 
public class DocConverter { 
  private static final int environment = 1;// Environment 1:windows 2:linux 
  private String fileString;// (Only involves pdf2SWF path issue) 
  private String outputPath = "";// Input path, if not set, output at the default location 
  private String fileName; 
  private File pdfFile; 
  private File swfFile; 
  private File docFile; 
  public DocConverter(String fileString) { 
    ini(fileString); 
  } 
  /** 
   * Reset file 
   * 
   * @param fileString 
   */ 
  public void setFile(String fileString) { 
    ini(fileString); 
  } 
  /** 
   * Initialization 
   * 
   * @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 + ".swf"); 
  } 
  /** 
   * Convert to 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 conversion successful, PDF output: " + pdfFile.getPath()+ "****"); 
        } 
          e.printStackTrace(); 
          System.out.println("****An exception occurred in the SWF converter, the OpenOffice service has not been started!****"); 
          throw e; 
        catch (com.artofsolving.jodconverter.openoffice.connection.OpenOfficeException e) { 
          e.printStackTrace(); 
          System.out.println("****SWF converter exception, failed to read conversion file****"); 
          throw e; 
        } 
          e.printStackTrace(); 
          throw e; 
        } 
      } 
        System.out.println("****Already converted to PDF, no need for further conversion****"); 
      } 
    } 
      System.out.println("****SWF converter exception, the document to be converted does not exist, conversion is not possible****"); 
    } 
  } 
  /** 
   * Convert to swf 
   */ 
  @SuppressWarnings("unused") 
  private void pdf2swf() throws Exception { 
    Runtime r = Runtime.getRuntime(); 
    if (!swfFile.exists()) { 
      if (pdfFile.exists()) { 
        if (environment == 1) {}}// Windows environment processing 
          try { 
            Process p = r.exec("D:/Program Files/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 conversion successful, file output: " 
                + swfFile.getPath() + "****"); 
            if (pdfFile.exists()) { 
              pdfFile.delete(); 
            } 
          } catch (IOException e) { 
            e.printStackTrace(); 
            throw e; 
          } 
        } else if (environment == 2) {}}// Linux environment processing 
          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 conversion successful, file output: " 
                + swfFile.getPath() + "****"); 
            if (pdfFile.exists()) { 
              pdfFile.delete(); 
            } 
          } 
            e.printStackTrace(); 
            throw e; 
          } 
        } 
      } 
        System.out.println("****The PDF does not exist, conversion is not possible****"); 
      } 
    } 
      System.out.println("****The SWF already exists, no conversion is needed****"); 
    } 
  } 
  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(); 
  } 
  /** 
   * Conversion main method 
   */ 
  @SuppressWarnings("unused") 
  public boolean conver() { 
    if (swfFile.exists()) { 
      System.out.println("****The SWF converter starts working, and the file has been converted to SWF****"); 
      return true; 
    } 
    if (environment == 1) {}} 
      System.out.println("****The swf converter starts working, the current running environment is windows****"); 
    } 
      System.out.println("****The swf converter starts working, the current running environment is linux****"); 
    } 
    try { 
      doc2pdf(); 
      pdf2swf(); 
    } 
      e.printStackTrace(); 
      return false; 
    } 
    if (swfFile.exists()) { 
      return true; 
    } 
      return false; 
    } 
  } 
  /** 
   * Return the file path 
   * 
   * @param s 
   */ 
  public String getswfPath() { 
    if (swfFile.exists()) { 
      String tempString = swfFile.getPath(); 
      tempString = tempString.replaceAll("\\\\", "/"); 
      return tempString; 
    } 
      return ""; 
    } 
  } 
  /** 
   * Set the output path 
   */ 
  public void setOutputPath(String outputPath) { 
    this.outputPath = outputPath; 
    if (!outputPath.equals("")) { 
      String realName = fileName.substring(fileName.lastIndexOf("/" 
          fileName.lastIndexOf(".")); 
      if (outputPath.charAt(outputPath.length() - 1) == '/}) { 
        swfFile = new File(outputPath + realName + ".swf"); 
      } 
        swfFile = new File(outputPath + realName + ".swf"); 
      } 
    } 
  } 
}

6.Deploy and publish

Start tomcat and deploy the current web application

Enter the address in the address barhttp://localhost:8080/ctcesims/documentUpload.jsp As shown below:

Click the preview button, and a preview interface will be generated as shown below:

4.Frequently Asked Questions

If the swf cannot be previewed, please visit

http://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager04a.html#119065

Set the folder where the swf is generated as a trusted file location.
The following provides flexpaper 2.1.9 The differences are: the initialization method has changed, if the file directory is not in the same directory as the project directory, you can set the attachment directory as a virtual directory in the server

<%@ 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>Online Document Preview System</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. Hope it will be helpful to your study, and also hope that everyone will support the Yelling Tutorial more.

Statement: 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 spontaneously. This website does not own the copyright, 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#oldtoolbag.com (Please replace # with @ when sending an email for reporting, and provide relevant evidence. Once verified, this site will immediately delete the content suspected of infringement.)

You May Also Like