Введение
Я написал статью о POI Online Preview, в которой также говорится, что использование OpenOffice также может быть сделано. Я представлю его подробно здесь.
У меня есть две логика реализации:
1. Используйте JodConverter (на основе службы OpenOffice) для преобразования файлов (.doc, .docx, .xls, .ppt) в формат HTML.
2. Используйте Jodconverter (на основе службы OpenOffice) для конвертации файлов (.doc, .docx, .xls, .ppt) в формат PDF.
Каждый может понять преобразование в формат HTML, чтобы вы могли просматривать его непосредственно в браузере, что осознает функцию предварительного просмотра онлайн; Преобразование в формат PDF требует, чтобы пользователь установил Adobe Reader XI, поэтому вы обнаружите, что перетаскивание PDF непосредственно на страницу браузера может непосредственно открыть предварительный просмотр, что также реализует функцию онлайн -предварительного просмотра.
Конвертировать файлы в формат HTML или формат PDF
Без лишних слов просто загрузите код.
пакет com.pdfpreview.util; import java.io.file; import java.io.fileinputstream; import java.io.fileOutputStream; импорт java.io.ioexception; import java.io.inputStream; import java.io.OutputStream; import.net.net.nectexception; import.textere.textrem. java.util.date; импорт com.atorofsolving.jodconverter.documentConverter; import com.atorofsolving.jodconverter.openoffice.connection.openofficeConnection; импорт com.atorofsolving.jodconverter.openoffice.connection.socketopenofficeconcenection; com.artofsolving.jodconverter.openoffice.converter.openofficeedocumentConverter;/** *Используйте JodConverter (на основе службы OpenOffice) для преобразования файлов ( *.doc, *.docx, *.xls, *.ppt) в формат HTML или формат PDF. * Перед использованием, пожалуйста, проверьте, была ли служба OpenOffice была включена. Openoffice Имя процесса: Software.exe | Software.bin * * @author yjclsx */public class doc2htmlutil {private static doc2htmlutil doc2htmlutil; / *** Получить экземпляр DOC2HTMLUTIL*/ public Static Synchronized Doc2htmlutil getDoc2htmlutilinStance () {if (doc2htmlutil == null) {doc2htmlutil = new doc2htmlutil (); } вернуть doc2htmlutil; } / ** * Конвертировать файл в html * * @param fromfileinputstream: * @throhs ioexception * / public String file2html (inputstream fromfileinputStream, String tofilepath, type, тип строки) Throws ioException {date Date = new Date (); SimpleDateFormat SDF = new SimpleDateFormat ("yyyyMmddhhmmss"); String Timesfufix = sdf.format (date); String Docfilename = null; String htmfilename = null; if ("doc" .equals (type)) {docfilename = "doc_" + timesfulfix + ".doc"; htmfilename = "doc_" + timesfufix + ".html"; } else if ("docx" .equals (type)) {docfilEname = "docx_" + timesfulfix + ".docx"; htmfilename = "docx_" + timesfufix + ".html"; } else if ("xls" .equals (type)) {docfilename = "xls_" + timesfulfix + ".xls"; htmfilename = "xls_" + timesfulfix + ".html"; } else if ("ppt" .equals (type)) {docfilEname = "ppt_" + timesfufix + ".ppt"; htmfilename = "ppt_" + timesfufix + ".html"; } else {return null; } File htmloutputfile = new File (tofilepath + file.separatorch + htmfilename); File DocInputFile = новый файл (tofilePath + file.separatorChar + docfilename); if (htmloutputfile.exists ()) htmloutputfile.delete (); htmloutputfile.createnewfile (); if (docinputfile.exists ()) docinputfile.delete (); docinputfile.createnewfile (); / *** Создание входного файла из FileInputStream*/ try {outputStream OS = new FileOutputStream (docInputFile); int bytesread = 0; Byte [] buffer = новый байт [1024 * 8]; while ((bytesread = fromfileinputstream.read (buffer))! = -1) {os.write (буфер, 0, Bytesread); } os.close (); fromfileinputstream.close (); } catch (ioException e) {} openOfficeConnection Connection = new SocketOpenOfficeConnection (8100); try {connection.connect (); } catch (connectException e) {System.err.println ("В преобразовании файла есть ошибка, пожалуйста, проверьте, запускается ли служба OpenOffice."); } // Конвертировать документы Converter Converter = new OpenOfficeedOcumentConverter (Connection); converter.convert (docinputfile, htmloutputfile); connection.disconnect (); // Удалить файл слова после конвертации docinputfile.delete (); вернуть htmfilename; } / ** * Конвертировать файл в PDF * * @param fromfileinputstream: * @throhs ioexception * / public String file2pdf (inputStream fromfileInputStream, String toFilePath, тип строки) Throws ioException {date Date = new Date (); SimpleDateFormat SDF = new SimpleDateFormat ("yyyyMmddhhmmss"); String Timesfufix = sdf.format (date); String Docfilename = null; String htmfilename = null; if ("doc" .equals (type)) {docfilename = "doc_" + timesfulfix + ".doc"; htmfilename = "doc_" + timesfufix + ".pdf"; } else if ("docx" .equals (type)) {docfilEname = "docx_" + timesfulfix + ".docx"; htmfilename = "docx_" + timesfulfix + ".pdf"; } else if ("xls" .equals (type)) {docfilename = "xls_" + timesfulfix + ".xls"; htmfilename = "xls_" + timesfulfix + ".pdf"; } else if ("ppt" .equals (type)) {docfilEname = "ppt_" + timesfufix + ".ppt"; htmfilename = "ppt_" + timesfulfix + ".pdf"; } else {return null; } File htmloutputfile = new File (tofilepath + file.separatorch + htmfilename); File DocInputFile = новый файл (tofilePath + file.separatorChar + docfilename); if (htmloutputfile.exists ()) htmloutputfile.delete (); htmloutputfile.createnewfile (); if (docinputfile.exists ()) docinputfile.delete (); docinputfile.createnewfile (); / *** Создание входного файла из FileInputStream*/ try {outputStream OS = new FileOutputStream (docInputFile); int bytesread = 0; Byte [] buffer = новый байт [1024 * 8]; while ((bytesread = fromfileinputstream.read (buffer))! = -1) {os.write (буфер, 0, Bytesread); } os.close (); fromfileinputstream.close (); } catch (ioException e) {} openOfficeConnection Connection = new SocketOpenOfficeConnection (8100); try {connection.connect (); } catch (connectException e) {System.err.println ("В преобразовании файла есть ошибка, пожалуйста, проверьте, запускается ли служба OpenOffice."); } // Конвертировать документы Converter Converter = new OpenOfficeedOcumentConverter (Connection); converter.convert (docinputfile, htmloutputfile); connection.disconnect (); // Удалить файл слова после конвертации docinputfile.delete (); вернуть htmfilename; } public static void main (string [] args) бросает ioException {doc2htmlutil coc2htmlutil = getDoc2htmlutilinStance (); File file = null; FileInputStream fileInputStream = null; file = new File ("d: /poi-test/exportexcel.xls"); fileInputStream = new FileInputStream (file); // coc2htmlutil.file2html (fileInputStream, "d:/poi-test/openoffice/xls", "xls"); coc2htmlutil.file2pdf (fileInputStream, "d:/poi-test/openoffice/xls", "xls"); file = new File ("d: /poi-test/test.doc"); fileInputStream = new FileInputStream (file); // coc2htmlutil.file2html (fileInputStream, "d:/poi-test/openoffice/doc", "doc"); coc2htmlutil.file2pdf (fileInputStream, "d:/poi-test/openoffice/doc", "doc"); file = new File ("d:/poi-test/Weekly Template.ppt"); fileInputStream = new FileInputStream (file); // coc2htmlutil.file2html (fileInputStream, "d:/poi-test/openoffice/ppt", "ppt"); coc2htmlutil.file2pdf (fileInputStream, "d:/poi-test/openoffice/ppt", "ppt"); file = new File ("d: /poi-test/test.docx"); fileInputStream = new FileInputStream (file); // coc2htmlutil.file2html (fileInputStream, "d:/poi-test/openoffice/docx", "docx"); coc2htmlutil.file2pdf (fileInputStream, "d:/poi-test/openoffice/docx", "docx"); }} Процесс преобразования в HTML почти такой же, как преобразование в PDF. Первый называется xxx.html при создании выходного файла, а последний называется xxx.pdf. При выполнении Converter.convert (docinputFile, htmloutputfile);, JodConverter будет преобразовать его в соответствующий файл в соответствии с именем типа файла.
Обратите внимание, что если в основном методе вызываются как File2HTML, так и File2PDF, будет сообщена ошибка. Либо конвертировать HTML или PDF, и вы можете выбрать только один. Кроме того, перед выполнением вам необходимо запустить службу OpenOffice: выполнить программное обеспечение - -ghead -accept = ”socket, host = 127.0.0.1, port = 8100; urp;" -Нофирстартизард в командном окне в каталоге OpenOffice для запуска.
Вышеупомянутые должны представить пакет Jodconverter's Jar. Я надеюсь, что это будет полезно для каждого обучения, и я надеюсь, что все будут поддерживать wulin.com больше.