Python: Convert Word to RTF and Vice Versa

2023-12-21 01:22:46 Written by  support iceblue
Rate this item
(0 votes)

RTF is a flexible file format that preserves formatting and basic styling while offering compatibility with various word processing software. Converting Word to RTF enables users to retain document structure, fonts, hyperlinks, and other essential elements without the need for specialized software. Similarly, converting RTF back to Word format provides the flexibility to edit and enhance documents using the powerful features of Microsoft Word. In this article, you will learn how to convert Word to RTF and vice versa in Python using Spire.Doc for Python.

Install Spire.Doc for Python

This scenario requires Spire.Doc for Python and plum-dispatch v1.7.4. They can be easily installed in your Windows through the following pip command.

pip install Spire.Doc

If you are unsure how to install, please refer to this tutorial: How to Install Spire.Doc for Python on Windows

Convert Word to RTF in Python

With Spire.Doc for Python, you can load a Word file using the Document.LoadFromFile() method and convert it to a different format, such as RTF, using the Document.SaveToFile() method; Conversely, you can load an RTF file in the same way and save it as a Word file.

The following are the steps to convert Word to RTF using Spire.Doc for Python.

  • Create a Document object.
  • Load a Word file using Document.LoadFromFile() method.
  • Convert it to an RTF file using Document.SaveToFile() method.
  • Python
from spire.doc import *
from spire.doc.common import *
               
# Create a Document object
document = Document()

# Load a Word file
document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.docx")

# Convert to a RTF file
document.SaveToFile("output/ToRtf.rtf", FileFormat.Rtf)
document.Close()

Python: Convert Word to RTF and Vice Versa

Convert RTF to Word in Python

The code for converting RTF to Word is quite simply, too. Follow the steps below.

  • Create a Document object.
  • Load an RTF file using Document.LoadFromFile() method.
  • Convert it to a Word file using Document.SaveToFile() method.
  • Python
from spire.doc import *
from spire.doc.common import *
               
# Create a Document object
document = Document()

# Load a Rtf file
document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.rtf")

# Convert to a Word file
document.SaveToFile("output/ToWord.docx", FileFormat.Docx2019)
document.Close()

Python: Convert Word to RTF and Vice Versa

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Additional Info

  • tutorial_title:
Last modified on Thursday, 25 April 2024 02:05