2010-04-10 7 views
3

Word-XML 파일을 프로그래밍 방식으로 RTF 파일로 변환해야합니다. 일부 제 3 자 라이브러리 때문에 요구 사항이되었습니다. 그렇게 할 수있는 API/라이브러리는 무엇입니까?Word XML을 RTF로 변환

실제로 작업이 필요하기 때문에 언어는 문제가되지 않습니다. 그러나 Java, .NET 언어 또는 Python이 선호됩니다.

답변

2

파이썬/리눅스 방법 :

당신은 (서버에서 당신이 헤드리스 (headless) 모드에서 OO를 실행할 수) 오픈 오피스 우노 신부가 필요합니다. 당신이 모든 OO-쓰기에 모든 OO 읽을 수있는 형식을 변환 할 수있는 결과 :

http://wiki.services.openoffice.org/wiki/Framework/Article/Filter/FilterList_OOo_3_0

실행 예제 코드

/usr/lib64/openoffice.org/program/soffice.bin -accept=socket,host=localhost,port=8100\;urp -headless 

파이썬 예 :

import uno 
from os.path import abspath, isfile, splitext 
from com.sun.star.beans import PropertyValue 
from com.sun.star.task import ErrorCodeIOException 
from com.sun.star.connection import NoConnectException 

FAMILY_TEXT = "Text" 
FAMILY_SPREADSHEET = "Spreadsheet" 
FAMILY_PRESENTATION = "Presentation" 
FAMILY_DRAWING = "Drawing" 
DEFAULT_OPENOFFICE_PORT = 8100 

FILTER_MAP = { 
    "pdf": { 
     FAMILY_TEXT: "writer_pdf_Export", 
     FAMILY_SPREADSHEET: "calc_pdf_Export", 
     FAMILY_PRESENTATION: "impress_pdf_Export", 
     FAMILY_DRAWING: "draw_pdf_Export" 
    }, 
    "html": { 
     FAMILY_TEXT: "HTML (StarWriter)", 
     FAMILY_SPREADSHEET: "HTML (StarCalc)", 
     FAMILY_PRESENTATION: "impress_html_Export" 
    }, 
    "odt": { FAMILY_TEXT: "writer8" }, 
    "doc": { FAMILY_TEXT: "MS Word 97" }, 
    "rtf": { FAMILY_TEXT: "Rich Text Format" }, 
    "txt": { FAMILY_TEXT: "Text" }, 
    "docx": { FAMILY_TEXT: "MS Word 2007 XML" }, 
    "ods": { FAMILY_SPREADSHEET: "calc8" }, 
    "xls": { FAMILY_SPREADSHEET: "MS Excel 97" }, 
    "odp": { FAMILY_PRESENTATION: "impress8" }, 
    "ppt": { FAMILY_PRESENTATION: "MS PowerPoint 97" }, 
    "swf": { FAMILY_PRESENTATION: "impress_flash_Export" } 
} 

class DocumentConverter: 

    def __init__(self, port=DEFAULT_OPENOFFICE_PORT): 
     localContext = uno.getComponentContext() 
     resolver = localContext.ServiceManager.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", localContext) 
     try: 
      self.context = resolver.resolve("uno:socket,host=localhost,port=%s;urp;StarOffice.ComponentContext" % port) 
     except NoConnectException: 
      raise Exception, "failed to connect to OpenOffice.org on port %s" % port 
     self.desktop = self.context.ServiceManager.createInstanceWithContext("com.sun.star.frame.Desktop", self.context) 

    def convert(self, inputFile, outputFile): 

     inputUrl = self._toFileUrl(inputFile) 
     outputUrl = self._toFileUrl(outputFile) 

     document = self.desktop.loadComponentFromURL(inputUrl, "_blank", 0, self._toProperties(Hidden=True)) 
     #document.setPropertyValue("DocumentTitle", "saf") TODO: Check how this can be set and set doc update mode to FULL_UPDATE 

     if self._detectFamily(document) == FAMILY_TEXT: 
      indexes = document.getDocumentIndexes() 
      for i in range(0, indexes.getCount()): 
       index = indexes.getByIndex(i) 
       index.update() 

      try: 
       document.refresh() 
      except AttributeError: 
       pass 

      indexes = document.getDocumentIndexes() 
      for i in range(0, indexes.getCount()): 
       index = indexes.getByIndex(i) 
       index.update() 

     outputExt = self._getFileExt(outputFile) 
     filterName = self._filterName(document, outputExt) 

     try: 
      document.storeToURL(outputUrl, self._toProperties(FilterName=filterName)) 
     finally: 
      document.close(True) 

    def _filterName(self, document, outputExt): 
     family = self._detectFamily(document) 
     try: 
      filterByFamily = FILTER_MAP[outputExt] 
     except KeyError: 
      raise Exception, "unknown output format: '%s'" % outputExt 
     try: 
      return filterByFamily[family] 
     except KeyError: 
      raise Exception, "unsupported conversion: from '%s' to '%s'" % (family, outputExt) 

    def _detectFamily(self, document): 
     if document.supportsService("com.sun.star.text.GenericTextDocument"): 
      # NOTE: a GenericTextDocument is either a TextDocument, a WebDocument, or a GlobalDocument 
      # but this further distinction doesn't seem to matter for conversions 
      return FAMILY_TEXT 
     if document.supportsService("com.sun.star.sheet.SpreadsheetDocument"): 
      return FAMILY_SPREADSHEET 
     if document.supportsService("com.sun.star.presentation.PresentationDocument"): 
      return FAMILY_PRESENTATION 
     if document.supportsService("com.sun.star.drawing.DrawingDocument"): 
      return FAMILY_DRAWING 
     raise Exception, "unknown document family: %s" % document 

    def _getFileExt(self, path): 
     ext = splitext(path)[1] 
     if ext is not None: 
      return ext[1:].lower() 

    def _toFileUrl(self, path): 
     return uno.systemPathToFileUrl(abspath(path)) 

    def _toProperties(self, **args): 
     props = [] 
     for key in args: 
      prop = PropertyValue() 
      prop.Name = key 
      prop.Value = args[key] 
      props.append(prop) 
     return tuple(props) 

if __name__ == "__main__": 
    from sys import argv, exit 

    if len(argv) < 3: 
     print "USAGE: python %s <input-file> <output-file>" % argv[0] 
     exit(255) 
    if not isfile(argv[1]): 
     print "no such input file: %s" % argv[1] 
     exit(1) 

    try: 
     converter = DocumentConverter()  
     converter.convert(argv[1], argv[2]) 
    except Exception, exception: 
     print "ERROR!" + str(exception) 
     exit(1) 
+1

[pyod converter] (https://github.com/mirkonasato/pyodconverter)는이를위한 아주 간단한 스크립트를 제공합니다. – Kato

0

자바

나는 Word Documents을 분석하기 위해 과거에 아파치 POI를 사용했습니다. 그것은 꽤 잘 작동하는 것처럼 보였다. 그런 다음 여기에 some libraries RTF에 쓸 수 있습니다. .NET에서 Word 문서를 작성하는 방법에 대한

닷넷

Here's an article. 나는 당신이 독서를 위해 같은 도서관을 사용할 수있을 것이라고 확신한다.

파이썬 파이썬

Here is an article.

관련 질문 또한

, here is a related if not duplicate question.

0

보기는 Docvert입니다. 데모에서는 공개 문서 만 업로드 할 수 있기 때문에 직접 설정해야합니다.

0

AutoIt을 사용하면 XML 파일을 Word에서 열고 RTF로 저장하는 작업을 자동화 할 수 있습니다.

Word 용 사용자 정의 함수를 사용하여 RTF 파일을 변환 할 일반 텍스트로 저장 했으므로 제대로 작동합니다. 구문은 매우 쉽습니다.

http://www.autoitscript.com/autoit3/index.shtml

0

자바에서을 사용할 수 있습니다.은 변환 및 선택적 채우기를 수행합니다. 오픈 오피스를 통해 포맷 변환을 수행합니다. 오픈 오피스를 설치하고 몇 가지 예제 문서를 수동으로로드하고 저장하면 형식 변환이 충분한 지 여부에 대한 느낌을 받게됩니다. 그렇다면 Docmosis를 사용하여 Docmosis를 Java에서 구동 할 수있다.