이 기사는 주로 OpenOffice, SWFTools 및 FlexPaper가 필요한 첨부 파일 미리보기의 Java 구현을 소개합니다. 특정 단계는 다음과 같습니다.
1. 개요
주요 원칙
1. Word, Excel, PPT, TXT 및 기타 파일 변환 타사 도구 OpenOffice를 통해 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 설치 드라이브 문자를 입력 한 다음 다음 코드를 입력하여 서비스를 시작하십시오.
소프트웨어 -headless -Accept = "소켓, 호스트 = 127.0.0.1, 포트 = 8100; URP;" -NofirstStartWizard
마지막 명령 앞에서 '-'에주의를 기울이십시오. 잘못 쓰지 마십시오! 서비스를받을 수 없으면 프로젝트는 계속 될 수 없습니다.
공식 웹 사이트 런칭 서비스의 스크린 샷은 다음과 같습니다.
로컬 스크린 샷 :
3. 개발 과정
1. 새 프로젝트를 만들고 flexpaper 파일 (Flexpaper_flash_debug.js, flexpaper_flash.js, jquery.js 포함,이 3 개의 JS 파일은 주로 SWF 파일을위한 플러그인입니다)에 대한 JS 폴더를 FlexPaper 파일 (flexpaper_flash_debug.js, jquery.js 포함)에 복사하십시오. FlexPaperViewer.swf를 웹 사이트 루트 디렉토리로 복사합니다 (파일은 주로 웹 페이지에서 SWF 파일을 재생하는 플레이어로 사용됩니다). 디렉토리 구조는 다음과 같습니다.
참고 : 업로드 폴더를 만들어야합니다
2. fileUpload.jsp를 만듭니다
<%@ page language = "java"contmenttype = "text/html; charset = utf-8"pageencoding = "utf-8"%> <! doctype html public "-// w3c // dtml 4.01 transitional // en" "http://www.w3.org/tr/tml/html 4/tml/html 4/tml 4.html/html 4.tml. <html> <head> <meta http-equiv = "content-type"content = "text/html; charset = utf-8"> <title> 문서 온라인 미리보기 시스템 </title> <style> body {margin-top : 100px; 배경 : #fff; font-family : verdana, tahoma;} a {ce4614; #CE4614; 글꼴 크기 : 0.9EM; 텍스트-정렬 : 중심;} #msg-box .Logo {Border-Bottom : 5PX Solid #ECE5D9; 마진-바닥 : 20px; 패딩-버트 톰 : 10px;} #msg-box .Title {font-size : 1.4EM; font-weight : bold; margin : 0 30}} #box 0; {margin-top : 20px;} </style> </style> </head> <body> <div id = "msg-box"> <form name = "form1"method = "post"encticpe = "multipart/form-data"action = "docuploadconvertaction.jsp"> <div> 처리 할 파일을 업로드하십시오. 프로세스에 몇 분이 걸릴 수 있습니다. 잠시 기다려주세요. </div> <p> <input name = "file1"type = "file"> </p> <p> <입력 유형 = "제출"이름 = "제출"value = "upload"> </p> </div> </body> </html> </html> 3. 변환 페이지를 만듭니다. docuploadconvertaction.jsp
<%@page language = "java"contmenttype = "text/html; charset = utf-8"pageencoding = "utf-8"%> <%@page import = "java.io.*"%> <%@page import = "java.util.enumeration"%> <%@page import = "com.oreilly.servlet.multiptarepepepepepeT" import = "com.oreilly.servlet.multipart.defaultfilerenamepolicy"%> <%@page import = "com.cectsims.util.docconverter"%> <%@page import = "com.cectsims.util.docconverter"%> <%@page import = "com.cectsims.util.docconter"%> COS 구성 요소는 Commons-FileUpload 업로드로 대체 할 수 있습니다. 파일이 업로드 된 후 업로드 폴더에 저장 // 파일 업로드 경로를 가져옵니다. // 업로드 경로 정보 시스템을 인쇄합니다. out.println (savedirectory); // 각 파일 최대 50m int maxpostsize = 50 * 1024 * 1024; // COS의 기본 명명 전략을 사용하고, 1, 2, 3 중복 이름 뒤에 추가하십시오 ... DFP 및 Duplical Name을 추가하지 않으면 defaultFilerenAmepolicy DFP = new DefaultFilerenAmePolicy (); // 응답 인코딩은 "UTF-8"이며 기본 파일 이름 충돌 해상도 전략은 업로드를 구현하는 데 사용됩니다. DFP 중복 이름이 추가되지 않으면 MultipartRequest가 덮어 씁니다. multipartrequest multi = 새로운 multipartrequest (요청, Savedirectory, MaxPostSize, "UTF-8", DFP); // multipartrequest multi = 새로운 multipartrequest (요청, Savedirectory, MaxPostSize, "UTF-8"); // 출력 피드백 정보 열거 파일 = multi.getFilenames (); while (files.hasmoreElements ()) {System.err.println ( "CCC"); 문자열 이름 = (문자열) files.nextElement (); 파일 f = multi.getFile (이름); if (f! = null) {String filename = multi.getfilesystemname (이름); // 업로드 된 파일의 확장자를 가져옵니다. string extName = filename.substring (filename.lastIndexof ( ".")+1); // 파일 전체 경로 문자열 lastFilename = savedirectory + "//" + filename; // 변환 해야하는 파일 이름을 가져 와서 경로 이름으로 '/'를 '/'string converfilename = savedirectory.replaceall ( "////", "/")+"/"+filename; System.out.println (converfilename); // 변환 클래스 DOCCONVERTER를 호출하고 파일을 전달 하여이 클래스의 생성자로 변환 될 파일을 전달합니다. docConverter d = new DocConverter (converfilename); // 변환 메소드를 호출하여 변환을 시작하고 먼저 doc2pdf ()를 실행하여 사무실 파일을 pdf로 변환합니다. 그런 다음 pdf2swf ()를 실행하여 pdf를 SWF로 변환합니다. d.conver (); // cell getSwfpath () 메소드를 인쇄하고 변환 된 SWF 파일 경로 시스템을 인쇄합니다. // flexpaper player로 전달할 SWF 상대 경로 생성 string swfpath = "upload"+d.getswfpath (). substring (d.getswfpath (). lastIndexof ( "/")); System.out.println (swfpath); // 상대 경로를 세션에 넣습니다 .setAttribute ( "swfpath", swfpath); out.println ( "업로드 된 파일 :"+lastFilename); out.println ( "파일 유형"+extName); out.println ( "<hr>"); }} %> <! doctype html public "-// w3c // dtd html 4.01 전환 // en" "http://www.w3.org/tr/html4/loose.dtd"> <html> <head> <meta http-equiv = "contents ="텍스트/httml; charset = utf-8 "> <title> 제목 삽입 제목 </title> <style> body {margin-top : 100px; 배경 : #fff; font-family : verdana, tahoma;} a {color : #ce4614;} #msg-box {color : #ce4614; 글꼴 크기 : 0.9EM; 텍스트-정렬 : 중심;} #msg-box .Logo {Border-Bottom : 5PX Solid #ECE5D9; 마진-바닥 : 20px; 패딩-버트 톰 : 10px;} #msg-box .Title {font-size : 1.4EM; font-weight : bold; margin : 0 30}} #box 0; {margin-top : 20px;} </style> </head> <body> <div> <form name = "viewform"id = "form_swf"action = "documentview.jsp"method = "post"> <input type = ''vale = 'class ='버튼 제출 '/> </form> </div> </html> </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-6. <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/script> <style. type = "text/css"media = "screen"> html, body {높이 : 100%; } 본체 {마진 : 0; 패딩 : 0; 오버플로 : 자동; } #flashContent {디스플레이 : 없음; } </style> <title> 문서 온라인 미리보기 시스템 </title> </head> <body> <div style = "위치 : 위치 : 절대; 왼쪽; 왼쪽 : 50px; 상단 : 10px;"> <a id = "viewerplaceholder"> </a> <script type = "text/javaScript"> var fp = new FlexPaperViewer ( 'flexpaperver', {flexpapperver ', : Escape ( '<%= swffilepath%>'), 스케일 : 0.6, 줌 타이션 : 'easeout', Zoomtime : 0.5, ZoominterVal : 0.2, fitpageonload : true, fitwidthonload : false, fullscreenasmaxwindow : false, progressiveloading : false, minzoomsize : 0.2, maxzoomsize : 5, fuccureall : 5,, fucture, maxzoomsize : 'SinglePage', ViewModetoolsvisible : True, Zoomtoolsvisible : true, navtoolsvisible : true, cursortoolsvisible : true, searchToolsvisible : true, localechain : 'en_us'}}); </script> </div> </body> </html> 5. 변환 클래스 DocConverter.java를 만듭니다
패키지 com.cectsims.util; import java.io.bufferedInputStream; import java.io.file; import java.io.ioexception; import java.io.inputstream; com.artofSolving.jodConverter.DocumentConverter import; com.artofsolving.jodconverter.openoffice.connection.openofficeConnection import; com.artofsolving.jodconverter.openoffice.connection.socketopenofficeCeNcection import; com.artofSolving.jodConverter.openOffice.converter.openofficedocumentConverter import; / *** doc docx 형식 변환*/ public class docconverter {private static final int 환경 = 1; // 환경 1 : Windows 2 : Linux 개인 문자열 filestring; // (pdf22SWF 경로 만 포함) 개인 문자열 출력 경로 = ""; // 입력 경로, 출력은 기본 String filename; 개인 파일 pdffile; 비공개 파일 Swffile; 개인 파일 Docfile; public docconverter (String filestring) {ini (filestring); } / ** * 파일 재설정 * * @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 = 새 파일 (Filestring); pdffile = 새 파일 (filename + ".pdf"); swffile = 새 파일 (filename + ".swf"); } / ** * PDF로 변환 * * @Param 파일 * / private void doc2pdf ()는 예외를 {if (docfile.exists ()) {if (! pdffile.exists ()) {OpenOfficeConnect Connection = New SocketOpenOfficeConnection (8100); try {connection.connect (); DocumentConverter Converter = New OpenOfficedOcumentConverter (Connection); converter.convert (docfile, pdffile); // 연결을 닫습니다. System.out.println ( "**** PDF 변환이 성공적입니다. PDF 출력 :" + pdffile.getPath () + "****"); } catch (java.net.connectexception e) {e.printstacktrace (); System.out.println ( "**** SWF 컨버터 예외, OpenOffice 서비스가 시작되지 않았습니다! ****"); e 던지기; } catch (com.artofSolving.jodConverter.openOffice.connection.openOfficeException e) {e.printstacktrace (); System.out.println ( "**** SWF 컨버터 예외, 변환 파일을 읽는 ****"); e 던지기; } catch (예외 e) {e.printstacktrace (); e 던지기; }} else {System.out.println ( "**** PDF로 변환되었으며 전환이 필요하지 않습니다 ****"); }} else {System.out.println ( "**** SWF 변환기 예외, 변환 해야하는 문서는 존재하지 않으며 변환 할 수 없습니다 ****"); }} / ** * SWF로 변환 * / @SuppressWarnings ( "UNISS") Private void pdf2swf ()는 예외 {runtime r = runtime.getRuntime (); if (! swffile.exists ()) {if (pdffile.exists ()) {if (환경 == 1) {// Windows 환경 처리 시도 {process p = r.exec ( "d :/program files/swftools/pdf2swf.exe" + pdffile.getpath () + "-o" + swffile.getpath () + "); 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 (); e 던지기; }} else if (환경 == 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 (예외 e) {e.printstacktrace (); e 던지기; }}} else {system.out.println ( "**** pdf가 존재하지 않으며 변환 할 수 없습니다 ****"); }} else {system.out.println ( "**** swf는 이미 존재하며 ****를 변환 할 필요가 없습니다."); }} 정적 문자열로드 스트림 (inputStream in)은 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 convert () {if (swffile.exists ()) {System.out.println ( "**** SWF 변환기가 작동하기 시작하면 파일이 swf ****"); 진실을 반환하십시오. } if (환경 == 1) {System.out.println ( "**** SWF 변환기가 작동하기 시작합니다. 현재 실행중인 환경 Windows ****"); } else {System.out.println ( "**** SWF 변환기가 작동하기 시작합니다. 현재 실행중인 환경 Linux ****"); } try {doc2pdf (); pdf2swf (); } catch (예외 e) {e.printstacktrace (); 거짓을 반환합니다. } if (swffile.exists ()) {return true; } else {return false; }} / ** * 반환 파일 경로 * * @param s * / public string getSwfpath () {if (swffile.exists ()) {String tempstring = swffile.getPath (); tempstring = tempstring.replaceall ( "///", "/"); 반환 온도; } 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 = 새 파일 (outputpath + realName + ".swf"); } else {swffile = 새 파일 (outputPath + realName + ".swf"); }}}}6. 배포 및 릴리스
Tomcat을 시작하고 현재 웹 응용 프로그램을 배포하십시오
아래와 같이 주소 표시 줄에 http : // localhost : 8080/ctcesims/documentupload.jsp를 입력하십시오.
미리보기 버튼을 클릭하면 아래 그림과 같이 미리보기 인터페이스가 생성됩니다.
4. 자주 묻는 질문
SWF가 나타나면 미리 볼 수 없습니다
http://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager04a.html#119065
SWFS가 신뢰 파일 위치로 생성되는 폴더를 설정하십시오.
다음은 Flexpaper 2.1.9의 차이를 제공합니다. 초기화 방법이 변경됩니다. 파일 디렉토리가 프로젝트 디렉토리와 함께없는 경우 첨부 디렉토리를 서버에서 가상 디렉토리로 설정할 수 있습니다.
<%@ page language = "java"contenttype = "text/html; charset = utf-8"pageencoding = "utf-8"%> <%// string swffilepath = session.getAttribute ( "swfpath"). "http://www.w3.org/tr/tr/html4/loose.dtd"> html> html> http-equiv ="content-type "content ="text/html; charset = utf-8 "> <script type ="text/javaScript " src = "js/jquery.min.js"> </script> <script> <script type = "text/javaScript"src = "js/flexpaper.js"> </script> <script type = "text/javaScript"src = "js/flexpaper_handlers.js"> {높이 : 100%; } 본체 {마진 : 0; 패딩 : 0; 오버플로 : 자동; } #flashContent {디스플레이 : 없음; } </style> <title> 온라인 미리보기 시스템 문서 </title> </head> <body> <div style = "위치 : 절대; 왼쪽; 왼쪽 : 50px; 상단 : 10px;"> <div id = "DocumentViewer"> </div> <스크립트 유형 = "text/javaScript"> var startDocument = "paper"; $ ( '##documentViewer'). FlexPaperViewer ({config : {swffile : 'upload/ddd3.swf', 스케일 : 0.6, 줌 타임 : 'easeout', Zoomtime : 0.5, ZoominterVal : 0.2, fitpageOnload : true, fitwidthonload : false, mingscrewasmaxwintow : false, false, false, false, false, false : maxzoomsize : 5, searchmatchall : false, initviewmode : 'portrait', enrenderingorder : 'flash', startatpage : ', viewmodetoolsvisible : true, zoomtoolsvisible : true, navtoolsvisible : true, cursortoolsvisible : true, searchToolsvisible : true, wmode :'glocanchain : '|'s '}; </script> </div> </body> </html> 마지막으로 인쇄 기능과 로고를 제거 해야하는 경우 FLICTPPAPER의 플래시 파일을 다시 컴파일하고 온라인으로 다운로드 할 수 있습니다.
위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.