javaweb:springmvc+swfTools+FlexPaper文檔在線預覽及問題解決(FlexPaper加載一直轉圈)

        接手公司項目,其中存在文檔預覽功能發現不好使,前者沒有詳細文檔,各種調試爬坑,走出來-————

具體需求是:針對上傳的各種office文件(包括.excel,.doc,.docx等)可以下載亦可以在線預覽;

寫博客的時候有時無暇顧及一些小細節,給讀者帶來疑問也很正常,所以在看一些博客的時候,多琢磨,不要着急;

實現涉及技術:

 

利用openOffice把word、excel、txt等類型的文檔轉換成pdf;

再借助swftools將pdf轉換成swf;

然後利用FlexPaper插件實現在線播放預覽;

所以需要藉助一些工具,先得做好準備工作:

1.openoffice是Apache下的一個開放免費的文字處理軟件

  下載地址:http://www.openoffice.org/zh-cn/download/

 

2.SWFTools是一組用來處理Flash的swf文件的工具包,我們使用它將pdf文件轉成swf文件!

  下載地址:http://www.swftools.org/download.html

 

3.FlexPaper是一個開源輕量級的在瀏覽器上顯示各種文檔的組件

  下載地址:FlexPaper官網下載

 

注意:現在的官網下載具體地址我也沒找到,網上有很多免費的demo,可以下載下來,裏面的jsp,js複製過來用就ok了;

4.JODConverter一個Java的OpenDocument文件轉換器,在此我們只用到它的jar包

   下載地址:JODCConverter下載

注意,如果用jodconverter2.2.1不支持doc,需要替換爲2.2.2

下載好後

將所下載的文件(JODConverter除外)進行安裝,盤符可隨自己設定!需要注意的是在openoffice安裝完成後,當我們使用它時,需將它的服務打開。在次我們需要以命令的方式打開:

可以編寫一個.bat腳本來運行,注意如果不是默認路徑替換成你自己的路徑:

cd /
cd "Program Files (x86)"
cd "OpenOffice 4"
cd program

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

直接執行.bat就行或者手動:

打開cmd窗口,進入openoffice安裝盤符,輸入以下代碼來啓動服務:

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

注意最後一個命令前邊的‘—’,可不要寫錯!服務起不來,項目可是繼續不下去的哦.

檢查8100有沒有被監聽:netstat -ano | find /i "8100"

或者查看進程:

說明已經啓動;

開發過程:

由於一般當你用到這個功能時候,可能你的上傳下載都已經寫好了,至於上傳下載那些個就不說了,我這裏是之前別人寫的項目,沒有從零開始,

也就不一一敘述了,如果你是新搭建的項目從零開始,那麼可以參照https://blog.csdn.net/pangxiao/article/details/78909289還是挺全面的;

我這裏直接上項目代碼及注意事項:

其中下載的

https://sourceforge.net/projects/jodconverter/files/

lib下面的jar包都搞到項目裏面去;

上面是用到的jar;

頁面(上傳我就不展示了啊):

<table  border="0" cellpadding="0" cellspacing="0" class="myTable">
				<tbody>
					<c:forEach items="${aList }" var="item">
					<tr>
						<td>
						    <span class="mySpanFile">
						         <img alt="" src="${item.tagId }" style="width: 30px;height: 30px;margin: 5px 10px 5px 10px;">
						   </span>
						 </td>
						 <td style="width: 160px;">
						   <span class="mySpanFile">
						   
						     <span style="overflow: hidden; text-overflow: ellipsis;-o-text-overflow: ellipsis;white-space:nowrap;width: 150px;display: block; ">
						      	${item.orgName }
						        </span>
						      </span>
						      <span>(${item.sizeKB }kb)</span>
						  </td>
					    <td style="min-width: 10px;">
					      <span class="mySpanFile">
					    		<a  style="text-decoration:underline;" href="javascript:;" target="_blank" class="preview" data-id="${item.appendixId }">預覽</a>
					      </span>
					    </td>
					    <td style="min-width: 10px;" >
					      <span class="mySpanFile">
					    		<a style="margin-left: 15px;text-decoration:underline;" href="javascript:;" class="uploadFile" data-id="${item.appendixId }">下載</a>
					      </span>
					    </td>
					    <td>
					      <span <c:if test="${del=='n' }">style="display: none;"</c:if> class="mySpanFile" >
					    		<a href="javascript:;" style="text-decoration:underline;" class="fileDel" data-id="${item.appendixId } " >刪除</a>
					      </span>
					    </td>
					</tr>
					</c:forEach>
				</tbody>
			</table>

點擊預覽按鈕:對應controller:

/**
	 * 預覽:
	 * @param id
	 * @param request
	 * @param response
	 * @return
	 */
	//@CrossOrigin
	@RequestMapping(value="preview",method = RequestMethod.GET)
	public String preview(Integer id,HttpServletRequest request,HttpServletResponse response){
		String str=   appendixService.preview(id, request);
		if(str.equals("img")){
			return "bjdb/charge/approval/IMGView";	
		}else{
			return "bjdb/charge/approval/documnetView";
		}
		
	}

其中preview對應實現:

@Override
	public String preview(Integer id,HttpServletRequest request) {
		AppendixBean append = appendixBeanMapper.selectByPrimaryKey(id);
		String parentP = PropertySetting.getValue("default", "global", "attach-path");
    	String childenP = PropertySetting.getValue("default", "global", "attach-childen-path");
    	String img = PropertySetting.getValue("default", "global", "image");
    	
    	String realPath =parentP+childenP;
		String converfilename=realPath+append.getPath();
		HttpSession session = request.getSession();
		
    	if(append.getTagId().equals(img)){
    		session.setAttribute("swfpath", childenP+append.getPath());
    		return "img";
    	}else{
    		DocConverter d;
			try {
				d = new DocConverter(converfilename);
				d.conver();
				String swfpath =d.getswfPath().substring(d.getswfPath().indexOf(childenP));
				session.removeAttribute("swfpath");
				session.setAttribute("swfpath", swfpath);
			} catch (Exception e) {
				e.printStackTrace();
			}
    		return "file";
    	}
    		

    	
	}

preview中對應conver工具類:

package com.jky.until;

/*import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

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;
import com.jky.util.PropertySetting;

*//**
 * doc docx格式轉換
 *//*
public class DocConverter {
	private static Log log = LogFactory.getLog(DocConverter.class);

	private static final int environment = 1;// 環境 1:Windows 2:Linux
	private String fileString;// (只涉及PDF2swf路徑問題)
	private String outputPath = "";// 輸入路徑 ,如果不設置就輸出在默認 的位置
	private String fileName;
	private File pdfFile;
	private File swfFile;
	private File docFile;

	public DocConverter(String fileString) {
		ini(fileString);
		if (log.isDebugEnabled()) {
			log.debug("轉換文件路徑" + fileString);
		}
	}

	*//**
	 *  重新設置file
	 *
	 * @param fileString
	 *            32.
	 *//*
	public void setFile(String fileString) {
		ini(fileString);
	}

	*//**
	 * @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");
	}

	*//**
	 * 轉爲PDF
	 *
	 * @param file
	 * 
	 *//*
	private void doc2pdf() throws Exception {
		if (docFile.exists()) {
			if (!pdfFile.exists()) {
				OpenOfficeConnection connection = new SocketOpenOfficeConnection("127.0.0.1",8100);
				try {
					connection.connect();
					DocumentConverter converter = new OpenOfficeDocumentConverter(connection);
					//2018/10/03修改,因爲預覽
					//DocumentConverter converter = new StreamOpenOfficeDocumentConverter(connection);
					converter.convert(docFile, pdfFile);
					connection.disconnect();
					if (log.isDebugEnabled()) {
						log.debug("pdf轉換成功,PDF輸出: " + pdfFile.getPath());
					}
				} catch (java.net.ConnectException e) {
					log.error("swf轉換器異常,openoffice 服務未啓動", e);
					throw e;
				} catch (com.artofsolving.jodconverter.openoffice.connection.OpenOfficeException e) {
					log.error("swf轉換器異常,讀取轉換文件失敗(" + docFile + ")", e);
					throw e;
				} catch (Exception e) {
					log.error("swf轉換器異常(" + docFile + ")", e);
					throw e;
				}
			} else {
				if (log.isDebugEnabled()) {
					log.debug("已經轉換爲pdf,不需要再進行轉化(" + docFile + ")");
				}
			}
		} else {
			if (log.isWarnEnabled()) {
				log.warn("swf轉換器異常,需要轉換的文檔不存在(" + docFile + ")");
			}
		}
	}

	*//** * 轉換成 swf *//*
	@SuppressWarnings("unused")
	private void pdf2swf() throws Exception {
		Runtime r = Runtime.getRuntime();
		if (!swfFile.exists()) {
			if (pdfFile.exists()) {
				if (environment == 1) {// windows環境處理
					try {
						String exePath = PropertySetting.getValue("default",
								"global", "swftools-pdf2swf-path");
						Process p = r.exec(exePath + " " + pdfFile.getPath()
								+ " -o " + swfFile.getPath() + " -T 9");
						if (log.isDebugEnabled()) {
							log.debug((loadStream(p.getInputStream())));
						}
						log.error(loadStream(p.getErrorStream()));
						if (log.isDebugEnabled()) {
							log.debug(loadStream(p.getInputStream()));
							log.debug("swf轉換成功,文件輸出: " + swfFile.getPath());
						}
						if (pdfFile.exists()) {
							pdfFile.delete();
						}
					} catch (IOException e) {
						log.error("PDF轉換爲SWF錯誤", e);
						throw e;
					}
				} else if (environment == 2) {// linux環境處理
					try {
						Process p = r.exec("pdf2swf" + pdfFile.getPath()
								+ " -o " + swfFile.getPath() + " -T 9");
						if (log.isDebugEnabled()) {
							log.debug(loadStream(p.getInputStream()));
						}
						log.error(loadStream(p.getErrorStream()));
						if (log.isDebugEnabled()) {
							log.debug("swf轉換成功,文件輸出:  " + swfFile.getPath());
						}
						if (pdfFile.exists()) {
							pdfFile.delete();
						}
					} catch (Exception e) {
						log.error("PDF轉換爲SWF錯誤", e);
						throw e;
					}
				}
			} else {
				log.error("pdf不存在,無法轉換(" + pdfFile.getCanonicalPath() + ")");
			}
		} else {
			if (log.isDebugEnabled()) {
				log.debug("swf已經存在不需要轉換(" + swfFile.getCanonicalPath() + ")");
			}
		}
	}

	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();
	}

	*//**
	 * * 轉換主方法
	 *//*
	@SuppressWarnings("unused")
	public boolean conver() {
		if (swfFile.exists()) {
			if (log.isDebugEnabled()) {
				log.debug("swf轉換器開始工作,該文件已經轉換爲 swf");
			}
			return true;
		}
		if (environment == 1) {
			if (log.isDebugEnabled()) {
				log.debug("swf轉換器開始工作,當前設置運行環境 windows");
			}
		} else {
			if (log.isDebugEnabled()) {
				log.debug("swf轉換器開始工作,當前設置運行環境 linux");
			}
		}
		try {
			doc2pdf();
			pdf2swf();
		} catch (Exception e) {
			log.error("", e);
			return false;
		}
		if (swfFile.exists()) {
			if (log.isDebugEnabled()) {
				log.debug("文件存在(" + swfFile + ")");
			}
			return true;
		} else {
			if (log.isWarnEnabled()) {
				log.warn("文件不存在(" + swfFile + ")");
			}
			return false;
		}
	}

	*//**
	 * 返回文件路徑
	 * 
	 * @param
	 *//*
	public String getswfPath() {
		if (this.swfFile.exists()) {
			String tempString = swfFile.getPath();
			tempString = tempString.replaceAll("\\\\", "/");
			if (log.isDebugEnabled()) {
				log.debug("最後文件路徑爲" + tempString);
			}
			return tempString;
		} else {
			return "文件不存在";
		}
	}

	*//**
	 * 設置輸出路徑
	 *
	 * @param outputPath
	 *//*
	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");
			}
		}
	}
}*/
 
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;
import com.jky.util.PropertySetting;
 
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) {
        ini(fileString);
    }
 
    
    // * 重新設置 file @param fileString
     
    public void setFile(String fileString) {
        ini(fileString);
    }
 
    
     //初始化 @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");
    }
 
    
     // 轉爲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
    @SuppressWarnings("unused")
    private void pdf2swf() throws Exception {
        Runtime r = Runtime.getRuntime();
        if (!swfFile.exists()) {
            if (pdfFile.exists()) {
                if (environment == 1)// windows環境處理
                {
                    try {
                        // 這裏根據SWFTools安裝路徑需要進行相應更改
                    	String exePath = PropertySetting.getValue("default","global", "swftools-pdf2swf-path");
                        Process p = r.exec(exePath + 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");
            }
        }
    }
 
    public static void main(String s[]) {
        DocConverter d = new DocConverter("E:/test/fileTest/06b2af1010ec422bb8a74b34ffbb20ac.docx");
        d.conver();
    }
}

其中DocConverter中對應的路徑我的是在配置文件裏面配置的,並且沒有放在項目之下,數據庫裏面就存了id和關係;

<?xml version="1.0" encoding="utf-8"?>
<setting>
	<category id="global">
		<item key="attach-path" value="E:/test" name="附件在磁盤文件系統上的主目錄" />
		 <item key="swftools-pdf2swf-path" value="C:/Program Files (x86)/SWFTools/pdf2swf.exe " />
		<!-- 沒有空格還不行 -->		
		<item key="attach-childen-path" value="/fileTest/" name="附件在磁盤文件系統上的子目錄" />		
	</category>
	<category id="outerNet">
		<item key="url" value="http://127.0.0.1:8080" name="外網地址(文件服務器)" />		
	</category>
	
</setting>

value="C:/Program Files (x86)/SWFTools/pdf2swf.exe " exe後面沒有空格還不行,這是由於工具類轉換的問題;

其實以上做了件什麼事情呢,就是將上傳到e盤下的文件進行轉換先轉換成pdf再轉換成.swf格式;然後將路徑存在session中;返回到前臺頁面用:

代碼運行到上面:點擊預覽按鈕:對應controller,執行成功後將轉換成的.swf文件路徑放入session然後跳轉到前臺頁面:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<!-- saved from url=(0014)about:internet --> 
<%@page contentType="text/html;charset=GBK" %>
<%  
	String swfFilePath=session.getAttribute("swfpath").toString(); 
%>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">	
    <head> 
        <title></title>         
        <meta http-equiv="Content-Type" content="text/html; charset=GBK" /> 
        <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="/js/jquery.js"></script> 
		<script type="text/javascript" src="/js/swfobject/swfobject.js"></script> 
		<script type="text/javascript" src="/js/flexpaper_flash_debug.js"></script> 
		
		<script type="text/javascript"> 
            <!-- For version detection, set to min. required Flash Player version, or 0 (or 0.0.0), for no version detection. --> 
            var swfVersionStr = "10.0.0";
            var xiSwfUrlStr = "playerProductInstall.swf";
            var swfFile = '<%=swfFilePath%>';
           /*  var swfFile = 'E:test/fileTest/b65d413d870a446cbb77b9910a385b02.swf';  */
            swfFile = encodeURI(swfFile);
            var flashvars = { 
                  SwfFile : escape(swfFile),
				  Scale : 0.6, 
                  StartAtPage:2,
				  ZoomTransition : "easeOut",
				  ZoomTime : 0.5,
  				  ZoomInterval : 0.2,
  				  FitPageOnLoad : true,
  				  FitWidthOnLoad : false,
  				  PrintEnabled : true,
  				  FullScreenAsMaxWindow : false,
  				  ProgressiveLoading : true,
  				  
//  				  PrintToolsVisible : true,
//  				  ViewModeToolsVisible : true,
//  				  ZoomToolsVisible : true,
//  				  FullScreenVisible : true,
//  				  NavToolsVisible : true,
//  				  CursorToolsVisible : true,
//  				  SearchToolsVisible : true,
  				  
  				  localeChain: "zh_CN"
				  };
				  
			 var params = {
				
			    }
            params.quality = "high";
            params.bgcolor = "#ffffff";
            params.allowscriptaccess = "sameDomain";
            params.allowfullscreen = "true";
            var attributes = {};
            attributes.id = "FlexPaperViewer";
            attributes.name = "FlexPaperViewer";
            swfobject.embedSWF(
                "FlexPaperViewer.swf", "flashContent", 
                "1200", "600",
                swfVersionStr, xiSwfUrlStr, 
                flashvars, params, attributes);
			swfobject.createCSS("#flashContent", "display:block;text-align:left;");
        </script> 
        
    </head> 
    <body> 
    	<div style="position:absolute;left:10px;top:10px;">
	        <div id="flashContent"> 
	        	<p> 
		        	To view this page ensure that Adobe Flash Player version 
					10.0.0 or greater is installed. 
				</p> 
				<script type="text/javascript">
				    var pageHost = ((document.location.protocol == "https:") ? "https://" : "http://");
				    document.write("<a href='http://www.adobe.com/go/getflashplayer'><img src='"
									+ pageHost + "www.adobe.com/images/shared/download_buttons/get_flash_player.gif' alt='Get Adobe Flash player' /></a>"); 
				</script> 
	        </div> 
        </div> 
        <!-- <div style="position:absolute;left:750px;top:10px;font-family:Verdana;font-size:9pt;"> 
        <table border="0" width="230"> 
	        <tr><th colspan=3>Operations</th></tr> 
	        <tr><td>loadSwf</td><td><input type=text style="width:70px;" id="txt_swffile" value="Paper.swf"></td><td><input type=submit value="Invoke" onclick="getDocViewer().loadSwf($('#txt_swffile').val())"></td></tr> 
	        <tr><td>fitWidth</td><td></td><td><input type=submit value="Invoke" onclick="getDocViewer().fitWidth()"></td></tr> 
	        <tr><td>fitHeight</td><td></td><td><input type=submit value="Invoke" onclick="getDocViewer().fitHeight()"></td></tr> 
	        <tr><td>gotoPage</td><td><input type=text style="width:70px;" id="txt_pagenum" value="3"></td><td><input type=submit value="Invoke" onclick="getDocViewer().gotoPage($('#txt_pagenum').val())"></td></tr> 
	        <tr><td>getCurrPage</td><td></td><td><input type=submit value="Invoke" onclick="alert('Current page:' + getDocViewer().getCurrPage())"></td></tr> 
	        <tr><td>nextPage</td><td></td><td><input type=submit value="Invoke" onclick="getDocViewer().nextPage()"></td></tr> 
	        <tr><td>prevPage</td><td></td><td><input type=submit value="Invoke" onclick="getDocViewer().prevPage()"></td></tr> 
	        <tr><td>setZoom</td><td><input type=text style="width:70px;" id="txt_zoomfactor" value="1.30"></td><td><input type=submit value="Invoke" onclick="getDocViewer().setZoom($('#txt_zoomfactor').val())"></td></tr> 
	        <tr><td>searchText</td><td><input type=text style="width:70px;" id="txt_searchtext" value="text"></td><td><input type=submit value="Invoke" onclick="getDocViewer().searchText($('#txt_searchtext').val())"></td></tr> 
	        <tr><td>switchMode</td><td><input type=text style="width:70px;" id="txt_viewmode" value="Tile"></td><td><input type=submit value="Invoke" onclick="getDocViewer().switchMode($('#txt_viewmode').val())"></td></tr> 
	        <tr><td>printPaper</td><td></td><td><input type=submit value="Invoke" onclick="getDocViewer().printPaper()"></td></tr> 
        </table> 
        <br/><br/> 
        <table border="0" width="230"> 
        	<tr><th>Event Log</th></tr> 
        	<tr><td><textarea rows=6 cols=28 id="txt_eventlog" style="width:215px;"></textarea></td></tr> 
        	<tr><td><input type=text style="width:215px;" id="txt_progress" value=""></td></tr> 
	    </table> 
        </div>  -->
   </body> 
</html> 

這裏注意,我這裏用到的三個jS跟網上大多數不是一樣,因爲版本的問題吧,但也是好用的,

當然跟我一樣的話注意,

代碼中的編碼爲gbk:<%@page contentType="text/html;charset=GBK" %>

轉到這個頁面上注意看一下路徑對不對:

我也貼下我項目運行下的前端頁面獲取到的路徑:

得到轉換後的相對路徑:

 var swfFile = '/fileTest/f9a9e577bd1b42a2a24b677716384b46.swf';

然後假如您文件就存在項目下,那麼你項目下的對應的:FlexPaperViewer.swf(FlexPaper下載下來解壓後放在jsp同目錄下的工具)就會加載您路徑下的文件,大功告成;

但是

假如你的文件是存在電腦的其他盤符(如d,e,c等盤符),

即:你的文件存儲位置不是項目中(爲了避免大量上傳空間考慮)

默認FlexPaper是加載不了的,那麼我們就需要設置虛擬路徑:

在tomcat中的service.xml中加上如下

 

 這裏的意思是,剛剛得到的相對路徑:var swfFile = '/fileTest/f9a9e577bd1b42a2a24b677716384b46.swf';

訪問/fileTest/f9a9e577bd1b42a2a24b677716384b46.swf就可以去訪問

我e盤下:

E:/test/fileTest/f9a9e577bd1b42a2a24b677716384b46.swf

了;

所以這也是點擊預覽,FlexPaper一直轉圈的原因之一,

都配置好之後,是完美展示的:

 圖片預覽:

 

 文件預覽

 最後注意事項總結:

 

1.如果有問題,去排查,轉.swf是否成功,轉的方式是不是有問題;

2.因爲涉及到的工具多,注意之間的版本協調性,是否支持問題;

3.路徑問題,一個是注意OpenOffice所在文件夾位置(文件夾空格問題);二一個就是我實例上的,不在同一目錄問題;

4.訪問http://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager04a.html#119065將生成swf的文件夾設置爲信任文件位置。當然,這個我這裏好像是設置不設置都沒什麼影響;

5.中文亂碼問題;

能訪問展示之後:

6.excel樣式問題;

7.flexpaper窗口無法滾動問題

8.自適應問題

9.多窗口滾動問題

10.瀏覽器與預覽滾動問題

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章