English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Este artigo introduce a pré-visualização de anexos implementada em java, que requer openoffice, SWFTools e FlexPaper, os passos específicos são os seguintes:
1Resumo
Principio principal
1Converter arquivos word, excel, ppt, txt e outros em arquivos pdf usando a ferramenta openoffice de terceiros
2Converter arquivos pdf em formato swf usando SWFTools
3Mostrar no documento FlexPaper na página
2pacote de instalação
1OpenOffice é um software de processamento de texto aberto e gratuito sob a Apache
Endereço de download: download da página oficial do Apache OpenOffice Versão-3.4.1 http://www.openoffice.org/zh-cn/download/
2SWFTools é um conjunto de ferramentas para manipulação de arquivos swf do Flash, usamos para converter arquivos pdf em swf!
Endereço de download: download da página oficial do SWFTools swftools-2013-04-09-1007.exe http://www.swftools.org/download.html
3FlexPaper é um componente de documentos de código aberto e leve que permite exibir vários documentos no navegador
Endereço de download: download da página oficial do FlexPaper Versão1.5.1 https://flowpaper.com/download/
4JODConverter é um conversor de arquivo OpenDocument em Java, aqui usamos apenas seu pacote jar
Endereço de download: download JODCConverter https://sourceforge.net/projetos/jodconverter/arquivos/
3Instalar o arquivo
1Instale os arquivos baixados (exceto JODConverter), o drive pode ser configurado conforme necessário! É importante notar que após a instalação do openoffice, ao usá-lo, precisamos abrir seu serviço. Nesta ocasião, precisamos abrir com comando:
Abra a janela do DOS, acesse o drive do disco de instalação do openoffice e digite o seguinte código para iniciar o serviço:
soffice -sem-visualização -accept="socket,host=127.0.0.1.0.0.810,port= -0;urp;"
nofirststartwizard
Atenção: não escreva o "—" antes do último comando! Se o serviço não começar, o projeto não pode continuar.
Captura de tela de inicialização do site oficial如下:
3Captura de tela local:
1.Desenvolvimento do processo
.Novo projeto, copie a pasta js do arquivo flexpaper (contém flexpaper_flash_debug.js, flexpaper_flash.js, jquery.js, esses três arquivos js são plugins para pré-visualização de arquivos swf) para o diretório raiz do site; copie FlexPaperViewer.swf para o diretório raiz do site (este arquivo é usado principalmente para reproduzir arquivos swf em páginas da web), a estrutura do diretório é como na figura a seguir:
2Notas: é necessário criar a pasta upload
<%@ 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>文档在线预览系统</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> .Criar fileUpload.jsp-<div id="msg box">1<form name="form/" method="post" enctype="multipart-form data" action="docUploadConvertAction.jsp"> <div class="title"> </div> " type="file"> Por favor, upload o arquivo a ser processado, o processo pode levar alguns minutos, por favor, aguarde um pouco.1<input name="file </<input type="submit" name="Submit" value="Upload"> " type="file"> <p> </<input type="submit" name="Submit" value="Upload"> </p> </div> </body> </html>
3form >
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8%> .Criar a página de conversão docUploadConvertAction.jsp*%> <%@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"%>-O upload de arquivo usando o componente cos, pode ser substituído por commons //Obter o caminho de upload de arquivo String saveDirectory = application.getRealPath("/")+"upload"; //Imprima informações de caminho de upload System.out.println(saveDirectory); //tamanho máximo de cada arquivo50m int maxPostSize = 50 * 1024 * 1024 ; //Utilize a estratégia de nomeação padrão do cos, adicionando ao nome do arquivo se houver conflito de nomes1,2,3...se não for adicionado dfp renomear, o arquivo será sobrescrito DefaultFileRenamePolicy dfp = new DefaultFileRenamePolicy(); //response.getCharacterEncoding() é "UTF-8, utilizando a estratégia padrão de resolução de conflitos de nomes de arquivos, realizando o upload, se não for adicionado dfp renomear, o arquivo será sobrescrito MultipartRequest multi = new MultipartRequest(request, saveDirectory, maxPostSize,"UTF-8 //MultipartRequest multi = new MultipartRequest(request, saveDirectory, maxPostSize,"UTF-8"; //Exiba informações de feedback 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); //Obtenha a extensão do arquivo carregado String extName=fileName.substring(fileName.lastIndexOf(".")+1); //Caminho completo do arquivo String lastFileName= saveDirectory+"\\" + fileName; //Obtenha o nome do arquivo a ser convertido, substituindo o caractere '\\' por '"/' String converfilename = saveDirectory.replaceAll("\\\\", "/")+"/"+fileName; System.out.println(converfilename); //Chame a classe de conversão DocConverter e passe o arquivo a ser convertido ao método construtor da classe DocConverter d = new DocConverter(converfilename); //Chame o método conver para começar a conversão, executando primeiro doc2O pdf() converte arquivos office em pdf; em seguida, execute pdf2swf()将pdf转换为swf; d.conver(); //调用getswfPath()方法,打印转换后的swf文件路径 System.out.println(d.getswfPath()); //生成swf相对路径,以便传递给flexpaper播放器 String swfpath = "upload"+d.getswfPath().substring(d.getswfPath().lastIndexOf("/")); System.out.println(swfpath); //将相对路径放入sessio中保存 session.setAttribute("swfpath", swfpath); out.println("上传的文件:"+lastFileName); out.println("文件类型"+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='预览' class='BUTTON SUBMIT'>/> </form> </div> </body> </html>
创建查看页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>文档在线预览系统</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.创建转换类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格式转换 */ public class DocConverter { 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); } /** * Reconfigurar file * * @param fileString */ public void setFile(String fileString) { ini(fileString); } /** * Inicializar * * @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"); } /** * Converter para 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); // fechar a conexão connection.disconnect(); System.out.println("****Conversão PDF bem-sucedida, saída PDF: " + pdfFile.getPath()+ "****"; catch (java.net.ConnectException e) { e.printStackTrace(); System.out.println("****O conversor SWF está em exceção, o serviço OpenOffice não foi iniciado!****"; throw e; catch (com.artofsolving.jodconverter.openoffice.connection.OpenOfficeException e) { e.printStackTrace(); System.out.println("****a conversão SWF falhou, falha ao ler o arquivo de conversão****"; throw e; } catch (Exception e) { e.printStackTrace(); throw e; } } else { System.out.println("****já convertido para PDF, não há necessidade de conversão adicional****"; } } else { System.out.println("****a conversão SWF falhou, o documento a ser convertido não existe, não é possível converter****"; } } /** * converter para SWF */ @SuppressWarnings("unused") private void pdf2swf() throws Exception { Runtime r = Runtime.getRuntime(); if (!swfFile.exists()) { if (pdfFile.exists()) { if (environment == 1) {}}// tratamento no ambiente Windows 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("****conversão SWF bem-sucedida, arquivo de saída: " + swfFile.getPath() + "****"; if (pdfFile.exists()) { pdfFile.delete(); } } catch (IOException e) { e.printStackTrace(); throw e; } } else if (environment == 2) {}}// tratamento no ambiente 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("****conversão SWF bem-sucedida, arquivo de saída: " + swfFile.getPath() + "****"; if (pdfFile.exists()) { pdfFile.delete(); } } catch (Exception e) { e.printStackTrace(); throw e; } } } else { System.out.println("****o PDF não existe, não é possível converter****"; } } else { System.out.println("****o SWF já existe, não há necessidade de conversão****"; } } 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(); } /** * método principal de conversão */ @SuppressWarnings("unused") public boolean conver() { if (swfFile.exists()) { System.out.println("****o conversor SWF começa a trabalhar, o arquivo já foi convertido para SWF****"; return true; } if (environment == 1) {}} System.out.println("****O conversor SWF começa a trabalhar, o ambiente de execução configurado atualmente é Windows****"; } else { System.out.println("****O conversor SWF começa a trabalhar, o ambiente de execução configurado atualmente é Linux****"; } try { doc2pdf(); pdf2swf(); } catch (Exception e) { e.printStackTrace(); return false; } if (swfFile.exists()) { return true; } else { return false; } } /** * Retorna o caminho do arquivo * * @param s */ public String getswfPath() { if (swfFile.exists()) { String tempString = swfFile.getPath(); tempString = tempString.replaceAll("\\\\", "/"; return tempString; } else { return ""; } } /** * Defina o caminho de saída */ 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"); } else { swfFile = new File(outputPath + realName + ".swf"); } } } }
6.Publicação de deployment
Inicie o tomcat, deploie o aplicativo web atual
Insira o endereço na barra de endereçoshttp://localhost:8080/ctcesims/documentUpload.jsp Conforme a figura a seguir:
Clique no botão de visualização, gerará a interface de visualização, conforme a figura a seguir:
4.Perguntas frequentes
Se não puder visualizar o swf, acesse
http://www.macromedia.com/suporte/documentação/en/flashplayer/ajuda/settings_manager04a.html#119065
Defina a pasta onde será gerado o swf como um local de arquivo confiável.
A seguir, fornecido flexpaper 2.1.9 的不同之处:初始化方式改变,若文件目录与项目目录不在一起,可将附件目录在服务器中设置为虚拟目录
<%@ 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>文档在线预览系统</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>
Por fim, se precisar remover a função de impressão e o logo, você pode recompilar o arquivo flash do flexpaper, também disponível para download na internet
Isso é tudo o que há no artigo, espero que ajude no seu aprendizado e que você apoie o tutorial Yell.
Declaração: O conteúdo deste artigo é de origem na Internet, pertence ao autor original, fornecido pelos usuários da Internet de forma voluntária e carregado por eles mesmos. Este site não possui direitos de propriedade, não foi editado manualmente e não assume responsabilidade por questões legais relacionadas. Se você encontrar conteúdo suspeito de violação de direitos autorais, por favor, envie e-mail para: notice#oldtoolbag.com (ao enviar e-mail, substitua # por @ para denunciar e forneça provas relevantes. Se confirmado, o site deletará imediatamente o conteúdo suspeito de violação de direitos autorais.)