Skip to content

Convert DOCX documents

Manfredi Marceca edited this page Mar 2, 2025 · 5 revisions

DOCX to RTF

  1. Install the DocSharp.Docx package from NuGet

  2. Use the following code:

var converter = new DocxToRtfConverter();
converter.Convert(inputFile, outputFile); // file paths or streams; inputFile may also be a WordprocessingDocument object

To customize the default font and paragraph formatting in case they are not specified in the document, you can access the DefaultSettings property:

converter.DefaultSettings.FontName = "Calibri"; 
converter.DefaultSettings.FontSize = 11; // In points (default is 12)
converter.DefaultSettings.SpaceAfterParagraph = 0; // In points (default is 8)
converter.DefaultSettings.LineSpacing = 1; // In lines (default is 1.15)

DOCX to RTF string

To produce an RTF string rather than directly saving to a file path or stream:

var converter = new DocxToMarkdownConverter();
string rtf = converter.ConvertToString(inputFile);

DOCX to Markdown

  1. Install the DocSharp.Docx package from NuGet

  2. Use the following code:

var converter = new DocxToMarkdownConverter();
converter.Convert(inputFile, outputFile); // file paths or streams; inputFile may also be a WordprocessingDocument object

Since many Markdown processors (e.g. GitHub) don't support base64 images, to enable images conversion you need to set the ImagesOutputFolder and ImagesBaseUriOverride properties. The first one specifies where images are actually saved and should be an absolute directory path, the second one is the first part of an offline or online URI which will be combined with the image file name and written in the Markdown file.
For example, to save images in the same folder of the Markdown document:

ImagesOutputFolder = Path.GetDirectoryName(inputFilePath),
ImagesBaseUriOverride = "", // will produce just the image file name, same as "./"

DOCX to Markdown string

To produce a Markdown string rather than directly saving to a file path or stream:

var converter = new DocxToMarkdownConverter();
string markdown = converter.ConvertToString(inputFile);

Open XML SDK extension methods

The SaveTo extension method can be used to save a WordprocessingDocument object to a separate DOCX, RTF or Markdown document:

using (WordprocessingDocument document = WordprocessingDocument.Create("document.docx", WordprocessingDocumentType.Document))
{
     MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();
     mainPart.Document = new Document();
     Body body = mainPart.Document.AppendChild(new Body());
     Paragraph paragraph = body.AppendChild(new Paragraph());
     Run run = paragraph .AppendChild(new Run());
     run.AppendChild(new Text("Add some text here."));
     document.SaveTo("document.rtf", SaveFormat.Rtf);
}

Clone this wiki locally