English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
이 문서는 Java로 구현된 첨부 파일 미리보기를 주로 소개합니다. openoffice, SWFTools, FlexPaper를 사용해야 하며, 구체적인 단계는 다음과 같습니다:
1. 개요
주요 원리
1. 제3자 도구 openoffice를 사용하여 word, excel, ppt, txt 등의 파일을 pdf 파일로 변환
2. swfTools를 사용하여 pdf 파일을 swf 형식의 파일로 변환
3. FlexPaper 문서 컴포넌트를 사용하여 페이지에서 표시
2. 설치 패키지 다운로드
1. openoffice는 Apache의 하에 있는 개방형 무료 텍스트 처리 소프트웨어입니다
다운로드 주소: Apache oppenoffice 웹사이트 다운로드 버전-3}4}1 http://www.openoffice.org/zh-cn/download/
2. SWFTools는 Flash swf 파일을 처리하는 도구 패키지의 일부입니다. 우리는 이를 사용하여 pdf 파일을 swf 파일로 변환합니다!
다운로드 주소: SWFTools 웹사이트 다운로드 swftools-2013-04-09-1007.exe http://www.swftools.org/download.html
3. FlexPaper는 브라우저에서 다양한 문서를 표시하는 오픈 소스 가벼운 컴포넌트입니다
다운로드 주소: FlexPaper 웹사이트 다운로드 버전1}5}1 https://flowpaper.com/download/
4. JODConverter는 Java의 OpenDocument 파일 변환기입니다. 여기서는 jar 패키지를 사용합니다.
다운로드 주소: JODCConverter 다운로드 https://sourceforge.net/projects/jodconverter/files/
3. 설치 파일
1. 다운로드한 파일(예외로 JODConverter)을 설치하십시오. 디스크는 자유롭게 설정할 수 있습니다! 주의할 점은 openoffice 설치가 완료되면, 사용할 때마다 서비스를 열어야 합니다. 이번에는 명령어 방식으로 열어야 합니다:
dos 창을 열고 openoffice 설치 디스크를 진입하여 다음 코드를 입력하여 서비스를 시작하십시오:
soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;" -nofirststartwizard
주의: 마지막 명령어 앞의 ‘—'을 틀리지 마세요! 서비스가 시작되지 않으면, 프로젝트는 계속 진행할 수 없습니다.
공식 웹사이트 서비스 시작 캡처如下:
로컬 캡처:
3.개발 과정
1.FlexPaperViewer.swf 파일을 웹사이트 루트 디렉토리에 복사합니다(이 파일은 웹 페이지에서 swf 파일을 재생하는 플레이어로 사용됩니다). 디렉토리 구조는 다음과 같습니다:
주의: upload 폴더를 생성해야 합니다
2.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>문서 온라인 предпросмотр системы</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 class="title"> 처리할 파일을 업로드하세요. 과정은 몇 분이 걸릴 수 있으며, 잠시 기다려 주세요. </div> <p> <input name="file1" type="file"> </p> <p> <input type="submit" name="Submit" value="업로드"> </p> </form > </div> </body> </html>
3.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"%> <% //파일 업로드는 cos 컴포넌트로 업로드되며, commons로 변경할 수 있습니다-fileupload 업로드, 파일 업로드 후, upload 폴더에 저장됩니다 //파일 업로드 경로 가져오기 String saveDirectory = application.getRealPath("/")+"upload"; //업로드 경로 정보 출력 System.out.println(saveDirectory); //각 파일의 최대50m int maxPostSize = 50 * 1024 * 1024 ; //cos 기본 명명 전략을 사용하여,同名시 추가로命名합니다;1,2,3...기본적으로 dfp를 추가하지 않으면 파일 이름을 재명명하지 않고 덮어씁니다; DefaultFileRenamePolicy dfp = new DefaultFileRenamePolicy(); //response의 인코딩은 "UTF-8",기본 파일 이름 충돌 해결 전략을 동시에 사용하여 업로드를 수행합니다. dfp를 추가하지 않으면 파일 이름을 재명명하지 않고 덮어씁니다; MultipartRequest multi = new MultipartRequest(request, saveDirectory, maxPostSize,"UTF-8",dfp); //MultipartRequest multi = new MultipartRequest(request, saveDirectory, maxPostSize,"UTF-8"); //피드백 정보 출력 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); //업로드 파일의 확장명을 얻습니다; String extName=fileName.substring(fileName.lastIndexOf(".")+1); //파일 전체 경로 String lastFileName= saveDirectory+"\\" + fileName; //변환할 파일 이름을 얻고, 경로 이름에서 '\'를 '"로 대체합니다;/' String converfilename = saveDirectory.replaceAll("\\\\", "/")+"/"+fileName; System.out.println(converfilename); //변환 클래스 DocConverter를 호출하고, 변환할 파일을 해당 클래스의 생성자에 전달합니다; DocConverter d = new DocConverter(converfilename); //conver 메서드를 호출하여 변환을 시작하고, 먼저 doc를 실행합니다;2pdf()은 office 파일을 pdf로 변환한 후 실행합니다;2swf()将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;// (pdf에만 관련됩니다2swf 경로 문제) 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); // 연결을 닫습니다 connection.disconnect(); System.out.println("****pdf 변환 성공, PDF 출력: " + pdfFile.getPath()+ "****"); catch (java.net.ConnectException e) { 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 { 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 변환 성공, 파일 출력: " + swfFile.getPath() + "****"); if (pdfFile.exists()) { pdfFile.delete(); } } catch (IOException 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; 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()) { 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) { 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("")) { / fileName.lastIndexOf(".")); if (outputPath.charAt(outputPath.length() - 1) == '/') { swfFile = new File(outputPath + realName + ".swf"); } else { swfFile = new File(outputPath + realName + ".swf"); } } } }
6.배포 배포
tomcat을 시작하고 현재 웹 애플리케이션을 배포합니다
주소줄에 입력http://localhost:8080/ctcesims/documentUpload.jsp 다음과 같습니다:
미리보기 버튼을 클릭하면 다음과 같은 미리보기 인터페이스가 생성됩니다:
4.자주 묻는 질문
SWF를 미리보기할 수 없으면 방문하십시오
http://www.macromedia.com/지원/문서화/en/flashplayer/도움말/settings_manager04a.html#119065
SWF를 생성하는 폴더를 신뢰할 수 있는 파일 위치로 설정합니다
다음은 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>
마지막으로, 프린팅 기능 및 로고를 제거하려면 flexpaper의 flash 파일을 다시 컴파일하십시오. 인터넷에서 다운로드도 가능합니다.
이것이 본문의 전부입니다. 여러분의 학습에 도움이 되길 바라며, 또한 많이 지지해 주시길 바랍니다.
선언: 본문 내용은 인터넷에서 가져왔으며, 저작권자는 모두입니다. 내용은 인터넷 사용자가 자발적으로 기여하고 업로드한 것이며, 이 웹사이트는 소유권을 가지지 않으며, 인공 편집 처리도 하지 않았으며, 관련 법적 책임도 부담하지 않습니다. 저작권 침해가 의심되는 내용을 발견하시면, notice#w로 이메일을 보내 주시기 바랍니다.3codebox.com에 (보내는 이메일에서 #을 @으로 변경하십시오) 신고를 해 주시고, 관련 증거를 제공하시면, 사실이 확인되면,本站이 즉시 저작권 침해 내용을 삭제할 것입니다。