Лидер:
В процессе распространения Java часто используется для преобразования документов серии Office в PDFS и, как правило, используйте OpenOffice+JodConverter, предоставленные Microsoft для преобразования документов.
OpenOffice имеет как версию Windows, так и версию Linux. Не беспокойтесь о том, что производственная среда является системой Linux.
1. OpenOffice зависит от JAR, возьмите Maven в качестве примера:
<dependency> <groupId>com.artofsolving</groupId> <artifactId>jodconverter</artifactId> <version>2.2.1</version> </dependency> <dependency> <groupId>org.openoffice</groupId> <artifactId>jurt</artifactId> <version>3.0.1</version> </dependency> <dependency> <groupId> org.openoffice </GroupId> <StrifactId> RIDL </artifactId> <sersive> 3.0.1 </version> </depervice> <dependency> <groupid> org.openoffice </GroupId> <Artifactid> </artifactid> <версия> 3.0.1 </Ground> <pery> <Group GroupD> <groupEd> <groupEd> <groupEd> <groupEd> <groupEd> <groupEd> <groupEd> <Группа> <Группа> <Группа> <Группа> <Группа> <Группа> <Группа>) <ArtifactId> unoval </artifactid> <sersive> 3.0.1 </version> </gethyse> <!-Jodconverter2.2.1 должен полагаться на SLF4J-JDK14, в противном случае журналы сообщат об ошибке в исходном коде. Это очень низкая проблема-> <Dependency> <groupId> org.slf4j </GroupId> <artifactid> slf4j-jdk14 </artifactid> <sersive> 1.4.3 </version> </dependency>
2. Чтобы прямо загрузить код, вам необходимо прослушать порт 8100 приложения OpenOffice.
public void convert (file sourcefile, file targetfile) {try {// 1: открыть соединение OpenOfficeConnection Connection = new SocketOpenofficeConnection (8100); connection.connect (); DocumentConverter Converter = new OpenOfficeIedocumentConverter (Connection); // 2: получить формат DocumentFormatregistry Factory = new BasicDocumentFormatregistry (); DocumentFormat inputDocumentFormat = factory .getFormatbyFileExtension (getExtensionName (sourceFile.getAbSolutePath ())); DocumentFormat outputDocumentFormat = factory .getFormatbyFileExtension (getExtensionName (targetFile.getAbSolutePath ())); // 3: выполнить преобразование преобразования. Convert (SourceFile, InputDocumentFormat, TargetFile, OutputDocumentFormat); } catch (connectException e) {log.info ("Отсутствие преобразования документа"); }}3. Примечание. Jodconverter сообщит об ошибке после преобразования документа xxx.docx после версии 2007 года. Все знают, что суффикс 03 - это xxx.doc. Версия 07 будет xxx.docx.
Проверяя исходный код JodConverter, обнаруживается, что DocumentFormat не поддерживает формат XXX.DOCX. BasicDocumentformatregistry. Public DocumentFormat GetFormatByFileExtension (string Extension) поддерживается по умолчанию. Формат DOC используется.
BasicDocumentFormatregistry Class Source Code
// // Jodconverter - Java Opendocument Converter // Copyright (C) 2004-2007 - Mirko Nasato <[email protected]> // // Эта библиотека является бесплатным программным обеспечением; Вы можете перераспределить его и/или // изменить его в соответствии с условиями лицензии GNU Lesser General Public //, опубликованной Фондом Free Software Foundation; либо // версия 2.1 лицензии, либо (по варианту) любую более позднюю версию. // // Эта библиотека распространяется в надежде, что она будет полезна, //, но без каких -либо гарантий; даже без подразумеваемой гарантии // торговой точки зрения или пригодности для определенной цели. Смотрите GNU // Messer General Public Public License для получения более подробной информации. // http://www.gnu.org/copyleft/lesser.html // package com.artofsolving.jodconverter; импортировать java.util.arraylist; импортировать java.util.iterator; импортировать java.util.list; Public Class BasicDocumentFormatregistry реализует DocumentFormatregistry {Private List/*<DocumentFormat>*/ DocumentFormats = new ArrayList (); public void AddCumentFormat (DocumentFormat DocumentFormat) {documentFormats.add (documentFormat); } Защищенный список/*<documentFormat>*/ getDocumentFormats () {return DocumentFormats; } / ** * @param adviness opension * @return the DocumentFormat для этого расширения или NULL, если расширение не сопоставлено * / public DocumentFormat getFormatbyFileExtension (string endension) {if (endension == null) {return null; } String lowerextension = extension.tolowercase (); for (iterator it = documentFormats.iterator (); it.hasnext ();) {documentFormat format = (documentFormat) it.next (); if (format.getFileExtension (). equals (lowerextension)) {return format; }} return null; } public DocumentFormat getFormatByMimeType (String mimeType) {for (iterator it = documentFormats.iterator (); it.hasnext ();) {documentFormat format = (documentFormat) it.next (); if (format.getMimeType (). Equals (mimeType)) {return format; }} return null; }}
Форматы файлов, поддерживаемые в классе реализации по умолчанию DefaultDocumentformatregistry, следующие
// // Jodconverter - Java Opendocument Converter // Copyright (C) 2004-2007 - Mirko Nasato <[email protected]> // // Эта библиотека является бесплатным программным обеспечением; Вы можете перераспределить его и/или // изменить его в соответствии с условиями лицензии GNU Lesser General Public //, опубликованной Фондом Free Software Foundation; либо // версия 2.1 лицензии, либо (по варианту) любую более позднюю версию. // // Эта библиотека распространяется в надежде, что она будет полезна, //, но без каких -либо гарантий; даже без подразумеваемой гарантии // торговой точки зрения или пригодности для определенной цели. Смотрите GNU // Messer General Public Public License для получения более подробной информации. // http://www.gnu.org/copyleft/lesser.html // package com.artofsolving.jodconverter; открытый класс defaultDocumentFormatregistry Extends BasicDocumentFormatregistry {public DefaultDocumentFormatregistry () {final DocumentFormat PDF = new DocumentFormat («Портативный формат документа», «Приложение/PDF», «PDF»); pdf.setexportfilter (documentfamily.drawing, "draw_pdf_export"); pdf.setexportfilter (documentfamily.presentation "Impress_pdf_export"); pdf.setexportfilter (documentfamily.spreadsheet, "calc_pdf_export"); pdf.setexportfilter (documentfamily.text, "writer_pdf_export"); AddDocumentFormat (PDF); final DocumentFormat swf = new DocumentFormat («Macromedia Flash», «Application/X-Shockwave-Flash», «SWF»); swf.setexportfilter (documentfamily.drawing, "draw_flash_export"); swf.setexportfilter (documentfamily.presentation, "Impress_flash_export"); AddDocumentFormat (SWF); final DocumentFormat xhtml = new DocumentFormat ("xhtml", "Application/xhtml+xml", "xhtml"); xhtml.setexportfilter (documentfamily.presentation, "xhtml Impress File"); xhtml.setexportfilter (documentfamily.spreadsheet, "xhtml calc file"); xhtml.setexportfilter (documentfamily.text, "xhtml writer file"); addDocumentFormat (xhtml); // HTML рассматривается как текст при подаче как вход, но как выход также // доступен для экспорта электронных таблиц и форматов презентации окончательный документ html = new DocumentFormat («html», DocumentFamily.Text, «Text/html», «html»); html.setexportfilter (documentfamily.presentation, "Impress_html_export"); html.setexportfilter (documentfamily.spreadsheet, "html (starcalc)"); html.setexportfilter (documentfamily.text, "html (starwriter)"); addDocumentFormat (html); final DocumentFormat odt = new DocumentFormat ("OpenDocument Text", DocumentFamily.text, "Application/vnd.oasis.opendocument.text", "odt"); odt.setexportfilter (documentfamily.text, "writer8"); addDocumentFormat (ODT); final DocumentFormat sxw = new DocumentFormat ("OpenOffice.org 1.0 Текстовый документ", DocumentFamily.text, "Application/vnd.sun.xml.writer", "sxw"); sxw.setexportfilter (documentfamily.text, "staroffice xml (писатель)"); addDocumentFormat (sxw); final DocumentFormat doc = new DocumentFormat («Microsoft Word», DocumentFamily.Text, "Application/Msword", "DOC"); doc.setexportfilter (documentfamily.text, "MS Word 97"); addDocumentFormat (doc); final DocumentFormat rtf = new DocumentFormat («богатый текстовый формат», DocumentFamily.Text, "Text/RTF", "RTF"); rtf.setexportfilter (documentfamily.text, «богатый текстовый формат»); addDocumentFormat (RTF); final DocumentFormat wpd = new DocumentFormat («WordPerfect», DocumentFamily.Text, "Application/WordPerfect", "WPD"); AddDocumentFormat (WPD); final DocumentFormat txt = new DocumentFormat («простой текст», DocumentFamily.Text, "Text/Plain", "txt"); // Установить FilEnterme на «текст», чтобы не позволить OO, чтобы отобразить диалог фильтра ASCII »// Альтернативно Filtername может быть« текст (кодированный) », и FilterOptions, используемые для установки кодирования, если это необходимо, txt.setimportoption (« FileMentame »,« текст »); txt.setexportfilter (documentfamily.text, "text"); addDocumentFormat (txt); final DocumentFormat wikitext = new DocumentFormat ("MediaWiki wikitext", "Text/x-wiki", "wiki"); wikitext.setexportfilter (documentfamily.text, "mediawiki"); AddDocumentFormat (Wikitext); final DocumentFormat ods = new DocumentFormat («Электронная таблица OpenDocument», DocumentFamily.spreadsheet, "Application/vnd.oasis.opendocument.spreadsheet", "ODS"); ods.setexportfilter (documentfamily.spreadsheet, "calc8"); addDocumentFormat (ODS); final DocumentFormat sxc = new DocumentFormat ("openOffice.org 1.0 Электронная таблица", DocumentFamily.spreadsheet, "Application/vnd.sun.xml.calc", "sxc"); sxc.setexportfilter (documentfamily.spreadsheet, "staroffice xml (calc)"); AddDocumentFormat (SXC); final DocumentFormat xls = new DocumentFormat ("Microsoft Excel", DocumentFamily.spreadsheet, "Application/Vnd.MS-Excel", "xls"); xls.setexportfilter (documentfamily.spreadsheet, "MS Excel 97"); AddDocumentFormat (XLS); final DocumentFormat csv = new DocumentFormat ("csv", documentfamily.spreadsheet, "text/csv", "csv"); csv.setimportoption ("filtername", "text - txt - csv (starcalc)"); csv.setimportoption («Filteroptions», «44,34,0»); // Полевой сепаратор: ','; Text delimiter: '' 'csv.setexportfilter (documentfamily.spreadsheet, "text - txt - csv (starcalc)"); csv.setexportoption (documentfamily.spreadsheet, "filteroptions", "44,34,0"); "addDocumentSemat (csvv); Значения ", DocumentFamily.spreadsheet," Text/Spearted -Values "," TSV "); TSV.Setimportoption (" fiLEntryame "," Текст - txt - csv (starcalc) "); tsv.setimportoption (« filteroptions »,« 9,34,0 »); tsv.setexportfilter (documentfamily.spreadsheet, "text - txt - csv (starcalc)"); tsv.setexportoption (documentfamily.spreadsheet, "Filteroptions", "9,34,0"); addDocumentFormat (TSV); final DocumentFormat odp = new DocumentFormat («презентация OpenDocument», DocumentFamily.presentation, "Application/vnd.oasis.opendocument.presentation", "ODP"); odp.setexportfilter (documentfamily.presentation, "Impress8"); addDocumentFormat (ODP); Окончательный DocumentFormat sxi = new DocumentFormat («OpenOffice.org 1.0 Presentation», DocumentFamily.presentation, "Application/vnd.sun.xml.Impress", "sxi"); sxi.setexportfilter (documentfamily.presentation, "staroffice xml (impress)"); addDocumentFormat (sxi); final DocumentFormat ppt = new DocumentFormat ("Microsoft PowerPoint", DocumentFamily.presentation, "Application/Vnd.MS-PowerPoint", "ppt"); ppt.setexportfilter (documentfamily.presentation, "MS PowerPoint 97"); addDocumentFormat (ppt); Окончательный документ формат odg = new DocumentFormat ("рисунок OpenDocument", DocumentFamily.Drawing, "Application/vnd.oasis.opendocument.graphics", "odg"); odg.setexportfilter (documentfamily.drawing, "Draw8"); addDocumentFormat (ODG); final DocumentFormat svg = new DocumentFormat («Масштабируемая векторная графика», «Image/svg+XML», «SVG»); svg.setexportfilter (documentfamily.drawing, "draw_svg_export"); AddDocumentFormat (SVG); }}
Решение: переписать метод общедоступного документов GetFormatbyFileExtension (string Extension) в классе BasicDocumentFormatregistry. Пока имя суффикса содержит DOC, используйте формат документов DOC DocumentFormat
// // Jodconverter - Java Opendocument Converter // Copyright (C) 2004-2007 - Mirko Nasato <[email protected]> // // Эта библиотека является бесплатным программным обеспечением; Вы можете перераспределить его и/или // изменить его в соответствии с условиями лицензии GNU Lesser General Public //, опубликованной Фондом Free Software Foundation; либо // версия 2.1 лицензии, либо (по варианту) любую более позднюю версию. // // Эта библиотека распространяется в надежде, что она будет полезна, //, но без каких -либо гарантий; даже без подразумеваемой гарантии // торговой точки зрения или пригодности для определенной цели. Смотрите GNU // Messer General Public Public License для получения более подробной информации. // http://www.gnu.org/copyleft/lesser.html // package com.artofsolving.jodconverter; импортировать java.util.arraylist; импортировать java.util.iterator; импортировать java.util.list; / *** Переписать FASICDOCUMENTFORMATREGISTIOR FORMAT ФОРМАТ* @Author uguangjun*/ public class basicdocumentformatregistry реализует DocumentFormatregistry {Private List/* <DocumentFormat>*/ documentFormats = new ArrayList (); public void AddCumentFormat (documentFormat DocumentFormat) {documentFormats.add (documentFormat); } Защищенный список/ * <documentFormat> */ getDocumentFormats () {return DocumentFormats; } / ** * @param endension * vensension file * @return the DocumentFormat для этого расширения или NULL, если расширение * не отображается * / public DocumentFormat getFormatbyFileExtension (string extension) {if (endension == null) {return null; } // Unified File Suffix if (extension.indexof ("doc")> = 0) {extension = "doc"; } if (extension.indexof ("ppt")> = 0) {extension = "ppt"; } if (extension.indexof ("xls")> = 0) {extension = "xls"; } String lowerextension = extension.tolowercase (); for (iterator it = documentFormats.iterator (); it.hasnext ();) {documentFormat format = (documentFormat) it.next (); if (format.getFileExtension (). equals (lowerextension)) {return format; }} return null; } public DocumentFormat getFormatByMimeType (String mimeType) {for (iterator it = documentFormats.iterator (); it.hasnext ();) {documentFormat format = (documentFormat) it.next (); if (format.getMimeType (). Equals (mimeType)) {return format; }} return null; }}
Выше всего содержание этой статьи. Я надеюсь, что это будет полезно для каждого обучения, и я надеюсь, что все будут поддерживать Wulin.com больше.