Office file online preview (JAVA)

Original http://hwl-sz.iteye.com/blog/1964397

1. Preparation before development

1) Download third-party software or plug-ins to install                       openOffice

: Official download: http://www.openoffice.org/download/Baidu.com

Disk: http://pan.baidu.com/s/1mpxdL



      swftools: Official download: http://www.swftools.org/swftools-0.9.0.exe

                      Baidu network disk: http://pan.baidu.com /s/11O0nS



FlexPaper_1.4.5_flash: http://pan.baidu.com/s/1oXmIL



Linux version installation and download see: "openOffice, swftools Installation Guide (Linux).doc"



2) Download the relevant jar package, As shown below:



3) Integrated plug-in

Unzip FlexPaper_1.4.5_flash.zip, and transplant the following files to the web directory, as shown in Figure




2. Write code



Project source code download: [url]http://pan.baidu.com/s/ 18AcnQ [/url]


readfile.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<html>

  <head>

    <meta http-equiv="pragma" content="no-cache">

    <meta http-equiv="cache-control" content="no-cache">

    <meta http-equiv="expires" content="0">   

    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">

  </head>

  <body>

    <form action="uploadServlet" enctype="multipart/form-data" method="post">

        <font style="color:red">Only supports online preview of office files, such as doc,docx,ppt,pptx,xls,xlxs</font></br>

        <input type="file" name="file"/></br>

        <input type="submit" value="Online preview">

    </form>

  </body>

</html>

 

UploadServlet.java

package servlet;

import java.io.File;

import java.io.IOException;

import java.util.List;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;

import org.apache.commons.fileupload.FileUploadException;

import org.apache.commons.fileupload.disk.DiskFileItemFactory;

import org.apache.commons.fileupload.servlet.ServletFileUpload;

import util.Office2Swf;

publicclass UploadServlet extends HttpServlet

{

    privatestaticfinallongserialVersionUID = 1L;

    @Override

    protectedvoid doGet(HttpServletRequest req, HttpServletResponse resp)

           throws ServletException, IOException

    {

       String inputFilePath = this.uploadFile(req);

       if (null != inputFilePath && !"".equals(inputFilePath.trim()))

       {

           String outFilePath = inputFilePath.replace(new File(inputFilePath).getName(), System.currentTimeMillis() + ".swf");

           outFilePath = Office2Swf.office2Swf(inputFilePath, outFilePath);

           req.getSession().setAttribute("fileName", new File(outFilePath).getName());

       }

       req.getRequestDispatcher("/readonline.jsp").forward(req, resp);

    }

   

    @Override

    protectedvoid doPost(HttpServletRequest req, HttpServletResponse resp)

           throws ServletException, IOException

    {

       this.doGet(req, resp);

    }

   

    @SuppressWarnings({"unchecked", "deprecation"})

    private String uploadFile(HttpServletRequest request)throws ServletException, IOException

    {

       request.setCharacterEncoding("utf-8");//Set the encoding

       // get disk file entry factory

       DiskFileItemFactory factory = new DiskFileItemFactory();

       //Get the path to which the file needs to be uploaded

       String path = request.getRealPath("/upload");

       factory.setRepository(new File(path));

       //Set the size of the cache. When the capacity of the uploaded file exceeds the cache, it is directly placed in the temporary storage room

       factory.setSizeThreshold(1024*1024) ;

       // file upload processing

       ServletFileUpload upload = new ServletFileUpload(factory);

      

       String uploadFilePath = null;

       // can upload multiple files

       try {

           List<FileItem> list = (List<FileItem>)upload.parseRequest(request);

           for(FileItem item : list)

           {

              //Get the attribute name of the form

              String name = item.getFieldName();

             

              // form text information

              if(item.isFormField())

              {                

                  String value = item.getString() ;

                  request.setAttribute(name, value);

              }

              // form uploaded file

              else

              {

                  // get the path

                  String value = item.getName() ;

                  int start = value.lastIndexOf("\\");

                  // Intercept upload file name

                  String filename = value.substring(start+1);

                  request.setAttribute(name, filename);

                  item.write(new File(path,filename));

                  uploadFilePath = path + File.separator + filename;

              }

           }

       } catch (FileUploadException e) {

           e.printStackTrace ();

       }

       catch(Exception ex)

       {

           ex.printStackTrace();

       }

       return uploadFilePath;

    }

}

 

Office2PDF.java

package util;

 

import java.io.File;

import java.util.ArrayList;

import java.util.Collections;

import java.util.regex.Pattern;

 

import org.artofsolving.jodconverter.OfficeDocumentConverter;

import org.artofsolving.jodconverter.office.DefaultOfficeManagerConfiguration;

import org.artofsolving.jodconverter.office.OfficeManager;

 

/**

 *

 * @author hwl_sz

 *

 * @desc needs the support of the third plug-in of OpenOffice, and supports windows\linux\mac and other systems

 */

publicclass Office2PDF

{

    publicstaticfinal String[] OFFICE_POSTFIXS = {"doc", "docx", "xls",

       "xlsx", "ppt", "pptx"};

   

    /**

     * According to the name of the operating system, get the installation directory of OpenOffice

     * Such as my installation directory: C:/Program Files/OpenOffice 4

     */

    privatestatic String getOfficeHome()

    {

       String osName = System.getProperty("os.name");

       if (Pattern.matches("Linux.*", osName))

       {

           return"/opt/openoffice.org3";

       }

       elseif (Pattern.matches("Windows.*", osName))

       {

           return"C:/Program Files/OpenOffice 4";

       }

       elseif (Pattern.matches("Mac.*", osName))

       {

           return"/Application/OpenOffice.org.app/Contents";

       }

       returnnull;

    }

 

    /**

     * Convert files

     *

     * @param inputFilePath converted office source file path

     * @param outputFilePath output target file path

     */

    privatestaticvoid converterFile(String inputFilePath, String outputFilePath)

    {

       File inputFile = new File(inputFilePath);

       File outputFile = new File(outputFilePath);

       // If the target path does not exist, create a new path

       if (!outputFile.getParentFile().exists())

       {

           outputFile.getParentFile().mkdirs();

       }

      

       DefaultOfficeManagerConfiguration config = new DefaultOfficeManagerConfiguration();

       // Get the installation directory of OpenOffice

       String officeHome = getOfficeHome();

       config.setOfficeHome(officeHome);

       // Start the OpenOffice service

       OfficeManager officeManager = config.buildOfficeManager();

       officeManager.start();

      

       OfficeDocumentConverter converter = new OfficeDocumentConverter(

              officeManager);

      

       converter.convert(inputFile, outputFile);

       System.out.println("File:" + inputFilePath + "\nConvert to\ntarget file:" + outputFile

              + "\nSuccess!");

      

       officeManager.stop();

    }

 

    /**

     * Convert office files such as (.doc|.docx|.xls|.xlsx|.ppt|.pptx) to pdf files

     *

     * @param inputFilePath source file path to be converted

     * @param outputFilePath output directory file path, if not specified (null), a pdf file with the same name will be generated in the current directory of the source file

     * @return processing result

     */

    publicstaticboolean openOffice2Pdf(String inputFilePath, String outputFilePath)

    {

       boolean flag = false;

       File inputFile = new File(inputFilePath);

       ArrayList<String> office_Formats = new ArrayList<String>();

       Collections.addAll(office_Formats, OFFICE_POSTFIXS);

       if ((null != inputFilePath) && (inputFile.exists()))

       {

           // Check if the target file path is empty

           if (office_Formats.contains(getPostfix(inputFilePath)))

           {

              if (null == outputFilePath)

              {

                  // Converted file path

                  String outputFilePath_new = inputFilePath.toLowerCase().replaceAll("."

                         + getPostfix(inputFilePath), ".pdf");

                  converterFile(inputFilePath, outputFilePath_new);

                  flag = true;

              }

              else

              {

                  converterFile(inputFilePath, outputFilePath);

                  flag = true;

              }

           }

       }

       return flag;

    }

 

 

    /**

     * Get the file extension

     */

    privatestatic String getPostfix(String inputFilePath)

    {

       String[] p = inputFilePath.split("\\.");

       if (p.length > 0)

       {

           return p[p.length - 1];

       }

        else

       {

           returnnull;

       }

    }

 

    /**

     * @param args

     */

    publicstaticvoid main(String[] args)

    {

       Office2PDF.openOffice2Pdf("E:/Yellow Earth Business PPT Template.ppt",null);

    }

}

 

 

Office2Swf.java

package util;

 

import java.util.regex.Pattern;

 

/**

 *

 * @author hwl_sz

 *

 * @desc needs the support of the third plug-in of swftools, which supports windows\linux\mac and other systems

 */

publicclass Office2Swf

{

    /**

     * According to the name of the operating system, get the command to execute the pdf->swf file

     * @param pdfFile Converted pdf source file path

     * @param swfOutFilePath output swf file path

     * @return

     */

    privatestatic String getCommand(String pdfFile, String swfOutFilePath)

    {

       String command = null;

       String osName = System.getProperty("os.name");

       if (null == swfOutFilePath || "".equals(swfOutFilePath.trim()))

       {

           swfOutFilePath = pdfFile.toLowerCase().replaceAll(".pdf", ".swf");

       }

      

       if (Pattern.matches("Linux.*", osName))

       {

           command = "pdf2swf -f " + pdfFile + " " + swfOutFilePath;

       }

       elseif (Pattern.matches("Windows.*", osName))

       {

           command = "C:/Program Files/SWFTools/pdf2swf.exe -t " + pdfFile + " -o "  + swfOutFilePath + " -T 9";

       }

       elseif (Pattern.matches("Mac.*", osName))

       {

       }

       return command;

    }

   

    /**

     * Convert pdf to swf file, preview online

     * @param pdfInputFilePath The path of the pdf source file to be converted

     * @param swfOutFilePath output swf target file path, if not specified (null), the swf file with the same name will be generated in the current directory of the source file

     * @return swf target file path

     */

    publicstatic String pdf2Swf(String pdfInputFilePath, String swfOutFilePath)

    {

       String command = getCommand(pdfInputFilePath, swfOutFilePath);

       try

       {

           Process pro = Runtime.getRuntime().exec(command);

           pro.waitFor();

           return pdfInputFilePath.replaceAll("." + getPostfix(pdfInputFilePath), ".swf");

       }

       catch(Exception ex)

       {

           ex.printStackTrace();

       }

       returnnull;

    }

   

    /**

     * Convert office files directly to swf files

     * @param inputFilePath The path of the source office file to be converted

     * @param outputSwfPath The output swf target file path, if not specified (null), the swf file with the same name will be generated in the current directory of the source file

     * @return swf target file path

     */

    publicstatic String office2Swf(String inputFilePath, String outputSwfPath)

    {

       String outputPdfPath = null;

       if (null == outputSwfPath || "".equals(outputSwfPath.trim()))

       {

           outputPdfPath = inputFilePath.replace("." + getPostfix(inputFilePath), ".pdf");

       }

       else

       {

           outputPdfPath = outputSwfPath.replace("." + getPostfix(outputSwfPath), ".pdf");

       }

      

       boolean isSucc = Office2PDF.openOffice2Pdf(inputFilePath, outputPdfPath);

       if (isSucc)

       {

           outputSwfPath = pdf2Swf(outputPdfPath, outputSwfPath);

       }

       return outputSwfPath;

    }

   

    /**

     * Get the file extension

     */

    privatestatic String getPostfix(String inputFilePath)

    {

       String postfix = null;

       if (null != inputFilePath && !"".equals(inputFilePath.trim()))

       {

           int idx = inputFilePath.lastIndexOf(".");

           if (idx > 0)

           {

              postfix = inputFilePath.substring(idx + 1, inputFilePath.trim().length());

           }

       }

       return postfix;

    }

}

 

readonline.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">  

  <head>

    <title>Online Preview</title>

<script type="text/javascript" src="FlexPaper/js/jquery.js"></script>

<script type="text/javascript" src="FlexPaper/js/flexpaper_flash.js"></script>

<script type="text/javascript" src="FlexPaper/js/flexpaper_flash_debug.js"></script>

  </head>

  <%--  <%=(String)session.getAttribute("fileName")%>  --%>

  <body>

        <div style="position:absolute;left:10px;top:10px;">

        <%-- Specify the width and height of flexPaper--%>  

            <a id="viewerPlaceHolder" style="width:100%;height:800px;display:block"></a>

            <script type="text/javascript">

                var fp = new FlexPaperViewer(   

                         'FlexPaper/swfFiles/FlexPaperViewer',

                         'viewerPlaceHolder', <!--corresponds to the id of the a tag-->

                         { config : {

                         SwfFile : escape('upload/<%=(String)session.getAttribute("fileName")%>'), <!--The path of the imported .swf, the file name is expressed in English, it cannot be displayed in Chinese, temporarily This issue has not been resolved -->

                         Scale : 0.6,

                         ZoomTransition : 'easeOut',

                         ZoomTime: 0.5,

                         ZoomInterval : 0.2,

                         FitPageOnLoad : true,

                         FitWidthOnLoad : false,

                         PrintEnabled : true,<%-- can print --%>

                         FullScreenAsMaxWindow : false,

                         ProgressiveLoading : false,

                         MinZoomSize : 0.2,

                         MaxZoomSize : 5,

                         SearchMatchAll : false,

                         InitViewMode : 'Portrait',

                        

                         ViewModeToolsVisible : true,

                         ZoomToolsVisible : true,

                         NavToolsVisible : true,

                         CursorToolsVisible : true,

                         SearchToolsVisible : true,

                           localeChain: 'en_US'

                         }});

            </script>

        </div>

</body>

</html>



renderings


Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326977588&siteId=291194637