This article mainly introduces the Java implementation of attachment preview, which requires openoffice, SWFTools, and FlexPaper. The specific steps are as follows:
1. Overview
Main Principles
1. Convert word, excel, ppt, txt and other files into pdf files through third-party tool openoffice
2. Convert pdf file to swf format file through swfTools
3. Display on the page through the FlexPaper document component
2. Download the installation package
1.openoffice is an open and free word processing software under Apache
Download address: Apache oppenoffice official website download version - 3.4.1 http://www.openoffice.org/zh-cn/download/
2. SWFTools is a set of toolkits used to process swf files of Flash. We use it to convert pdf files into 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 that displays various documents on the browser.
Download address: FlexPaper official website download version 1.5.1 https://flowpaper.com/download/
4.JODConverter A Java OpenDocument file converter, where we only use its jar package
Download address: JODCConverter Download https://sourceforge.net/projects/jodconverter/files/
3. Install the file
1. Install the downloaded file (except JODConverter), and the drive letter can be set as you want! It should be noted that after the installation of openoffice is completed, when we use it, we need to open its service. Then we need to open it in the command:
Open the dos window, enter the openoffice installation drive letter, and enter the following code to start the service:
software -headless -accept="socket,host=127.0.0.1,port=8100;urp;" -nofirststartwizard
Pay attention to the '-' in front of the last command, don't write it wrong! If you can't get a service, the project cannot continue.
The screenshot of the official website launch service is as follows:
Local screenshot:
3. Development process
1. Create a new project and copy the js folder in the flexpaper file (including flexpaper_flash_debug.js, flexpaper_flash.js, jquery.js, these three js files are mainly plug-ins for preview swf files) to the website root directory; copy FlexPaperViewer.swf to the website root directory (the file is mainly used as a player that plays swf files on web pages). The directory structure is as follows:
Note: You need to create an 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> Document online 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> Please upload the file to be processed. The process may take several minutes. Please wait for 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 a 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"%> <%@page import="com.cectsims.util.DocConverter"%> <%@page import="com.cectsims.util.DocConverter"%> <% //File upload is uploaded using the cos component, which can be replaced with commons-fileupload upload. After the file is uploaded, save it 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 maximum 50m int maxPostSize = 50 * 1024 * 1024 ; //Use the default naming strategy of cos, add 1, 2, 3 after the duplicate name... If you do not add dfp and duplicate name, it will overwrite DefaultFileRenamePolicy dfp = new DefaultFileRenamePolicy(); //The encoding of response is "UTF-8", and the default file name conflict resolution strategy is used to implement upload. If the dfp duplicate name is not added, the MultipartRequest 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 of the uploaded file String extName=fileName.substring(fileName.lastIndexOf(".")+1); //File full path String lastFileName= saveDirectory+"//" + fileName; //Get the file name that needs to be converted, and replace '/' in 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 this class DocConverter d = new DocConverter(converfilename); //Call the convert method to start the conversion, first execute doc2pdf() to convert the office file to pdf; then execute pdf2swf() to convert the pdf to swf; d.conver(); //Cell getswfPath() method and print the converted swf file path System.out.println(d.getswfPath()); //Generate swf relative paths to pass to flexpaper player String swfpath = "upload"+d.getswfPath().substring(d.getswfPath().lastIndexOf("/")); System.out.println(swfpath); //Put the relative path into 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 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>Document Online Preview System</title> </head> <body> <div style="position:absolute;left:50px;top:10px;"> <a id="viewerPlaceHolder"></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 the 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 issues) private String outputPath = "";// Input path, if not set, output is 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); } /** * Initialize* * @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 is successful, PDF output: " + pdfFile.getPath()+ "****"); } catch (java.net.ConnectException e) { e.printStackTrace(); System.out.println("****swf converter exception, openoffice service has not started! ****"); throw e; } catch (com.artofsolving.jodconverter.openoffice.connection.OpenOfficeException e) { e.printStackTrace(); System.out.println("****swf converter exception, reading the conversion file failed****"); throw e; } catch (Exception e) { e.printStackTrace(); throw e; } } else { System.out.println("**** has been converted to pdf, no conversion is required****"); } } else { System.out.println("****swf converter exception, the document that needs to be converted does not exist, and cannot be converted ****"); } } /** * 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 is 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 is successful, file output: " + swfFile.getPath() + "****"); if (pdfFile.exists()) { pdfFile.delete(); } } catch (Exception e) { e.printStackTrace(); throw e; } } } else { System.out.println("****pdf does not exist, cannot be converted ****"); } } else { System.out.println("****swf already exists and does not need to convert ****"); } } 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(); } /** * Convert main method*/ @SuppressWarnings("unused") public boolean convert() { if (swfFile.exists()) { System.out.println("****swf converter starts working, the file has been converted to swf****"); return true; } if (environment == 1) { System.out.println("****swf converter starts working, the current running environment windows****"); } else { System.out.println("****swf converter starts working, the current running environment linux****"); } try { doc2pdf(); pdf2swf(); } catch (Exception e) { e.printStackTrace(); return false; } if (swfFile.exists()) { return true; } else { return false; } } /** * Return file path* * @param s */ public String getswfPath() { if (swfFile.exists()) { String tempString = swfFile.getPath(); tempString = tempString.replaceAll("////", "/"); return tempString; } else { 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()) == '/') { swfFile = new File(outputPath + realName + ".swf"); } else { swfFile = new File(outputPath + realName + ".swf"); } } } }6. Deployment and release
Start tomcat and deploy the current web application
Enter http://localhost:8080/ctcesims/documentUpload.jsp in the address bar as shown below:
Click the preview button and a preview interface will be generated, as shown in the figure below:
4. Frequently Asked Questions
If swf appears, you cannot preview it, please visit
http://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager04a.html#119065
Set the folder where swfs is generated as the trust file location.
The following gives the difference between flexpaper 2.1.9: the initialization method is changed. If the file directory is not together with the project directory, the attachment directory can be set 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>Document Online Preview System</title></head><body> <div style="position:absolute;left:50px;top:10px;"> <div id="documentViewer"></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 printing function and logo, you can recompile the flash file of flexpaper, and download it online.
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.