在网页中在线查看文档(doc、docx 、xls 、xlsx、 pdf 、swf )

步骤一:(涉及到的工具)

             在线查看使用FlexPaper软件(http://flexpaper.devaldi.com/download/

            doc、docs、xls、xlsx转换dpf工具openoffice(http://www.openoffice.org/download/index.html

            pdf转成swf工具swftools-0.9.2(http://www.pc6.com/softview/SoftView_51612.html


步骤二:(配置工程)

             1、在项目中导入下载FlexPaper解压后文件(js、css、swf文件等)

              2、编写一个html页面

          

<!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 --> 
<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=utf-8" /> 
        <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/swfobject/swfobject.js"></script>
		<script type="text/javascript" src="../js/flexpaper_flash.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";
            <!-- To use express install, set to playerProductInstall.swf, otherwise the empty string. -->
         /*    var xiSwfUrlStr = "playerProductInstall.swf"; */
            var xiSwfUrlStr = "";  //值可以任意
            
            var flashvars = { 
                  SwfFile : escape("lucene4.6.swf"),   //swf文件路径(lucene4.6和页面同一个位置)   
				  Scale : 0.6, 
				  ZoomTransition : "easeOut",
				  ZoomTime : 0.5,
  				  ZoomInterval : 0.1,
  				  FitPageOnLoad : false,
  				  FitWidthOnLoad : true,
  				  PrintEnabled : true,
  				  FullScreenAsMaxWindow : false,
  				  ProgressiveLoading : true,
  				  
  				  PrintToolsVisible : true,
  				  ViewModeToolsVisible : true,
  				  ZoomToolsVisible : true,
  				  FullScreenVisible : true,
  				  NavToolsVisible : true,
  				  CursorToolsVisible : true,
  				  SearchToolsVisible : true,
  				  
  				  localeChain: "en_US"
				  };
				  
			 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", 
                "800", "600",
                swfVersionStr, xiSwfUrlStr, 
                flashvars, params, attributes);
			swfobject.createCSS("#flashContent", "display:block;text-align:center;");
        </script> 
        
    </head> 
    <body> 
    	<div style="position:absolute;left:200px;top:10px;">
	        <div id="flashContent"> 
	       </div> 
        </div>
   </body> 
</html> 

打开html页面就可以运行,效果如下:

 


步骤三:pdf转换成swf格式(借鉴别人)

               1、下载 jodconverter-2.2.2 ,将lib目录所有jar 复制到项目 lib目录

               2、写一个java工具类(doc、dcox、xls、xlsx->pdf->swf)

                  

package com.netsix.util;  

import java.io.BufferedInputStream;  
import java.io.File;  
import java.io.FileNotFoundException;  
import java.io.IOException;  
import java.io.InputStream;  
import java.net.ConnectException;  
import java.util.ResourceBundle;  
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;  

/** 
 * 将文件转成swf格式 
 *  
 * @author Administrator 
 *  
 */  
public class ConvertSwf {  

	/** 
	 * 入口方法-通过此方法转换文件至swf格式 
	 * @param filePath  上传文件所在文件夹的绝对路径 
	 * @param fileName  文件名称 
	 * @return          生成swf文件名 
	 */  
	public String beginConvert(String filePath, String fileName) {  
		final String DOC = ".doc";  
		final String DOCX = ".docx";  
		final String XLS = ".xls";  
		final String XLSX = ".xlsx";  
		final String PDF = ".pdf";  
		final String SWF = ".swf";  
		final String TOOL = "pdf2swf.exe";  
		String outFile = "";  
		String fileNameOnly = "";  
		String fileExt = "";  
		if (null != fileName && fileName.lastIndexOf(".") > 0) {  
			int index = fileName.lastIndexOf(".");  
			fileNameOnly = fileName.substring(0, index);  
			fileExt = fileName.substring(index).toLowerCase();  
		}  
		String inputFile = filePath + File.separator + fileName;  
		String outputFile = "";  

		//如果是office文档,先转为pdf文件  
		if (fileExt.equals(DOC) || fileExt.equals(DOCX) || fileExt.equals(XLS)  
				|| fileExt.equals(XLSX)) {  
			outputFile = filePath + File.separator + fileNameOnly + PDF;  
			office2PDF(inputFile, outputFile);  
			inputFile = outputFile;  
			fileExt = PDF;  
		}  

		if (fileExt.equals(PDF)) {  
			String toolFile = filePath + File.separator + TOOL;  
			outputFile = filePath + File.separator + fileNameOnly + SWF;  
			convertPdf2Swf(inputFile, outputFile, toolFile);  
			outFile = outputFile;  
		}  
		return outFile;  
	}  

	/** 
	 * 将pdf文件转换成swf文件 
	 * @param sourceFile pdf文件绝对路径 
	 * @param outFile    swf文件绝对路径 
	 * @param toolFile   转换工具绝对路径 
	 */  
	private void convertPdf2Swf(String sourceFile, String outFile,  
			String toolFile) {  
		String command = toolFile + " \"" + sourceFile + "\" -o  \"" + outFile  
				+ "\" -s flashversion=9 ";  
		try {  
			Process process = Runtime.getRuntime().exec(command);  
			System.out.println(loadStream(process.getInputStream()));  
			System.err.println(loadStream(process.getErrorStream()));  
			System.out.println(loadStream(process.getInputStream()));  
			System.out.println("###--Msg: swf 转换成功");  
		} catch (Exception e) {  
			e.printStackTrace();  
		}  
	}  

	/** 
	 * office文档转pdf文件 
	 * @param sourceFile    office文档绝对路径 
	 * @param destFile      pdf文件绝对路径 
	 * @return 
	 */  
	private int office2PDF(String sourceFile, String destFile) {  
		ResourceBundle rb = ResourceBundle.getBundle("OpenOfficeService");  
		String OpenOffice_HOME = "D:\\Program Files\\OpenOffice 4";  //openoffice安装路径 
		String host_Str = "127.0.0.1";   //地址
		String port_Str = "8100";        //端口号
		try {  
			File inputFile = new File(sourceFile);  
			if (!inputFile.exists()) {  
				return -1; // 找不到源文件   
			}  
			// 如果目标路径不存在, 则新建该路径    
			File outputFile = new File(destFile);  
			if (!outputFile.getParentFile().exists()) {  
				outputFile.getParentFile().mkdirs();  
			}  
			// 如果从文件中读取的URL地址最后一个字符不是 '\',则添加'\'  
            if (OpenOffice_HOME.charAt(OpenOffice_HOME.length() - 1) != '\\') {  
                OpenOffice_HOME += "\\";  
            }  
			// 启动OpenOffice的服务    
			String command = OpenOffice_HOME  
					+ "program\\soffice.exe -headless -accept=\"socket,host="  
					+ host_Str + ",port=" + port_Str + ";urp;\"";  
			System.out.println("###\n" + command);  
			Process pro = Runtime.getRuntime().exec(command);  
			// 连接openoffice服务  
			OpenOfficeConnection connection = new SocketOpenOfficeConnection(  
					host_Str, Integer.parseInt(port_Str));  
			connection.connect();  
			// 转换   
			DocumentConverter converter = new OpenOfficeDocumentConverter(  
					connection);  
			converter.convert(inputFile, outputFile);  

			// 关闭连接和服务  
			connection.disconnect();  
			pro.destroy();  

			return 0;  
		} catch (FileNotFoundException e) {  
			System.out.println("文件未找到!");  
			e.printStackTrace();  
			return -1;  
		} catch (ConnectException e) {  
			System.out.println("OpenOffice服务监听异常!");  
			e.printStackTrace();  
		} catch (IOException e) {  
			e.printStackTrace();  
		}  
		return 1;  
	}  

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

}  

测试类

package com.netsix.test;

import com.netsix.util.ConvertSwf;

public class MainClass {

	public static void main(String[] args) {
		
		String dirPath = "D:\\workspace\\20140403_WebScaner\\pdf";  // 下载swftools-0.9.2.exe 安装后,复制安装目录中 pdf2swf.exe 到项目附件目录中。
		String fileName = "lucene4.6.doc";
		
		String outPath = new ConvertSwf().beginConvert(dirPath,fileName);   
		System.out.println("生成swf文件:" + outPath);  
		
	}
}

demo例子:http://download.csdn.net/detail/lin062854/7145653


  • 3
    点赞
  • 42
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
在Vue预览docxdocpdfxlsxlsx文件,可以使用第三方库来实现。 对于docxdocxlsxlsx文件,可以使用`js-xlsx`库来进行解析和预览。该库可以将Excel文件转换为JSON格式,而对于Word文件,可以使用`docx.js`库来进行解析和预览。 对于pdf文件,可以使用`pdf.js`库来进行预览。该库可以通过Canvas将PDF文件渲染成图片,然后在Vue显示。 下面是一个示例代码,演示如何使用上述库来预览不同类型的文件: ```html <template> <div> <div v-if="fileType === 'docx' || fileType === 'doc'"> <div v-html="docContent"></div> </div> <div v-else-if="fileType === 'xls' || fileType === 'xlsx'"> <table> <tr v-for="row in excelData"> <td v-for="cell in row">{{ cell }}</td> </tr> </table> </div> <div v-else-if="fileType === 'pdf'"> <canvas ref="pdfCanvas"></canvas> </div> </div> </template> <script> import XLSX from 'xlsx'; import Docx from 'docx'; import pdfjsLib from 'pdfjs-dist'; export default { data() { return { fileType: '', docContent: '', excelData: [], }; }, mounted() { // 根据文件类型进行解析和预览 if (this.fileType === 'docx' || this.fileType === 'doc') { const reader = new FileReader(); reader.onload = (event) => { const content = event.target.result; const doc = new Docx(); doc.load(content); this.docContent = doc.getHtml(); }; reader.readAsArrayBuffer(this.file); } else if (this.fileType === 'xls' || this.fileType === 'xlsx') { const reader = new FileReader(); reader.onload = (event) => { const content = event.target.result; const workbook = XLSX.read(content, { type: 'array' }); const sheetName = workbook.SheetNames[0]; const worksheet = workbook.Sheets[sheetName]; this.excelData = XLSX.utils.sheet_to_json(worksheet, { header: 1 }); }; reader.readAsArrayBuffer(this.file); } else if (this.fileType === 'pdf') { const canvas = this.$refs.pdfCanvas; const ctx = canvas.getContext('2d'); pdfjsLib.getDocument(this.file).promise.then((pdf) => { pdf.getPage(1).then((page) => { const viewport = page.getViewport({ scale: 1.5 }); canvas.height = viewport.height; canvas.width = viewport.width; page.render({ canvasContext: ctx, viewport, }); }); }); } }, props: { file: { type: File, required: true, }, }, created() { // 根据文件后缀名判断文件类型 const fileExtension = this.file.name.split('.').pop(); if (fileExtension === 'docx' || fileExtension === 'doc') { this.fileType = 'docx'; } else if (fileExtension === 'xls' || fileExtension === 'xlsx') { this.fileType = 'xls'; } else if (fileExtension === 'pdf') { this.fileType = 'pdf'; } }, }; </script> ``` 在上述代码,根据文件后缀名判断文件类型,然后使用不同的库进行解析和预览。对于Word文件,使用`docx.js`库将文件解析为HTML格式,然后在Vue显示;对于Excel文件,使用`js-xlsx`库将文件解析为JSON格式,然后在Vue生成表格;对于PDF文件,使用`pdf.js`库将文件渲染成图片,然后在Vue显示。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值